How to do inference in a card game?

In the game there are 5 players, each with 8 cards in hand. No other card is present. Using Monte Carlo (MCTS) I run many simulations of the game from the current state to the end of the match. In those simulations adversaries play with very simple dumb rules. When generating a new simulation I assign to them _unknown_ cards with a uniform random distribution. I say a card is _unknown_ if it is not in my hand, it is not on the table and it has not been discarded before, then it must be in someone other's hand. However, uniform random distribution it's not the best way to distribute cards. In fact, sometimes it's straightforward to a human player a reasoning like this: _If he had 3♥ he **probably** would have discarded it the previous turn as it was a **very good** move. Then, it's **very unlikely** that he'll discard 3♥ in hand hereinafter._ Well, before discarding, before generating the Monte Carlo simulations, I would assign to each adversary the set of _unknown_ cards with their probability distribution: { (3♥, 0.20) , (4♥, 0.12) , (5♥, 0.03) ...}. How can I calculate those probabilities? Is there some paper or some ideas where to start from? EDIT: An idea: Computationally talking, would it be a good idea to run a simple Monte Carlo simulation when chosing adversaries' strategy? With _simple_ I mean a rough, fast, simulation which ends in a small time like a second. In this way, the next turn I would have a _measure_ of the goodness of adversaries moves and I can start doing inference from there.


Build a map with city blocks and road

Is there a design pattern or well known algorithm to build a simple map with roads and city blocks? To have an idea of what's my target i describe some of the constraints and the context:   * a matrix which represents a (rectangular) map   * few possible city blocks represented as rectangles (eg, 4x3, 5x2, 1x6)   * few possible road sizes (eg, 1, 2)   * block are never connected, meaning that there is always a road between them the result would be an array like this:               111101111100110     111101111100110     111100000000110     000001110000110     000001110000000     ...      where as for example, "1" are the blocks and "0" are the roads. What I intend to do is to place a block where it is possible, then circumscribe with roads, and go on. This would be ok, but could lead to some place where blocks don't fit. I would like to know if there is something in the state of the art of such algorithms.


Should there be separate database schemas for each developer or should there be just one that all developers share?

During development, should developers each have their own copy of the database to work on ? Or should there be a common shared development database ? The former will give developers more flexibility. For ex., they can run their own regression tests during development and unit testing without worrying about corrupting the data for other developers. However, it is difficult to maintain for database adminstrators. The latter is easier to maintain (less integration overheads as everyone's working on the same schema) but requires more effort to ensure data sanctity (developers should be careful and not make changes that will impact others).


API Development - Sinatra?

I've been tasked to create a mobile application as well as an accompanying website. Both the application and website will interact with the same database. To make things easy, I figure creating an API would be best that way I can separate it out from the mobile application and website. Would this be the preferable method? I'm thinking Sinatra would be best for this situation. I'm using Ruby on Rails for the website but feel it would be overkill for the API. I just want to validate my thoughts regarding this issue. Thanks!


Whether to use -pedantic flag in g++ or not?

I'm learning C++ and I'm using g++ on Linux for practicing. 1) I want to know if people working as programmers use g++ -pedantic flag and also it's importance in real world. 2) What about other compilers, do they also allow this? Has this become some de-facto standard? I'm interested because I'm reading C++ Primer where the author points that its illegal to use non-const expression as dimension in array definition and g++ by default allows it. And there might be other things I'm unaware of.


Java performance of StringBuilder append chains

In Java, if I am building a significant number of strings, is there _any_ difference in performance in the following two examples?               StringBuilder sb = new StringBuilder();          for (int i = 0; i < largeNumber; i++) {         sb.append(var[i]);         sb.append('=');         sb.append(value[i]);         sb.append(',');     }      or               StringBuilder sb = new StringBuilder();          for (int i = 0; i < largeNumber; i++) {         sb.append(var[i]).append('=').append(value[i]).append(',');     }      Thanks!


Algorithm / working approach to get a random list of data

I am working on a android schedule app but that isn't matter , the problem is a algorithm / methodology so you are welcome to just write the pusedo code to answer. The data is like this               Place      =============     Name     lat      lng     duration     isBookMark     type      Note: There are **only** two type: Shop, Park, duration is the time base on hour e.g. 1 => 1hour, 0.5 hour etc.... lat lng are the location unit So, I would like to generate a random place list based on the following criteria:   1. There are 2 duration limit     * if short limit, then I need to get exactly 1 Park and some Shop, based on the hour 3-5 is given     * if medium limit, I need to get exactly 2 Park and some Shop, based on the hour 6-8 is given     * if long limit, then I need to get exactly 3 Park and some Shop, based on the hour 9-11 is given   2. The user can select whether the bookmarked item is higher priority, so it may need to handle bookmark higher priority when select the item.    3. Also, the next place chosen must be the nearest place. You can assume there is already a `calcuateDistanceDiff()` function available  So, how to generate a list in the above case? I have tried to simply like "hardcode" to handle the duration limit one by one e.g. get one Park first and get the next by checking the priority / distance one by one , but there should be some more wise way to create a more generic "methodology" to handle this, in terms of better performance and elegant.


Will taking a year out reduce my employability

I'm just coming to the end of my BSc Computer Science degree, and I'm faced with a choice. My dream has always been to do independent game development, and I'm considering taking the next year to try at indie game dev. If it works, that's cool and I can carry on, if it fails I'll try looking for another job. However, one of my friends suggested that doing this would massively hurt my employability, which would not be good! Will it?


Android proprietary app including Apache-2.0 licensed code from Google

My Android app contains some Apache-2.0 licensed code from Google (in-app billing example) and links to `com.android.vending.billing` library in the form of a `InAppBillingFile.aidl` file (same license?). I would like to know what I have to do for my app to be license compliant, i.e. what to show in the About section, what files to include and so on?


Organizing an image processing pipeline for on-the-fly video analysis

I'm trying to design a system that performs image analysis on video streams from the internet. I have a few rudimentary ideas for how to organize such a system, and I was hoping you guys could critique them and offer suggestions of your own. For clarity, I'm going to present my ideas in the following manner:   1. High-level description of the problem   2. Assumptions and constraints   3. My suggested approach I think this conversation can, for the most part, remain language-agnostic, but FWIW, we're planning on doing this in Go. **I'm looking for a general critique, and advice about how to structure my code.** # 1\. High-Level Description The problem can be generally described as follows: our system is an image processing pipeline that will extract features from video frames with one important caveat: **the remote client will request that a certain subset of proposed analyses be conducted.** In other words, we will offer a variety of analyses, and the client will choose which subset of these analyses he would like us to perform. This is important for two reasons:   1. Image processing is expensive, so we don't want to perform unnecessary computations.   2. Certain high-level features (e.g. facial expression analysis) depend on lower-level features (e.g. face segmentation, person detection, ...) **The goal is therefore to create a pipeline that performs all prerequisite analyses exactly once, but does not perform any superfluous analyses.** # 2\. Assumptions and Constraints A few assumptions and constraints, in no particular order:   1. Frames will enter the pipeline via `stdin`, as base64-encoded byte strings.   2. One process per video stream.   3. Some features can be extracted independently for each frame.   4. Some features require several consecutive frames in order to be computed.   5. We're striving for soft real-time, or at least low-latency. The client is informed of results on-the-fly rather than retrieving them from storage at a later time   6. This service is running on Amazon EC2 (but I think most of the discussion can remain environment-agnostic) # 3\. A Potential(ly stupid) Approach My main concern is in optimizing the pipeline such that all necessary prerequisite computations are performed exactly once and no unnecessary computations are performed. A simple approach would be as follows:   1. Frames are stored in structures with a `feature` hashmap where results of previous computations can be stored.   2. Each possible stage of the pipeline (i.e. "unit of work" that extracts a feature) exists as a structure with methods. Said structure contains metadata information about prerequisite features.   3. At each stage of the pipeline, the frame struct is checked to see if all prerequisites are met. If not, the necessary function is applied and the result is stored in the aforementioned hashmap.   4. The pipeline stage is applied. This solves the problem of not repeating a given computation, but doesn't really define any general pipeline architecture. It's trivial, for instance, to use this method when operating on frames individually, but what about operating on groups of consecutive frames (i.e. a sliding/tiling window over the last _n_ frames)? I eagerly await critiques and suggestions! Thanks in advance!


Is there a Pattern or a Refactoring Method to pull data-loading out of existing Class

I am refactoring legacy codebase. Part of it is a `loadProduct()` function inside a larger "everything" class. `loadProduct()` loads data from a database. I want to move this loading-data part out of the larger class, because I do not think it belongs there. I am not sure exactly where I want to move it yet, but I think that just moving it out into a separate class will do great to start. How do I do this? i.e. Imagine this:               class Big     {         function x() {}         function y() {}         function z() {}         function w() {}              ...              function loadProduct()         {             $sql = "select * from X where Y = $this->p1 and w = $this->p2";             $result = db_call($sql);             ...             $this->a = $result->field_a;          }     }      What I think of so far is:   1. I can create a `Product` class that instantiates and returns the product data. Call it i.e. `$data = new Product($p1, $p2, $p3)`.   2. create a `ProductProvider` class, which has function `loadFromDB()`. Call it:               $pp = new ProductProvider();     $data = $pp->loadFromDB($p1, $p2, $p3);     ...     include 'db.php';     class ProductProvider()     {         function loadFromDB($p1, $p2, $p3)         {              $product = null;              //code to load Product              return $product;         }     }      I think way 2 is a bit more flexible and allows me to add more functions later on, such as loading different sets of data from different sets of parameters. This flexibility may come in useful in case legacy codebase gives me surprises later on. (i.e. say as I refactor I may realize I need to move or group this data-loading piece into or with some other piece of code and code encapsulation Provider will give me should be easy to move elsewhere). Will my 2nd example pattern be a proper* fit for my refactoring example?   * By _proper fit_ I mean industry-accepted best practice, recommended for cases similar to mine.


Core Data: is performing NSFetches in transient property code bad? Why?

In Core Data, we can put transient properties in our entity objects (or categories on our entities). These transient properties can calculate transient data based on actual entity properties. Is putting code that does NSFetchRequests in transient properties over the top and to be avoided? I feel this use is beyond the remit of a transient property, but I'm trying to express why this isn't a good idea. What are the downsides?


How properly perform passing operation result to View

I'm developing web site on self made MVC engine. I have _actionController_ that handles operations like _register_ , _login_ , _post submit_ and etc. _actionController_ receives operation name and parameters. Of course it mast handle errors such _user with same nick already exists_ or _password is to short_ about which action handler have to notify user. The question is which is the best way to organize errors, such that View could easily get localized user notification message. I see two ways First one: define error constants like               ERR_NICK_BUSY = '1'     ERR_NICK_INVALID = '2'     ...      and localization map               local[ERR_NICK_BUSY] = 'User with the same nick already registered'     local[ERR_NICK_INVALID ] = 'Nick, you entered is invalid'     ...      And second one: define abstract constants like               ERR_FIELD_BUSY = '1'     ERR_FIELD_INVALID = '2'     ...      and pass them with field name. In this case localization looks like               local['nick_'+ERR_FIELD_BUSY] = 'User with the same nick already registered'     ...      I don't like both this methods. Can you advise something else?


Let applications share a database or keep them in sync with web services?

We have decided to build separate applications for user authentication and user management. The reason is that the the former is a "this just needs to always work, and do so instantly" style service, and the latter includes a much-larger user-interface component with many requirements and features. Unfortunately, while white-boarding, prototyping, and getting more information about required features, we discovered that they need to share several types of information. For example, both apps need to know whether a user is locked out or needs to reset their password. We are considering connecting the applications to the same database. We considered using web services for communication, but that has a higher up- front cost, is more complex, and will have worse performance (assuming the same query will be made in either case). We'd have to keep some pieces of information in sync across two database instances, which is obviously not an optimal setup. On the other hand, sharing the database instance would require the ORM's entity schemas to stay in sync somewhat (even if we weren't using one, we'd still need to make sure our queries still worked in both apps whenever the database schema changed). It creates a shared dependency. In addition, the database becomes a single-point of failure/poor performance. In addition, I'm not sure it would be possible to hide irrelevant data from either app, so encapsulation is reduced. Has anyone here worked this dilemma before and gained any insights? I'm sure there are other considerations here that I haven't thought of yet. It's not exactly unusual to have different applications connect to a central database.


Git, auto updating, security and tampering?

I was thinking about hosting my private project on my server (i may use 'gitolite') and have a copy on my local machine as backup (git clone then automated git fetch every few minute). I want to know what happens if there is a bug gitolite or somewhere else on my server and the source code and git repository has been tampered with? Will my backup also be corrupted? will i easily be able to revert the source using the history?


Pointers to implementing a taxonomy system?

I am taking part in the development of a PHP CMS (yeah I know you are like, meeh). It is currently using simple tags for tagging content. What I want to do is push the whole thing to using Taxonomy but I am not sure on what to pay attention to, or how to go about structuring the whole vocabularies/terms. I'd love to be able to keep the user interaction close to that of the current simple tags and at the same time allow for more advanced usage by power users. The Drupal and the Wordpress taxonomy systems are being reviewed at the moment and they provide valuable resources. Nevertheless, it could be that someone has some simpler and more appropriate thoughts on this matter.


What is the origin of sessions, by whom and when were they created?

I know sessions are in PHP, ASP, ASP.NET and probably in many other languages. In most cases session solve a problem which the language itself fails to solve. I am wondering   1. Who created sessions and when were they first introduced?   2. Was it a feature of a particular language first?   3. Is the use of sessions limited to web browsers only? Or are they used in desktop applications as well?


Solving geometric constraints with Minion

I am doing research on squares, and I thought of using constraint- satisfaction-problems solvers for proving or disproving some conjectures. As a simple example problem, consider the following task:               Draw two green squares and two red squares, such that:      - All squares of the same color are interior-disjoint;      - All squares of different colors are interior-intersecting.      To solve this problem, I wrote the following script in the Minion language. To make the program shorter, I used C-style macros:               MINION 3          **VARIABLES**     // There are 2 red squares and 2 green squares.     // for every square, x and y are the south-west corner, and s is the side-length:     DISCRETE xred[2] {1..100}     DISCRETE yred[2] {1..100}     DISCRETE sred[2] {1..100}          DISCRETE xgrn[2] {1..100}     DISCRETE ygrn[2] {1..100}     DISCRETE sgrn[2] {1..100}          **CONSTRAINTS**     // The following macros handle intersection relations between squares.      // Let a and b be names of squares.      // intersect(a,b) defines constraints meaning "rectangle a intersects rectangle b".     // disjoint(a,b) defines constraints meaning "rectangle a does not intersect rectangle b".          // a and b interior-intersect, if ALL the following equalities hold:     //  a.x + a.s > b.x     //  b.x + b.s > a.x     //  a.y + a.s > b.y     //  b.y + b.s > a.y     #define intersect(a,b) \     watched-and({\         sumgeq([x##a,s##a,-1], x##b), \         sumgeq([x##b,s##b,-1], x##a), \         sumgeq([y##a,s##a,-1], y##b), \         sumgeq([y##b,s##b,-1], y##a)})          // a and b are interior-disjoint if they do not interior-intersect.     // We need a special macro for this because Minion does not support negation of constraints.     #define disjoint(a,b) \     watched-or({\         sumleq([x##a,s##a], x##b), \         sumleq([x##b,s##b], x##a), \         sumleq([y##a,s##a], y##b), \         sumleq([y##b,s##b], y##a)\         })          // Squares of the same color must be disjoint:     disjoint(red[0],red[1])     disjoint(grn[0],grn[1])          // Squares of the different colors must intersect:     intersect(red[0],grn[0])     intersect(red[0],grn[1])     intersect(red[1],grn[0])     intersect(red[1],grn[1])          **EOF**      I ran the solver using the following shell command:               cpp myfile > myfile.tmp     minion myfile.tmp      Minion returned the following result               Sol: 1 1      Sol: 1 4      Sol: 3 3           Sol: 1 3      Sol: 3 1      Sol: 2 4       read:   * red #0 starts at (1,1) with side 3;   * red #1 starts at (1,4) with side 3;   * grn #0 starts at (1,3) with side 2;   * grn #1 starts at (3,1) with side 4; This is what it looks like on the plane: ![enter image description here](http://i.stack.imgur.com/GYIgN.png) Indeed, squares of the same color are interior-disjoint while squares of different colors intersect! (Of course there are many other solutions. Minion returns the first solution it finds, which is OK for my needs). Now, my questions are:   * First, do I use the right tool for the task? Is there a way to do what I just did without the need to explicitly define what "intersect" means?   * Second, do I use the Minion language correctly?


Copyright notices/disclaimers in source files

It's a common practice to place copyright notices, various legal disclaimers and sometimes even full license agreements in each source file of an open- source project. Is this really necessary for a (1) open-source project and (2) closed-source project? What are you trying to achieve or prevent by putting these notices in source files? I understand it's a legal question and I doubt we can get a fully competent answer here at programmers.SO (it's for programmers, isn't it?) What would also be interesting to hear is, when you put legal stuff in your source files, is it because "everyone does it" or you got legal advice? What was the reasoning?


What is the best way to allow a client to contribute to a project?

We've been building a CRM for a client. Now that the first major phase has been finished, and a second one agreed upon, the client would like to pick up some of the work, making minor amendments to the database schema and business processes the first phase _while we build the second_. I'm undecided whether this is at all practical, but assuming it is, I'd like some pointers on which measures can be taken to make this at all workable. Here's what I've got so far:   * Until now, the client has _mostly_ seen the project from a user's point of view; clearly, a two-part seminar ought to take place where we introduce him to the inner workings:     * first, showing the existing database schema and, by way of example, extending it,     * then, showing some sample code, and writing a new business process for the schema enhancement.   * The code currently resides in an internal Subversion repository. While we could set up a public one or one on _his_ network (which we can VPN to), I feel a distributed system would work better. I appear to be the only one who feels that way, however, so I could use some good convincing arguments.   * I'm not sure how to mandate/ensure that code that runs in production is committed. Seems like "x made a critical, undocumented change right before going on vacation; now y's trying to figure out this bug that's been occurring ever since" disasters are inevitable. Ideally, all changes, before deployment, would:     * be documented in an issue tracking system,     * occur on a separate testing environment first, and     * have to pass automated tests. Alas, I doubt the discipline for _any_ of those will prevail. Assume that a plug-in architecture or separate project aren't viable options, because 1) the former doesn't exist, and 2) the latter would prohibit the client from looking at and possibly modifying existing code, an ability I believe he would insist on.


How do you mitigate proprietary vendor API issues

Over the past year or so the financial firm I work at has been moving towards converting our COBOL banking core, which is really tailored and custom fit to our business model, to a standardized big box vendor software package (written.. in.. RPG /facepalm). My opinion of the software, along with the IT staff and other programmers was that it really wasn't anything better and wouldn't fit our customers needs (that is the point after all..). Long story short, the project has not been going smoothly and data mapping has been like pulling teeth. I have been rewriting a lot of internal systems to use the new core, and I've run into a big show stopper with their API. I have been going back and forth with the "analyst" who goes back and forth with the programmer (I think, who knows in reality) and I'm getting nowhere fixing this issue. In fact I did get a response that it might be a few weeks to check the scope of the fix, and then months after in order to even fix it. I simply can't find a workaround, and I really would never edit banking database tables directly (ever). **So what do you find most effective at getting the ball moving with vendors fixing their bugs?** Should I fix the RPG code? I am _really_ negligent to go in and try and fix the RPG code because I don't know RPG, and none of my colleagues do either. Really my only other technical fall back is to screen scrape the application at a terminal level, and automate that with some scripting - but that seems extremely hackish. I've already brought this up with the COO, and now the VP, but I don't think they have enough clout with this vendor to get this fast tracked. Should I bring this up as another reason to delay the conversion? It would be a huge shift from an automatic process into a tedious manual entry procedure which would require a lot more man power and I doubt that would go over well.


Simplest token-system for authenticating and authorizating

I want to make Python script that will accept input from Vim and send it to my web-site. So basically I want to make Vim my text-editor for blog articles. Of course, I need to authenticate and authorizate. I wanted to simply ask username and password. My college asked me why not to take login data from file. I answered that I don't want to save password in plain-text. He told me to use tokens! So how to do it? I understand that I need to generate random token for user and knowing it will allow anyone to login. It should be really strong and random so nobody can guess it. Is there something else? Will it be safe to save it in text file? I would like to hear how would you implement it in the simplest possible yet secure way. Some links to literature would be good too!


Why do people suggest not to use instance variable for views in Ruby on Rails

Why do I hear that it is not good to share instance variables between controllers and views. I kind of like it because I can see immediately via the @ that something is coming from the controller. I see a nice way to use helpers in controllers here: http://www.stephencelis.com/2008/09/06/rails- controllers-views-and-variables.html. But I am using cancan for that portion.


What technique to use when trying to drag elements around on a canvas

I want to achieve two things in my java swing application: First, i need a canvas zone where i can drag elements (a rectangle or a circle) from the outside of a pane inside the canvas and place it at the position where they where dropped. also it should be possible to select an element on the canvas and move it around and drop it on another location on the canvas. what techniques would fit best to do such a job? Please leave a comment if something is unclear.


Making the logical jump from complete noob to developer?

I've been programming very lightly for a few years, and not making much progress. It's something that definitely interests me, but I just haven't gotten motivated. Then, I think I figured out what's killing me. All the books I've read, all screencasts I've watched, seem to have missed out on one important thing: How do I go from print statements, variables, etc., to doing more complicated stuff? For example, let's take a site like Posterous. For those who don't know, it's a blogging platform that accepts blog posts via e-mail. The author of the blog has a special @posterous.com e-mail that they send blog posts to, and they are automatically formatted and posted. How would a developer use their toolbox of functions and statements to accomplish something like this on the back end? I'm sorry if this question seems really broad, it's just been frustrating me. I feel like I have a decent grasp of basic concepts, but have no idea how to actually _do_ anything.


Reestimation (ideal hours + elapsed time)

At the beginning of every iteration our whiteboard is covered with "not started" stories estimated in IDEAL HOURS. On a daily basis we update these estimates to keep track of each task's progress. I think we are doing it wrong. The original estimates are in ideal hours and our daily "re-assessment" in ELAPSED TIME. This seems inconsistent, right?! How would you measure your progress towards the end of the sprint?


Adding more responsibilities to Activities in a flexible way

I am considering how I can add tasks to Android Activities in a flexible way. I can only use implementation inheritance for one thing in Java and I would like to use it, if I use it at all, for something else. I think I need to draw the _domain_ first a bit: _Activities_ are UI windows basically, with intrinsic lifecycle responsibilities enforced by the API. The _tasks_ I speak of are UI-visible popovers that do some offline stuff and then disappear. They stem from AsyncTasks. The code of all of this is not a problem, I have this already, even pretty generalized with interfaces. I'm looking at further design improvements I can make. There are many type of activities and they could all work with some types of tasks. _For instance_ a search window would have a task that adds one of the search results, let's say it's a book, to the collection of books in the main application. It allows you to add multiple, hence the popover. A window that displays the collection has a task that lets you export a book to an external file format. It won't stop you from browsing through your collection, yet it needs to display a progress bar as it may take a while to export. A specific Task _exists_ as a nested class in a specific Activity. It needs to be saved away and restored along with lifecycle events: there's a `onSaveInstanceState(Bundle)` and `onRestoreInstanceState(Bundle)` for that, among others. The Activity has a list of active tasks (or just a member for one task). Some UI event will create a new task and add it to the list, a la `onClick(): ATask task = new ATask(); task.execute(something);`. Here's what I have _considered_ so far:   * **Implementation inheritance** Just move this task business to an abstract super class of all specific activities.   * **Decorator pattern** Create a TaskedActivityDecorator that would add this responsibility on any activity. The decorator would have to mimic the entire Activity interface as provided by the API, mostly passthroughs though. So this may already be a bit too heavyweight. It would also need to add the UI events/buttons that launch the task, which may not always be possible if the action is more consequential. But the biggest problem I could come up with here is that Android uses a **manifest** to loosely couple all activities together. Therein you need to declare every specific activity or it can not be used. This is a problem because the decorator would work at runtime, with composition. I can't declare the decorator and add in the information that it needs to wrap a specific activity. With _Android_ I seem to end up with implementation inheritance a lot more than I'd like to. Hence I have too much coupling or code duplication. The activities always easily grow out to big fat classes. Am I correct to say that that is partly because of existing design choices in the Android framework, such as the manifest taking away composition solutions, or the Context object? Am I correct to say that from the get-go it cuts away a significant amount of established design patterns in key areas, including the MVC pattern.   * **Decorator with wrappers** : That I can't specify the decorator and the specific activity it applies to together in the manifest, doesn't mean I can't create classes that represent and arrange this composition. I could of course create many SpecificDecoratorActivity classes, that also implement the Activity interface and act like the decorator, and then wrap in the real specific activity. I'm not sure if it solves my problem though. It seems like a lot of work, a lot of rubbish classes, and takes me far from my original goal.   * **Strategy pattern** : If I can't skin the activity, then I'd better outsource part of its guts. This will give me yet more connections though as the activities will need to know about the Strategy. The Strategy itself however will be more lightweight as a Decorator. Yet it feels not so much like Strategy where there is a choice of which one, but rather just moving part of the class to another class. I would call it TaskManager. And would I still pull up the strategies knowledge into an activity super class?   * **Any other pattern?** : _Which pattern is the best choice? Don't shun your opinion on the specific Android case. No need to talk about tasks specifically._


Compute costs of bad code

I am looking for arguments to convince management to invest effort into refactoring. We log work using Jira and relate every svn-commit to a jira call. My idea is to do the following:   * manually spot an area of code which is extremely bad implemented, but often used: both from User-POV and of Developer-POV (bugfixes)   * get the svn-commits which contain the JIRA-Issues   * filter the issues according to some criteria (issue type, version, prio. etc...)   * compute the time/effort spent on these bugs   * estimate efforts and risks of refactoring   * present the numbers and ask for effort to fix it. What do you think of this? Would such a measurement be useful and/or convincing? What are the Pros and Cons?


Can we use Java for commercial use?

The Java is GPL license (reference from wikipedia). I am not sure I can use it in in commercial projects. I already have a website written in Java and I plan to use this for commercial use. Is that illegal?


Should I obtain a licence from Oracle before developing Java software? I'm in the preliminary planning stages of developing a server on top of the the Hadoop/Java platforms. I'm not much at all worried about the Hadoop side, but the "process" for developing on top of the Java VM is somewhat ambiguous. I was in the process of setting up the JVM on FreeBSD, when I saw that we are only licensed to use it for "personal use". So I thought hmm, what's the situation over in Linux Land? It was even more ambiguous there, and I wasted about an hour on Usenet looking for the answer. Let me clarify my question. I don't care about OpenJDK and much less so interested in fighting Oracle in court (no relation), I'm interested more in Oracle's **policy** towards "Indie" Java developers and by "Indie" I mean a small house of developers under a sole-proprietorship/llc. with no legal team. To be even extra clear, I want to stay on Oracle's good side so if/when my product becomes a success that I don't have to give up the majority of my revenue, or worse, incorporate for quick cash or worse, file bankruptcy and throw away 10 years of work/maintenance. I'm sorry but their legal license is full of double-talk and ambiguous "legal" terms that could mean pretty much anything. I apologize again if this is common knowledge, I come from a C/C++ background and have only been considering Java recently now that the it's becoming the definitive language for distributed computing.


As a professional developer, is it acceptable to not write unit tests?

Just wondering on the pros and cons on TDD/automated unit testing and looking for the community's view on whether it's acceptable for professional developers to write applications without supporting unit tests?


How to improve database schema with different n:m and 1:n associations between users/tasks/comments/attachments

I'm trying to build a database for an upcoming Ruby on Rails webproject. There will be 4 tables minium: tasks, users, attachments and comments. And 1 table to join the n:m relations (tasks <-> users). One task has many users, many comments and many attachments. One comment has many attachments and was created by one user. One attachment was created by one user. Users can have many tasks, many comments and many attachments. A little sketch to illustrate my thougts: ![database scheme](http://i.stack.imgur.com/o0gVu.jpg) The tables with 1:n relations contains the ID from the related table (e.g.: one comment contains the user id) Do you think this scheme follows the normalization rules? Does this make sense or are there any redundancies? I think there is a little problem with the attachment table, cause this must contain a type field and a id field to differentiate between task and comment. And all content types (tasks, comments, attachments) are assigned by many users (tasks) or created by (comments, attachments) one user. Comments are **not** recursive. I've considered the following pseudocode:               tasks = getTasks     each tasks as task              # get task content              users = getUsersByTaskID         each users as user             #get user content              attachments = getAttachmentsByTypeAndTaskID         each attachments as attachment             # get attachment content             user = getUserByID              comments = getCommentsByTaskID         each comments as comment             # get comment content             user = getUserByID             attachments = getAttachmentsByTypeAndCommentID               each attachments as attachment                 # get attachment content                 user = getUserByID      I think it's still a little bit too complicated. Did i overlooked something? Are there better ways to implement my ideas?


How to structure our Javascript so that it is easily editable, testable, and can make calls to render a view without knowing specifics about the view

I am working on a web app that displays some data and uses javascript. Right now, we are serving up parts of our js (to display certain types of information, ie "Render a View") via our server which dynamically writes the java script with the needed data embedded in it using JSPs. Three main points/ requirements we need to consider are:   * We need to be able to easily edit our javascript. (spread through multiple files right now with global variables. can't edit anything with out mabey(no testing framework) breaking everything.   * We want to be able to make calls on the client side to render a view without knowing specifics about the View (in case we add/ change a View).   * We need to test our javascript (for obvious reasons) Currently we have our js very spread around and in large files which makes it hard to make edits. I've been looking into the module pattern to address this concern, but many of the posts I've been reading have been: (a) Older (most recent from 2010) (b) Had some disagreement about how to make modules that are also testable Any ideas about ways we should change/ restructure our application to accomplish all three goals? do these goals have too much inherent conflict, or is there hope? Also, any helpful blog posts are appreciated.


LGPLv3 in closed embedded environment

I'm thinking of using a LGPLv3 library in a closed source commercial program running in a closed embedded environment. According to what I know from LGPLv3 licensing, I can use it as long as the closed source software dynamically links with the LGPLv3 library and leaves the freedom to the user to change or update the LGPLv3 library by changing the library binaries. Since my software runs in a closed, controlled, validated environment, it would be really odd to respect the part of allowing the user to change the LGPLv3 library. I could add a functionality to my environment allowing to update the library binaries, but it would be odd to present this functionality to our customers since they would have no interest into changing that library and would see that as a security hole, so they'll want us to remove it (or restrict the access to no one). Is adding an update binary functionality the only way to respect LGPLv3 ? If by using it, I require to call my company to give access to it (by a password), Will I still respect the license ?


What is the name of ** in python?

When programming Python I sometimes do a `**` to make a conversion. I understand what it does but what data structures am I manipulating? A `dict` and what is the other? An `array`? Is there a name for the `**` operator?


How do you make money from html 5 games (i.e sponsorships)?

I make games with Flash and I am interested in making games in html but I haven't seen any companies or websites which are willing to buy these games (i.e game sponsorships). I was hoping somebody could tell me about a company who would do this or why people don't buy html games?


Client-side oriented website approach name (less server-side code, more client-side code)

I have a terminology question. I was searching about tips to design a website that is using less server-side code and more client-side code, and realized I don't really know which exact term to search if there is one. Example: Maximizing CDNs usage for library, using widgets when possible, integration of client-side social-media SDKs. So my question is not about tips themselves, but about the existence of such a term. Edit: I already know about SPAs and Client-Side Javascript Frameworks. This is what brings me to wonder if there's a name to an approach where you focus on client-side code at a point that you maximize external resources.


design pattern for describing a variable subpart of a config file

Suppose I have an XML _config_ file like the following:                 <myapp>         <settings/>              <output>                  <mailto>mail service configuration parameters</mailto>                                OR                         <smsto>sms service configuration parameters</smsto>                      <output>      While the settings node will have always the same structure, the output node may have different structures, depending on whether it is a mail or an SMS output. The Java classes will be:               class MyAppConfig {              String settingXXX;              {what type?} output;          }      Obviously I will have a `class MailTo {}` and a `class SmsTo {}`. Since output may either be a `MailTo` or a `SmsTo` object, it can be:   * an Object type, since `MailTo` and `SmsTo` don't have any superclass in common.    * an `Output` interface, that in turn is implemented by MailTo and SmsTo. Since `MailTo` and `SmsTo` don't have anything in common, `Output` interface will be empty and will "collapse" to a marker interface.  I think that, given this situation, this is the only implementation possible.   The client code will typecast `Object` or `Output` to `MailTo` or `SmsTo`, that must be handled differently.   Nevertheless, I'm puzzled because design patterns (GoF book) seem not consider this kind of situations.   What is the "real world" pattern that you would apply in this case?


Is there a freelance website dedicated to high-end work, like writing compilers?

I've read through the previous posts on freelance websites and used most of them. I'm looking for a website dedicated to high-end professionals and high- end work. Such as writing software compilers, designing database engines, etc. Probably no such website exists (there would have to be some kind of moderation), but I'm really hoping there is one, both as an employer and as a developer.


New website - best practice for requirements specs?

> **Possible Duplicate:**   >  Extracting user requirements from a person who does not know how to express > himself As a hobby freelancer I'm new to this. I've never had a non-technical client before explain to me what his future website is supposed to do. A person wants me to make a website for him and he basically explained to me what's it about. However, he's not a technical person and he just doesn't understand what I need to know and how to properly describe/explain it to me. When I ask him how a user is supposed to submit an entry to the website he told me _"He fills out a form."_ , which is not really helping me. This was just an example, it goes on for other sections of the website as well which are a lot harder to explain. The website will be aimed at a specific professional user demographic and I have no clue about their profession and how their industry works. I tried to find some good **Product Requirements Document templates** on Google but none of them really seemed like they could help him understand **how to write it so I can understand what he wants/needs**. Can somebody please give me **a hint on how to deal with such non-technical clients**?


Connected components of a graph using Prolog

Given a corner `x` of an undirected Graph `G` I would like to ask for the connected component of `x`, but my first try does not work as desired. Here it is:               edge( a,b ).     edge( b,a ).          edge( b,c ).     edge( c,b ).          edge( c,d ).     edge( d,c ).          connected( X,X ).     connected( X,Y ) :- edge(X,Y).     connected( X,Y ) :- \+ edge(X,Y), edge( X,Z ), connected( Z,Y ).      And here are my queries and the results:               | ?- connected(b,What).          What = b ? ;          What = a ? ;          What = c ? ;          no          | ?- connected(b,b).             true ? ;          true ? ;          true ? ;          no      Why is corner `b` not connected to corner `d`? Why is corner `b` connected to itself three times? I am afraid of other problems I will get with more complex graphs. Are there any?


Does automatic returning affect performance?

There's a bunch of languages that automatically return the last value in a function (mostly functional) like Ruby, Haskell, Lisp, etc. Does this feature (or what do you call it) affect the performance of these languages?


Why elseif instead of else if?

Few days ago I stopped on some PHP's developers quide (for contributors to particular project) and it stated, that `elseif` must be strictly used instead of `else if` \-- without giving any reason, why? Can someone clarify this? I don't see neither much difference nor any argument supporting this. Info: _I believe, there are more languages, than just PHP, that this problem strikes, that's why I asked here, not on Stack Overflow. Feel free to migrate, if necessary._


How to start and maintain an after-work project

I work as a full time developer. My workplace, however, is very limiting in the technologies and programming languages I can use. All of the work is done in C++. It is clear that C++ is rapidly losing (or maybe already lost) its leading position. (please don't flame me, I have years and years of C++ experience, and I love this language, I am merely stating a fact). I have a few ideas for Java/Android projects as well as a project I would like to implement in C#. I see this as a way for me to stay current with the job market's trends and I hope that it will help me find my next job in a more up to date area. So here's the problem: My normal workday is 10-11 hours, after finishing with the kids and house chores I get about 1-2.5 hours before I am too tired to think, much less code. At that point I am going to bed frustrated, disappointed with myself for not being able to stick with my plans, and then I wake up the next morning to do it all again. I have a few hours more during the weekends but clearly I would need to do something different if I want to reach any of my goals. Is there any way for me to make better use of the time I have? Did any of you guys have a similar problem, and had successfully resolved it?


What are the consequences of immutable classes with references to mutable classes?

I've recently begun adopting the best practice of designing my classes to be immutable per Effective Java [Bloch2008]. I have a series of interrelated questions about degrees of mutability and their consequences. I have run into situations where a (Java) class I implemented is only "internally immutable" because it is immutable except that it uses (immutable) references to other mutable classes. To clarify, if the object were constructed with its references set to immutable classes, the class would be immutable.   1. Do any of the benefits (see below) of immutable classes hold true even by only "internally immutable" classes?   2. Is there an accepted term for the aforementioned "internal mutability"? Wikipedia's immutable object page uses the unsourced term "deep immutability" to describe an object whose references are also immutable.   3. Is the distinction between mutability and side-effect-ness/state important? * * * The "Java Practices" site lists the following benefits of immutable classes:   * are simple to construct, test, and use   * are automatically thread-safe and have no synchronization issues   * do not need a copy constructor   * do not need an implementation of clone   * allow hashCode to use lazy initialization, and to cache its return value   * do not need to be copied defensively when used as a field   * make good Map keys and Set elements (these objects must not change state while in the collection)   * have their class invariant established once upon construction, and it never needs to be checked again   * always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state


Doing a passive job search while employed, dealing with the barrage of messages from untargeted Recruiters, HR people?

I'm currently employed with what is basically a startup company, I took the job to gain more experience on the platform I want to work on. I want to entertain options for possibly moving into a new position with a more stable company but have had some issues when posting my resume (I seem to get a large volume of contact from recruiters, etc) including   * lots of messages from people recruiting for jobs out of my area which I have no interest in   * people recruiting for jobs that are not what I am looking for (for a different language, etc than I currently work on, which I have no interest in)   * within my metro area, people recruiting for jobs that are still far away (its a very spread out, suburbanized area) to where the commute is simply too far for my preference. I've made a few attempts to "put myself out there" to open some lines of communication but then I start getting a lot of calls to where I can't reasonably even answer the phone during the day or I wouldn't get much work done. What I am asking is what steps I should take to narrow down the amount of people contacting me, I figure I could try taking out any keywords for other languages form my resume (even though I had them in there originally to show a diversity in previous experience) and specifically stating my preference on location, commute, etc but I am not sure they will actually read this to heed my expectations. I've taken the stance that I'd like to be able to talk to them via email first just to narrow down whether this is even a position that makes sense for me to pursue. They always seem to just want to get me on the phone without providing any info upfront, sometimes they will leave a phone message then email me later (after I don't call them back). Should I just email them back basically with a few initial questions and say that I'm not able to talk on the phone until I know if its even a possible fit? I'm rambling a bit here but I guess I am wondering how not to turn off the people who may have good opportunities but also be protective of my time because there seem to be a lot of recruiters who are just taking the "contact as many people as I can" approach


How do people know the C++ Standard so well?

First of all, this is not a formal C++ question. I have been working with C++ for many years. Most of time, I improve my skill by working on different projects, reading good books, and learning from teammates. My posted questions are frequently answered by some experts here with quotes from the C++ Standard. I am really amazed how people can know the C++ Standard so well that they can immediately find the corresponding guidelines. Here is the question for those C++ experts: Do you guys really read the C++ Standard page by page or you are the persons who had reviewed the standard in the past?


Checking for minimum number of command-line arguments, but allowing help switch

I just ran into an odd scenario. I’m sure that I must have run into the same situation in the past and yet somehow not noticed it until now. I am writing a program that requires at least two command-line arguments. Dealing with this is simple enough, just check that there are sufficient arguments. For example:               A:  if (argc < 3) PrintHelpAndQuit();      However, I also want to allow the user to specifically request the help- screen(s) using a single command-line argument. For example:               B:  if (args[1] == "/?")  PrintHelpAndQuit();     C:  if (args[1] == "/?1") PrintHelp1AndQuit();     D:  if (args[1] == "/?2") PrintHelp2AndQuit();         The problem is that if I put line _A_ first, it ensures that at least two arguments were specified, which prevents then lines _B_ , _C_ , and _D_ from being called, and so the user cannot access those screens. If I put line _A_ after the others, then the program will crash if no arguments are specified (accessing the first member of the argument array is undefined).    There seems to be (only?) two ways to approach this:   * Put the help-screen lines in a conditional block that checks that there is at least one argument (which duplicates the work of line _A_ ):              if (argc > 1) {       if (args[1] == "/?...     }          if (argc < 3) PrintHelpAndQuit();           * Put an extra line at the top that checks if there are no arguments and prints help and quits if so:              if (argc < 2) PrintHelpAndQuit(); // now almost entirely duplicates line A     if (args[1] == "/?...     if (argc < 3) PrintHelpAndQuit();         Both of these approaches are redundant to varying degrees.    How do others deal with this situation? Is there a more elegant (and less redundant) way to require a minimum number of arguments without precluding a single argument?


Looking for a popular, well known example of closed-source software which uses LGPL code, and says so

For advocacy purposes, I'm looking for a good example of some popular/widely- known closed-source and generally paid-for software application/package which uses dynamically linked **LGPL** -licensed libraries, and isn't shy of saying so in its installer dialogs or preferably in its "About" info and/or online documentation once the application is installed. Basically I'm looking for evidence which will back up an argument " _If ...big vendor... doesn't have a problem shipping ...hugely popular SW... with an LGPL dependency, neither should you._ " (Links to any screenshots or online copies of documentation which demonstrate the usage without me needing to actually acquire the software would be most appreciated).


Where is a good starting point for planning Information Architecture for a website?

I am planning a project to develop and enhance an information architecture for a website. This will include navigation structures, content classification, metadata etc.   * Where is the best place to start planning this?   * What software can be used to create this (apart from MS Word?)   * Any tips on how to go about designing a structure?   * What should/should not be included? Hoping you can help.


what should I do?

I am a configuration manager. I did my internship for 6 month before and they hired me for just 3 months now. They hire a new person for CM team today, I am worried they'd kick me out. Right now I maintain their CM software, because they develop it by themself in Oracle. My question is when you're working in a place where they don't pay so much, do you put yuor code free for them? Or as much as they hire you they can use your own code & package? (I mean special package such as get export data in excel). I write program in Oracle forms...


How to get back into software development when you took a 10yr break?

I graduated 2004 CECS and the only experienced I had was at intern for 2 years. At that time I had c and c++ knowledge. I took a 10yrs break and now want to go back into it. I am interested in c#. I have been reading books about c# and some basic programming doodles. Currently trying digest PRO c# 5.0 and the 4.5 .net. What recommendation I need to do to get back into the software field? Should getting a certification Programming in c# Exam 70-483 help me or should I just try to write something to show my current skill and post it on internet?


Overlapping Version Control Repositories

So, I'm working with an open source project, and I'm making some significant changes to a small module of the project. The project uses SVN as its version control, and I need access to this repository, since there is a lot of active development, and I need to be able to get the updates. At the same time, I don't want to commit my changes to the repository until I've finished and tested it, as well as passing the patch file around for comments. I would also like to have my own repository, so that I can have access to version control capabilities, but I don't want to use the SVN repository, since I'd like to keep my changes out of the main branch until it's done. To make things slightly easier, I will not be modifying anything that is currently in the SVN repository, only adding new files. The only way I've thought of doing this so far is to use SVN to track the existing files, and use Mercurial, CVS, Git, or some other version control to track my new files, so in the directory I'm working in, I'd have both a .svn and .hg folder. This is kind of a hassle, though. Does anyone have any other suggestions for how to do this?


Free Typescript editor with definition based code completion feature

I know that a plugin for Visual Studio exists. However i can't afford VS so i'm looking for a free alternative which can be used to code TypeScript and aware of the .d.ts definition files and can do code completion based on them. I know that Sublime Text and VIM can do syntax highlighting with the correct language definition file. However the biggest advantage of Typescript for me is that ability to give code assistance while coding. Are you aware of any editor which can do this? I'm interested even if it's in an experimental state.


Can a flow diagram have more than one start?

I'm drawing a flow diagram which should visualize the communication between 4 services I created. Now I've got a question I'm not quite sure about. There are two ways the services could be started. Is it allowed to have multiple starting-points in a flow chart? And: do I have to visualize error handling, like a service not being available? I think this doesn't belong in a flow chart, perhaps?


What should be allowed inside getters and setters?

I got into an interesting internet argument about getter and setter methods and encapsulation. Someone said that all they should do is an assignment (setters) or a variable access (getters) to keep them "pure" and ensure encapsulation.   * Am I right that this would completely defeat the purpose of having getters and setters in the first place and validation and other logic (without strange side-effects of course) should be allowed?   * When should validation happen?      * When setting the value, inside the setter (to protect the object from ever entering an invalid state - my opinion)     * Before setting the value, outside the setter     * Inside the object, before each time the value is used   * Is a setter allowed to change the value (maybe convert a valid value to some canonical internal representation)?


Is the UX affected negatively by fully cacheable pages?

I want to have fully cacheable pages in my websites, but one cannot do that if they contain user-specific data, like the userbar or things in the UI that can change depending on the permissions the user has. So I was thinking whether it was possible to pull everything that is user- specific via ajax, and update the UI accordingly. But I'm worried that this might be annoying for the user, and also it might be difficult to develop. What do you think? Is there a pattern or something I can follow to deal with this?


Architecting an organization's web strategy. What is the preferred method here?

I'm working on a solution for an organization that needs to last them long term (as subjective as that is). They currently have a Joomla installation whereby the CMS talks directly to the database, from there I have started "bolting on" the additions that they need for their environment (mobile app, kiosk, and lobby display). I've also started writing a RESTful service to talk to Joomla (not the joomla database) and the apps. Here's a diagram of how it's currently going. ![current architecture direction](http://www.gliffy.com/pubdoc/3221299/L.png)   **_note:** they already have the "public & admin" as well as the central db, google cal, email, and vimeo_ Since I'm just getting started with this, I'm thinking that I should probably push for an appropriate design from the ground up. I'm suggesting this so that they have a good foundation moving forward. Here's my suggestion to them ![proposed architecture](http://www.gliffy.com/pubdoc/3221292/L.png) Being that they already have some pieces in place, is it worth pushing for a new architecture? Also, am I on the right track with regards to the new architecture? Lastly, it's worth noting that they're not totally satisfied with Joomla and are looking for a possible rebuild for that portion of their project anyways.


Is it fair to require copyright assignments from contributors of an OS project?

As a follow up to Does a BSD-licensed project need a signed statement from each contributor?: There are several reasons why an open source project might want to get copyright assignments from its contributors. For example:   * To allow the project author to sue for infringement (as only the copyright holder can do so). This is also why FSF requires such an assignment.   * To prevent future problems with the contributors, such as they claiming later that they didn't release their contribution under the same OS license. Another reason is if a company releases its software under (L)GPL and also sells it under a commercial license. Then a copyright assignment is necessary so that the company can include contributions under the commercial license. If the contributors are informed beforehand, this is fair. But if the company has the copyright to everything, it can do basically anything with the sources, something that the contributors wouldn't agree on. It can switch to another license, like from (L)GPL to a non-copyleft license, or even stop releasing the project as open-source and switch to proprietary licensing only. This has reportedly happened with SourceForge. So what is a fair way to handle the problem? If the project owner doesn't get copyright assignments, (s)he can get into problems in the future. If (s)he does, the work of the contributors can lose its license or open-source status. Is there a solution to this dilemma that is fair to both sides? As I'm not a native speaker, I might used wrong legal terms. Please feel free to correct the question. Related:   * How to get contributors assign copyright for copyright holder?.   * Copyright assignment on open source projects


Why is Encapsulation considered a primary principle in OOP?

I am currently trying to understand more deeply the 4 principles of OOP: Abstraction, Encapsulation, Inheritance, and Polymorphism. After studying the four principles, I don't fully understand why Encapsulation is considered one of the four primary principles of OOP. Encapsulation is extremely common and useful in OOP, but it seems to me as more of a technique or strategy to use as part of Abstraction. A good definition for Abstraction: _'Abstraction is the concept of **moving the focus from the details** and concrete implementation of things, **to the types (i.e. classes), the operations available (i.e. methods)** , etc, thus making the programming simpler, more general, and more abstract.'_ Encapsulation, on the other hand, is this: _' **Hiding the internal implementation details of a class** from the outside software world, and prividing an interface for other software entities to communicate and manipulate that class.`_ If so, it seems to me that Encapsulation is mostly a technique to make things more abstract in the software system. Thus, it acts more of a strategy that implements the concept of Abstraction, rather than a primary principle by itself. It could be considered a 'principle' and not only a technique, but it still would be a part of the more general Abstraction principle, and not a major principle by itself. Does anybody agree? If I'm wrong, please explain why.


What conclusion to be drawn from no difference in generated assembly from 2 rather different programs?

I might not have had a counterexample when I got the reply "A pointer is just an address, what's the difficulty?" but I didn't really buy such a simple explanation and at assembly code it's not obvious what's a pointer for 2 different C programs that generate the same assembly.                cat pelle.s valle.s          .file   "pelle.c"         .text         .globl  main         .type   main, @function     main:     .LFB0:         .cfi_startproc         pushl   %ebp         .cfi_def_cfa_offset 8         .cfi_offset 5, -8         movl    %esp, %ebp         .cfi_def_cfa_register 5         movl    $0, %eax         popl    %ebp         .cfi_def_cfa 4, 4         .cfi_restore 5         ret         .cfi_endproc     .LFE0:         .size   main, .-main         .ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"         .section    .note.GNU-stack,"",@progbits         .file   "valle.c"         .text         .globl  main         .type   main, @function     main:     .LFB0:         .cfi_startproc         pushl   %ebp         .cfi_def_cfa_offset 8         .cfi_offset 5, -8         movl    %esp, %ebp         .cfi_def_cfa_register 5         movl    $0, %eax         popl    %ebp         .cfi_def_cfa 4, 4         .cfi_restore 5         ret         .cfi_endproc     .LFE0:         .size   main, .-main         .ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"         .section    .note.GNU-stack,"",@progbits      1) An address to a variable is `&var1` and the pointer is `int* var1` written differently than the address. 2) When I compile 2 C programs where the only difference is pointing then there is no difference in the assembly:               $ diff pelle.c valle.c ;cat pelle.c valle.c;diff pelle.s valle.s      3c3     < int * pelle;     ---     >  int valle;     #include <stdio.h>     int main(void) {     int * pelle;         return 0;     }     #include <stdio.h>     int main(void) {      int valle;         return 0;     }     1c1     <   .file   "pelle.c"     ---     >   .file   "valle.c"      But what conclusions can be drawn from no difference in generated assembly to investigate the "simple and obvious difference" between a pointer declaration and other type? Is the simplistic answer right all along, a pointer is just a variable and there's no point in more analysis? Or that the difference between a pointer and a variable is a case of "sugar" since the types are removed at assembly level where there is no difference? Will a difference in the generated assembly show a diff if I use pointers as arguments to a function and there will indeed be a difference for some pointer usage and this example is too trivial and can't be generalized? So when types are removed in the generated assembly, can I conclude that type difference indeed will result in a difference i nthe generated assembly for a non-trivial example e.g. pointers as arguments and this example is not very good since it looks like the generated assembly disregards typing, while type difference such as this will make a difference in generated assembly for another example?               int valle;     int * pelle;           Assembler          .data     .align 2     .global valle     valle: .word 0          .data     .align 2     .global pelle     pelle: .word 0


Rules for doctypes

After going through a lot of articles and this post, i know Why doctypes are used for and also about the different modes triggered by the browser like standards, quirks etc. I downloaded the a strict doctype from this url - http://www.w3.org/TR/html4/strict.dtd but couldn't understand a thing of what is written inside it. My question is, if i want to write a page with html and css which is going to have a doctype that will trigger standards mode, where can i get a clear and simple to understand list of all the rules(for instance, elements and attributes that i should avoid) that my html and css code should adhere to?


Taking an audio file, automatically transcribing it, taking the output, and matching it to a transcript

We have transcripts of around 8000 videos. However, these transcripts do not have any timed text (ie: they are not time coded to the video) We are trying to ascertain whether software exists, or what approach to take to automatically time code the transcript to its associated video. Does software exist to do this? If not, what software approach would you use to accomplish this feat?


Is there an established software taxonomy that's based on the type of software?

I'm researching engineering approaches to software development based on the type of software, for example:   * Custom one-off software (e.g. space shuttle software)   * Whitebox application requiring customised (e.g. Apache Ofbiz ERP - source code is usually downloaded and customized for each implementation)   * Blackbox application without extension points    * Blackbox application with extension points for customisation (e.g. MS Word, SAP)   * ... Is there an established taxonomy of different types of software based on how the software is implemented?


Using JavaScript to find the correct offset in bundled files

I am currently making multiple parsers using PEGjs and have implemented my own partial preprocessor which using a RegExp finds and replaces '#include' directives with the desired files, resulting in a bundled file. Now I can easily find a problem in my PEGjs syntax if I save this bundled file and then try building the parser, but since I'm working now with multiple parsers, I don't want to take this method, so was making a new preprocessor that saves the start/end offsets into an array that is checked when an error occurs while building the parser and looks for the correct file and calculates the real offset. Iv'e gotten to the part where I can find the correct file, but can't seem to figure out how to calculate the correct offset. Here's a gist link that shows 'the fruits of my labour': https://gist.github.com/futagoza/10520299   The part where I'm calculating the correct offset is the function 'buildPosDetails' on line 47 (it's easy to tell I'm bad at maths :D)


Is it a good idea to register views and view models as singletons in an IOC container?

I understand the benefits of injecting dependencies into objects, but have not found much guidance on the types of objects to inject and when to make them singletons. If we take as as example an application with the following types of objects:   * Services (including repositories and business services such as calculateprice)   * Views    * ViewModels **Services** Injecting services is the typical example given and it is clear these are not registered as singletons in the container as they are statelesss. Was it the original intention that only services should be injected by containers? **Views/ViewModels & other stateful long lasting objects** The general way to access a long lasting object in several places has been to use a registry (or similar), assuming we cannot pass it around as a parameter. Now we have the option to register the object as a singleton in a container and inject it where needed. I can't see any problem using the singleton in a container approach beyond the issue of removing the object from the container when its lifecycle ends (not sure how easy that is going to be - I use Unity). Would be interested to hear of any problems others can forsee. As an interesting aside, the MVVM Light framework uses a ViewModelLocator rather than injecting viewmodels.


What's a good way to prepare for this course titled "Programming Language Security"?

I have a course with the following description: > The purpose of this course is the study of programming language security > features and languages designed to support it explicitly. Static and dynamic > constructs for security in languages and systems, as well as software > engineering security principles/patterns. > > Topics: > >   * Basic Programming Language security framework. >   * Designing secure programming languages >   * Access control in programming languages >   * Information flow languages >   * Capability Languages >   * Mobile programming languages >   * Software Engineering and Security >   * Basic software vulnerabilities in systems >   * Secure Software Engineering life-cycle >   * Patterns, and Practices for software security > I'm confused - How is PL security different from regular security? I'm looking for possible textbooks/books to study, or websites that are good in this topic, or any advice/tips. The professor told me to know C and Java well, that's all I know so far. I appreciate any tips or advice.


I need help designing a long running job processing server

I'm about to propose a new architecture for several pieces of the system I'm working on; it's going to entail getting a lot of number crunching and data translation jobs off of tomcat, and on a more fitting platform and I need a little advice. First, the way this system is currently setup: There is an AS400 and a PostgreSQL database; some of those tables need to be synchronized at various points in the year. An administration application running on Tomcat6 would have a button, "Synchronize" and the struts action class will spawn a new thread to run the job. The job can take anywhere from 15 seconds to 4 days (this is the maximum time we have experienced so far). I do not like this design. Tomcat is a web server, not a job processing server. So, the solution I have in mind is to take one of our unused servers and put Jboss 7 on it. then have a simple interface on that job processing server (e.g. web, JMS) that would listen for triggers. when someone clicks on the "synchronize" button on the web page, the job server is sent the signal telling it what job to fire, what parameters are included and to start processing the job. Years ago I designed a similar concept in job processing where I had a JMS queue that would listen for jobs to come in. when a certain task was added to the queue the system would fire off and run that task. But on that system the jobs would never take more than 5 or 6 seconds, not several days so I'm not sure that JMS Queues would be the best fit here. I looked at Quartz but thats more of a recurring task scheduling system. Although I know I can code around that and make it work, I'm still wondering if thats the best tech for the problem. Do you have any suggestion?


MVC 5 - Best practice for handling dates inside and outside the USA

I have an MVC 5 application that will be used world wide. A number of the pages in the app will require users to enter dates. I'll be using the jQuery datetimepicker plug-in to allow the user to select dates. Or they can enter them manually. I'm curious what the best practice is for cultures where dates are entered in the dd/mm/yyyy format instead of mm/dd/yyyy? I could require all dates to be entered in mm/dd/yyyy format, which is the format my app is expecting, but I also don't want to cause too much angst with my users in other parts of the world.


Tight Coupling Between Javascript, HTML, and CSS: A More Modern Approach?

It's very common to see Javascript bound to certain selectors to find elements, store data, and listen for events. It's also common to see these same selectors used for styling. jQuery (and its selector engine Sizzle) support and promote this by referencing elements with CSS-type syntax. As such, this technique is particularly difficult to 'unlearn' (or refactor) when building out projects. I've come to understand that this is a result of the history of HTML and Javascript development, and that browsers have been built to efficiently consume / parse / and render this sort of coupling. But as websites become increasingly complex, this reality can introduce difficulties in organizing and maintaining these separate layers. **My question is: can and should this be avoided in modern websites?** If I'm new to front-end development, and I wish to learn things 'the right way,' is it worth learning to decouple and avoid such dependencies from the start? Does this mean avoiding jQuery in favor of a library that promotes a more decoupled structure?


Should I Specialize for my Career? Specialist vs Jack-of-all-Trades?

> **Possible Duplicate:**   >  Do Diversified Skills Foster or Hinder Specialization? I am 27 years old and I've been working professionally as a developer for about 4 or 5 years now. I've worked mostly on Web based projects using either PHP or ASP.NET. Recently, I've been doing mobile development at work developing apps for iOS, Android and BlackBerry. I've been bouncing back and forth between languages and technologies, but I feel like it would be hard to present myself to an employer as an expert or demigod in a particular thing. I'm sort of a jack-of-all trades kind of guy. Lately, I've been thinking about specializing in LAMP (CodeIgniter as a framework) for the Web side of things and Android and BlackBerry on the Mobile side. My question is should I be specializing at all? Or should I try to adopt which ever technology the company I'm working with takes on?


Any articles/research/data comparing pre-checkin validation vs post-checkin validation?

I'm currently on a team that uses post-checkin validation in our developers' workflow:   1. Developer checks in code (and hopefully runs tests first)   2. CI machine syncs, builds, run tests   3. If tests fail, code is already checked in but dev (and related people) are made aware (e.g. mail) I've seen or read of several teams who instead use pre-checkin validation (aka "gated checkins"):   1. Dev submits changes (and hopefully runs tests first)   2. Checkin system builds changes and runs test   3. If tests fail, changes are not checked in, and dev is informed of test failures.   4. If tests pass, changes are checked in, and dev is informed. It seems like there's a couple of tradeoffs between these options, such as the turnaround for developers to know if their code is submitted (post-checkin is immediate, pre-checkin waits for the validation to finish), and the known state of code that is checked in (pre-checkin flushes out all issues found by the validation tests, but post-checkin could allow for easily buggy code to get checked in on the Friday afternoon before the dev goes on vacation). Is there any reference material on the tradeoffs/benefits between these two approaches? Or any measured research on whether developers are affected by either one? (E.g. developer productivity is interruptions from pre-checkin validation distracting, since their code is not checked in; or, developers with pre-checkin validation tend to find bugs quicker and can turn around high quality features faster).


Legality of taking ideas from an in-house tool for use in an open source project?

I recently worked for a (UK) medium sized company on an in-house IDE plugin tool. I thought it looked generally useful, but probably needed a different direction to be relevant for people with my interests. I no longer work for that company and I was thinking of making a similar tool for myself using the experience I gained on the project as well as some of the ideas covered. My understanding of things is that they had looked to commercialise it and had discussions with an Intellectual Property lawyer to check if anything was patentable, which didn't apparently result in any patents. I don't think the project will be comercialised as the company specialises in consulting contracts for other companies and has no history of making products. I know I am being vague, but I would like to know if there is anything I should consider (in terms of legality) before I continue. Thanks in advance!


OOP way to design a manager of groups of users

Alright. I have this pattern to model that comes in two variations that are very much the same. I have a class which can be considered an "entry point" which will call a few manager classes depending on the user interaction. We can probably liken it to a controller class. This class should allow the user to manage either groups of users or users themselves. In both cases the operations are quite similar, you can add, modify, remove, view groups and users. Groups have one more operation which is to add users inside them. That's where I am stuck on: My original idea was to model it this way:   1. `class User`,    2. `class Group`,    3. `class GroupManager`,    4. `class UserManager`,    5. `class IManager` However this has the problem of not being able to model the fact that groups need to be able to add users to them. If I put it inside IManager then it is available to UserManager which makes no sense and I put it as a specific method of GroupManager then I am cannot have a single "interface" which is less clean. That led me to skipping entirely the IManager class altogether and only have both managers but then it seems clunky and repetitive. Is there a proper design pattern to apply here ? **TLDR** : What is the proper design pattern where all methods to manage a group or user should have the feel of a "common interface" but still be able to model the fact that groups should be able to add users to themselves.


How to audit an Android application (not rooted) without having access to its source?

How can I check if an Android application running on a not rooted device is "secure" without knowing its source? I would look for:   1. Plain text in Web-Requests (wireshark and emulator)   2. SQL-injection (in EditTexts...)   3. Doing stuff, that isn't always expected (i.e. fast clicking to check for race conditions) Question: What else could be interesting for auditing Android apps?


Decomposing a system in to sub systems, modules and components

This question is about how should a large system be decomposed to sub systems, modules , components etc. For example lets say in a Payroll solution there may be core areas like Attendance, Salary processing, Registries ( for the maintenance of information like employee details, client details, recovery details etc) , Reports and administration. If we take Attendance, its primary objective would be, to give an interface to users to enter/ view/ edit/ delete attendance and monitoring progress of attendance entry. If we are using Model View Presenter architecture in the implementation the entire attendance part could be represented using a single MVP Triad. My question is, should we consider the attendance part of the system as a sub system or a module or a component? To qualify as a sub system should it have more than one modules / components? **EDIT:** I feel that I should have mentioned more about the context of this question. Actually when implementing a system you may not bother about parts whether it's a sub or a module. Also it might depend on personal preferences when calling it. But when you documenting things / preparing manuals etc. I believe we should follow a standard.


When does the "Do One Thing" paradigm become harmful?

For the sake of argument here's a sample function that prints contents of a given file line-by-line. Version 1:               void printFile(const string & filePath) {       fstream file(filePath, ios::in);       string line;       while (std::getline(file, line)) {         cout << line << endl;       }     }      I know it is recommended that functions do one thing at one level of abstraction. To me, though code above does pretty much one thing and is fairly atomic. Some books (such as Robert C. Martin's Clean Code) seem to suggest breaking the above code into separate functions. Version 2:               void printFile(const string & filePath) {       fstream file(filePath, ios::in);       printLines(file);     }          void printLines(fstream & file) {       string line;       while (std::getline(file, line)) {         printLine(line);       }     }          void printLine(const string & line) {       cout << line << endl;     }      I understand what they want to achieve (open file / read lines / print line), but isn't it a bit of overkill? The original version is simple and in some sense already does one thing - prints a file. The second version will lead to a large number of really small functions which may be far less legible than the first version. Wouldn't it be, in this case, better to have the code at one place? At which point does the "Do One Thing" paradigm become harmful?


Standard -server to server- and -browser to server- authentication method

I have server with some resources; until now all these resources were requested through a browser by a human user, and the authentication was made with an username/password method, that generates a cookie with a token (to have the session open for some time). Right now the system requires that other servers make GET requests to this resource server but they have to authenticate to get them. We have been using a list of authorized IPs but having two authentication methods makes the code more complex. My questions are:   * Is there any standard method or pattern to authenticate human users and servers using the same code?   * If there is not, are the methods I'm using now the right ones or is there a better / more standard way to accomplish what I need? Thanks in advance for any suggestion.


how to programtically build a grid of interlocking but random sized squares

I want to create a two dimensional layout of rectangular shapes, a grid made up of random sized cubes. The cubed should fit together and have equal padding or margin (space between). Kind of like a comic book layout, or more like the image attached. How could I do this procedurally? Practically, I would probably be using Python and some graphic software to render an image, but I don't know the type of algorithm (or whatnot) I would need to use to generate the randomized grid. ![random cubes](http://i.stack.imgur.com/XDzF3.jpg)


Estimating time for planning and technical design using Evidence Based Scheduling

I'm at the beginning of a development project in a large organization. The Functional Requirements are currently being worked out and documented with our business stakeholders by our Enterprise Design department. I'm required to produce Technical Design Documents and manage the team to actually build the solution. I'm wanting to try Evidence Based Scheduling, but as I understand, part of that is breaking the job down into small tasks that are less than 14 hours in duration, which requires me to have already done the Technical Design. **Therefore, can Evidence Based Scheduling only be used after the Technical Design has been done?** How do you then plan and estimate the time it may take to come up with the Technical Design?


Designing extensible, interactive systems

Steve Yegge's The Pinoccio Problem describes a very special type of program: one that not only fulfills the original purpose of its creators, but also is capable of performing arbitrary, user-defined computations. They typically also host a console, by which one can reprogram the software on runtime, maybe persisting the modifications. I find this problem very hard to reason about - there seems to be a conflict between implementing the 'core modules' of a program, and making the system really implementation-agnostic (i.e. no functionality is hard-coded). **So, how to architecture such a program - what techniques can help? Is it a well-studied topic?**


Software Management Tools for Agile Process Development

We would like to implement the Agile/ Scrum process in our daily software management, so as to provide better progress visibility and feature managements, here are some of the activities that we want to do:   1. Daily stand-up    2. Release cycles of 6 weeks with 3 2-week iterations.   3. Having a product back-log of tasks ( _integrate with bugzilla_ ) and bugs estimated out.   4. Printing a daily burn down to make velocity visible. When used as motivator, it's great.   5. Easy feature development tracking and full blown visibility, especially for the sales and stake holders ( this means that it must be a web based tool).   6. **My team is distributed, so physical whiteboards aren't feasible.** Is there such a web based tool that meets our needs? I heard icescrum may be one, but I've never used it so I don't know. There are a few more suggestions as here, but I've never heard of them, anyone cares to elaborate or suggest new tools?


Running multiple versions on the same .NET website

I have a website (which is actually mainly a Web API site) and I'd like to be able to simultaneously access multiple versions of it. What I'm currently doing is creating a new website for each version under IIS and referring to sync2.site.com, sync3.site.com etc. This solution is not very scale able nor maintainable. How to quickly add more "versions" of this app and access them using something like `sync.site.com?version=3`?


Worried about memory leak in DLL that creates a dynamic sized array

I have a wrapper DLL that interfaces to another DLL that contains the following function:               char * Foobar(void)     {              // BLAH is the function from the DLL this wrapper interfaces too         char *array = 0; // Set up an array pointer for dynamic memory allocation.         int NumOfChar = 0;              // Build array         for (int n=0; (*(BLAH+n) != '\0'); n++)         {                 NumOfChar++; // keep track of how big BLAH is.         }              NumOfChar++;    // +1 so I can re-add the NULL              // Try to allocate an array based on the size of BLAH This is dynamic...         if (!(array = new char[NumOfChar]))         {                // If there's a problem allocating the memory, pop up a message.             MessageBox (0, "Error: out of memory.", "Crap", MB_OK);          }         else         {             memcpy(array, BLAH,(NumOfChar)); // copy the contents of BLAH to array.         }              array[NumOfChar+1]='\0'; // ensure the last character is a NULL              FreeLibrary(hGetProcIDDLL); // release the DLL              return array;        }      I am calling this DLL from LabVIEW which is don't think is specific to this question, as the DLL can be called by any program. My question is once Foobar returns the pointer to the array, how can I make sure that the array is deallocated afterwards? This seems to be a memory leak, because next time this routine is called, the next array won't necessarily overwrite the old array. It will just use up more and more memory, am I correct in this logic? Thank you


What are the arguments against or for putting application logic in the database layer?

Most software developers want to keep application logic in the application layer, and it probably feels natural for us to keep it here. Database developers seem to want to put application logic in the database layer, as triggers and stored procedures. Personally I would prefer to keep as much as possible in the application layer to make it easier to debug and keep the responsibilities of the layers separate. What are your thoughts on this, and what should or should not be ok to implement in the database layer? **Edit** This question is also covered on dba.se, from the DBAs perspective. As programmers.se & dba.se have different audiences and biases, future readers might want to review both sets of answers before deciding what works best for them.


Is it possible/likely to be paid fairly without a college degree?

Some back story, and then my question: I took a "break" from getting a university education last year to work full time as back end developer on a GIS application at $10.50 an hour. Later that year I was hired on by a fairly prestigious organization on their GIS application for a meager salary + rockin' benefits (not that I need them). I agreed to work on this project through Summer 2012. I don't feel like I'm being fairly compensated for my time. Other team members make between 3-5 times as much as I do, and their work isn't 3-5 times as good as mine, nor do they have 3-5 times as much output. I don't think this is a rectifiable situation within this institution. They've got a set of personnel charts and the way it gets computed, I make less money than any of the janitors (who are very good, and very nice people to boot, and I'm glad they get paid so well. I wish everyone got livable wages). I'm pretty bright, but school's a drag. I don't want mega bucks, I just want $40k/yr (localized to the southeast united states) so I can save enough money to travel, or maybe "finish [my] education". My question is this: Are people without degrees ever compensated commensurate with other people who have degrees? As a someone who never "finished their education", how badly do you think this as hurt you? How do you navigate the job seeking and hiring process? As someone who hires programmers, do you pay more for diplomas? Is that an institutional necessity, or based on your own value judgement?


License for free but restricted software sharing

I have built a JavaScript library that I'd like to release for free within my user community. However I want to keep it under control, and not allow my users to pass it on to others without my permission. As far as I can tell, a MIT or GPL license won't work for that scenario. What licensing options do I have? Background: I've had some bad experience in the past where my solutions were used in situations other than the intended purpose, and this triggered maintenance and security issues. I am more careful this time.


Caching strategies - LRU, MRU, Clock-Pro

I am going to write a bachelor's science work on caching strategies and really, can't find any links to specifications or full descriptions of some of them. Only something like summaries from wikipedia. Please, help with some links on LRU, MRU caching and new-one - Clock Pro. * * * Thanks a lot. All links are very useful for me. The purpose of work - is to compare different cache strategies to get more effiency. It based on WebApplication with ejb 2.0, so algorithm's will be implemented there, espesially in ejbLoad() and ejbFindByPrimarKey(). Also, one of aspects of this application - it will use not common scheme of tables in database - it based on metamodel. So, if you had any experience on this topic, i would be grateful to take some of your knowledge)


Are questions on graphs common in programming interviews?

Despite saying that graphs are very important, none of my friends have got any graph related questions in interviews in Google and Amazon. I am preparing for these companies right now. Should I worry about graph related questions?   What are the must-know things in Graph theory before going to interviews?


Loading XML File

I'm using xml to store cross-program information. This information is used in some webpages and in C# programs. When the information is altered, these alterations are not displayed right away in the webpages, they keep on displaying the information saved in cache, it takes a few refreshes for the webpage to show these alterations. Is there any way I can force the webpages to show the actual file and not the cached one?


Domain model associations that do not required the behaviour of the associated object. How to model?

I've been struggling with this question for a while. I'm specifically thinking within the object orientated domain model. Let's say I have two entities. A `supplier` and a `customer`. There is a relationship that a `supplier` can have many customers, and a `customer` (in this case) can only have one `supplier`. The issue I have is that neither object needs any behaviour of the other object i.e. the supplier object does not need to use any behaviour of the customer object and visa versa. There is however still an association between them. The reason is that the problem domain requires that all a suppliers customers are destroyed if the supplier is destroyed. We also need to be able to retrieve a collection of all customers associated with a supplier. **How is this managed in the OO domain model?** **Who is responsible for the association?** Some may say that there should be a `getCustomers()` method on the `supplier` object and this is where the association lies. I don't really like this as it makes it difficult to close the `supplier` class (violation of Open Closed Principle). Every time we create a new type of class which has an association to a `supplier`, we have to add a get method to the `supplier`. One thing I think could be used to model the association are repositories (from Eric Evens Domain Driven Design book). I guess it would be the Repository that then cares about this relationship? We could call `selectCustomersFor(supplier_id)` etc **Edit** The only reason I can see for having the association is for object retrieval criteria or object destruction (i.e. if user is destroyed, all customers will be destroyed). To me, it is not the responsibility of either object to retrieve or destroy itself. You could argue that the supplier should retrieve/destroy a customer, but this surely violates the Single Responsibility rule, and could also lead to Open Closed violation. Why would we then bother to add the responsibility of association to an object thats doesn't use it? Its useless to the object. The association isn't useless though, I just feel something else should be responsible for it.