title: How to transition a small team developing on a remote testserver from svn to git

text: At the company I work we use SVN. The SVN repository resides on the local server. When developing we commit the changes to SVN on the local server which transfers the changes via ftp to a testsite remote test server. The whole team uses the same testsite. We use a remote testserver so that we don't have to setup anything on our local machines. If developer A wants to see the changes of developer B on is local machine, he must simply update his working copy. Most of the time we are very happy with this approach:   * it's simple   * svn is nicely integrated in Netbeans Things that bother us are:   * the changes are transfered via ftp. When transferring a lot of files this can be quite slow   * we would like to have a repository "in the cloud" so we can develop not only from our office but from anywhere (and without have to setup a vpn) Is our workflow possible if we were to use github to host our repository? These things are important to us:   * we are not going to develop locally, we would still like to use a testsite on a testserver that is shared by the entire team   * because we do a lot of small changes pushing the changes to the testsite should be very easy   * we have a lot of small sites so the setup that a developer should do per site should be minimal


title: Developing basic drawing tool involving lines, curves

text: I am developing a CAD - drawings to CNC machine code software. These CNC's have sort of a Instruction set which receive parameters,etc to do some blah blah job. I am quite comfortable with the CNC side; but am suddenly being asked to make a software which would let you "draw" plus will convert the drawing to the machines code. I am REALLY worried about the "draw" part. Shall i go for OpenGL development? or is there a more simplified way of doing things ? So to summarize, my problem : Creating a mini CAD platform (its all 2D and i dont need to bother with complex shapes apart from lines , some curves) But i have to provide the user with tools to make these "simple drawings" Please give me technical advice and a head start.


title: Convert Algebraic Expression directly into Binary Tree Structure (sans prefix / postfix)

text: I am looking all over internet to find a logic to convert an Algebraic Expression into a Binary Tree. I could only find ones where you first convert the algebra expression to postfix or prefix and then convert it to Binary Tree. I am just curious to know , if its possible. Any pointers to external links or logical answers to put me in the right direction ? * * * yes A Syntax Tree So this expression               A+(B-C)*D+E*F      should be translated into                             |-(+)-|                   |     |         |---(*)---|     |---(*)---|         |         |     |         |     |---(+)---|   D     E         F     |         |     |         |     A   |--( - )--|         |         |         B          C


title: Is my application vulnerable to SQL injection if I don't specify each type in Doctrine2?

text: I thought Doctrine 2 DBAL prepared statements were safe from SQLi. But I found this confusing bit in the docs: > By default the Doctrine DBAL does no escaping. Escaping is a very tricky > business to do automatically, therefore there is none by default. When you > use the Doctrine DBAL as standalone, you have to take care of this yourself. What does that mean exactly? If someone tries to inject malicious code, will the query fail (as opposed to insert escaped) because the RDBMS protects me? Or I'm not protected at all? I'm using PostgreSQL as my RDBMS.


title: Is it possible to design a language that doesn't have syntax errors?

text: In other words, a language where every possible string is valid syntax? **EDIT** : This is a theoretical question.   I have no interest in _using_ such a language; I'm just asking whether it's possible.


title: Law of Demeter issues with complex class design

text: I've posted questions pertaining to this issue before, but they've all tackled different aspects of the problem (Just so you know that I'm not reposting the same question to get more answers). So, in a nutshell, here is my problem: I have a `Timeline` class, which has-a `Content` interface member variable. The Timeline manages WHEN the content gets activated. There is also a `Trigger` class, which gets a reference to the `Timeline` class and call the `Timeline`'s `play()` methods at certain times (like when the user hits spacebar). To organize the `Triggers` and the `Timeline` together, they're bound together in a class called `Cue` (which is the only class the rest of the program cares about). This leads me to a design problem, since this `Cue` class is used so often throughout my code, it would be a pain to change it later. Because of the Law of Demeter, should I not make getters and setters for the `timeline` and `triggers` member variables, and instead copy many of their functions into `Cue` (and just call the functions of the member variables in turn). That way, other classes won't know the inner workings of it?


title: Is this a monad in Java? (part 2)

text: My first try was on stackoverflow. I'm picking up on the answer there to improve my monad: StackOverflow - Is this a monad in Java? My goal is to write an example of a monad. I'm not trying to solve the general case, just come up with one to see how it works. If I'm right, then I really like this pattern. I've already used it to rework some code I'm working on. So I hope it's right. I was pretty strict about the signatures & not taking shortcuts that OO allows. The (contrived) example is to provide semantics to represent a Friend relationship between two users. If there's an error, or the friendship is blocked, then processing stops. I have sample code that "lifts" Boolean, String and a custom Friend class into the monadic space, so I think that' a sign I'm on the right track. I've included the sample code lifting String into the monadic space. My question is, did I get the monad implementation right? Please call out the places where I jumped the rails!               public class FriendSpace<A> {              public boolean rejected = false;         public String errors = "";         public A original;              public interface Function<B, MA> {             MA apply(B b, MA a);         }              public FriendSpace<A> unit(A a) {             FriendSpace<A> that = new FriendSpace<A>();             that.original = a;             return that;         }              public <B> FriendSpace<A> bind(B b, Function<B, FriendSpace<A>> f) {             if (! errors.isEmpty()) {                 // we have errors; skip the rest                 return this;             }                  if (rejected) {                 // No means no                 return this;             }                  FriendSpace<A> next = f.apply(b, this);                  return next;         }              @SuppressWarnings("unchecked")         public <B> FriendSpace<A> pipeline(B value,                FriendSpace.Function<B, FriendSpace<A>>... functions) {             FriendSpace<A> space = this;             for (FriendSpace.Function<B, FriendSpace<A>> f : functions) {                 space = space.bind(value, f);             }             return space;         }              // toString omitted to save space     }      And here's an example where the (arbitrary) input is a People class, and the (arbitrary) class representing the friendship state is String               public class People {              public People(String from, String to) {             this.from = from;             this.to = to;         }              public String from;         public String to;     }              @SuppressWarnings("unchecked")         public static void main(String[] args) {             FriendSpace<String> proto = new FriendSpace<String>();                  People people0 = new People("Bob", "Fred");             FriendSpace<String> space0 = proto.unit("");             FriendSpace<String> friends0 = space0.pipeline(people0, VERIFY, INVITE, ACCEPT);             System.err.println(friends0);                  People people1 = new People("Bob", "Jenny");             FriendSpace<String> space1 = proto.unit("");             FriendSpace<String> friends1 = space1.pipeline(people1, VERIFY, INVITE, ACCEPT);             System.err.println(friends1);                  People people2 = new People("Fred", "Jenny");             FriendSpace<String> space2 = proto.unit("");             FriendSpace<String> friends2 = space2.pipeline(people2, VERIFY, INVITE, BLOCK);             System.err.println(friends2);                  People people3 = new People("Bob", "Tom");             FriendSpace<String> space3 = proto.unit("");             FriendSpace<String> friends3 = space3.pipeline(people3, VERIFY, INVITE, ACCEPT);             System.err.println(friends3);         }              public interface StringFunction extends FriendSpace.Function<People, FriendSpace<String>> {         }              static StringFunction VERIFY = new StringFunction() {             public FriendSpace<String> apply(People from, FriendSpace<String> to) {                 String KNOWN_USERS = "Bob Fred Jenny";                      if (! KNOWN_USERS.contains(from.from)) {                     to.errors += "Unknown from: " + from.from;                 }                      if (! KNOWN_USERS.contains(from.to)) {                     to.errors += "Unknown to: " + from.to;                 }                      return to;             }         };              static StringFunction INVITE = new StringFunction() {             public FriendSpace<String> apply(People from, FriendSpace<String> to) {                 // Jenny has blocked Bob                 if ("Jenny".equals(from.to) && "Bob".equals(from.from)) {                     to.errors = "Jenny blocked Bob";                 }                 return to;             }         };              static StringFunction ACCEPT = new StringFunction() {             public FriendSpace<String> apply(People from, FriendSpace<String> to) {                 // Good to go!                 to.original = "YES";                 return to;             }         };              static StringFunction BLOCK = new StringFunction() {             public FriendSpace<String> apply(People from, FriendSpace<String> to) {                 to.original = "BLOCK";                 to.rejected = true;                 return to;             }         };


title: Console Application vs GUI?

text: I'm trying to develop a minimal MP3 player with some cool but light features. It is so simple that it doesn't matter if it is console application or not. Since my purpose is to consume the sources as small as possible which one should I pick? Extra info: I will be using a single textbox if it's going to be an application with GUI. Also, I am using VS 2010 C++


title: Is it better expose a collection or an API to the collection?

text: Take for example the following:               public interface IManager     {            void AddItem(CollectionItem item);         void RemoveItem(CollectionItem item);     }          public interface IManagerCustomCollection     {         ManagerCollection Systems;     }      Is it usually more preferable to create a collection, and allow the consumer to operate directly on the collection?


title: Set modified date = created date or null on record creation?

text: I've been following the convention of adding created and modified columns to most of my database tables. I also have been leaving the modified column as null on record creation and only setting a value on actual modification. The other alternative is to set the modified date to be equal to created date on record creation. I've been doing it the former way but I recent ran into one con which is seriously making me think of switching. I needed to set a database cache dependency to find out if any existing data has been changed or new data added. Instead of being able to do the following: `SELECT MAX(modified) FROM customer` I have to do this: `SELECT GREATEST(MAX(created), MAX(modified)) FROM customer` The negative being that it's a more complicated query and slower. Another thing is in file systems I believe they usually use the second convention of setting modified date = created date on creation. What are the pros and cons of the different methods? That is, what are the issues to consider? **UPDATE** I believe given the apparent trade-offs I'm going to go with modified = created strategy. In addition, I was curious how other web databases handled this and I noticed drupal seems to follow the convention of modified = created also.


title: Different ways of managing Java code documentation

text: What are good alternatives to inline Java documentation, i.e. can one have a separate docs file somehow mapped to a java source file? I have never liked huge comment sections littered in code, so was just looking for options. Are there any good tools available for such docs management?


title: Should I omit the parameter "e" when using EventHandler<EventArgs>?

text: Whenever I am defining my own events, I use a pattern such as the following (which I _believe_ is how the MSDN recommends doing it):               public class MyEventClass     {         private bool _value; // Backing variable         public bool Value         {             get { return _value; }             set             {                 if (value != _value) // Only raise event if value is changed/different                 {                     _value = value;                     OnValueChanged(EventArgs.Empty);                 }             }         }              public event EventHandler ValueChanged; // Anything can subscribe to the event         protected void OnValueChanged(EventArgs e) // Only this and children can invoke event         {             if (ValueChanged != null)                 ValueChanged(this, e);         }     }      Thus, the client code just needs to subscribe to the event and it automagically works. However, it feels cumbersome to pass the `EventArgs e` parameter, in particular with a class that uses EventHandler to raise its events, since the base EventArgs has no data to it, only `EventArgs.Empty`. Would it be considered a faux pas to change it to this?               protected void OnValueChanged()     {         if (ValueChanged != null)             ValueChanged(this, EventArgs.Empty);     }


title: Diminishing Returns on Additional Developers

text: Is there a term to describe the point at which adding more developers to a software project will provide diminishing returns? I realize that at a high level, it is more complicated that just a number of developers at which the project will be at productive capacity (ex/ state of the project, quality of the added developer), but I am trying to come up with a way to relate this to non-technical management through repetition. I'm basically looking for a term which invokes a strong mental image like "terminal velocity", except for Brook's Law.


title: What is the most effective order to learn SQL Server, LINQ, and Entity Framework?

text: I am trying to get some advice on what order I should learn about SQL Server, LINQ, and Entity Framework to be able to better work with ASP.NET Webforms and MVC. From what I've been able to learn so far, many recommend learning LINQ or Entity Framework before learning SQL Server. It also appears that many companies are looking for people with knowledge in LINQ-to-SQL and Entity Framework without mentioning SQL Server. However, my understanding is that LINQ-to-SQL and Entity Framework translate code into SQL Server queries, making this a poor approach. Is there a correct or best order in which to learn these technologies?


title: Should I use C style in C++?

text: As I've been developing my position on how software should be developed at the company I work for, I've come to a certain conclusion that I'm not entirely sure of. It seems to me that if you are programming in C++, you should not use C style anything if it can be helped and you don't absolutely need the performance improvement. This way people are kept from doing things like pointer arithmetic or creating resources with new without any RAII, etc. If this idea was enforced, seeing a char* would possibly be a thing of the past. I'm wondering if this is a conclusion others have made? Or am I being too puritanical about this?


title: How should I architect my Model and Data Access layer objects in my website?

text: I've been tasked with designing Data layer for a website at work, and I am very interested in architecture of code for the best flexibility, maintainability and readability. I am generally acutely aware of the value in completely separating out my actual Models from the Data Access layer, so that the Models are completely naive when it comes to Data Access. And in this case it's particularly useful to do this as the Models may be built from the Database or may be built from a Soap web service. So it seems to me to make sense to have Factories in my data access layer which create Model objects. So here's what I have so far (in my made-up pseudocode):               class DataAccess.ProductsFromXml extends DataAccess.ProductFactory {}     class DataAccess.ProductsFromDatabase extends DataAccess.ProductFactory {}      These then get used in the controller in a fashion similar to the following:               var xmlProductCreator = DataAccess.ProductsFromXml(xmlDataProvider);     var databaseProductCreator = DataAccess.ProductsFromXml(xmlDataProvider);          // Returns array of Product model objects     var XmlProducts = databaseProductCreator.Products();     // Returns array of Product model objects     var DbProducts = xmlProductCreator.Products();      So my question is, is this a good structure for my Data Access layer? Is it a good idea to use a Factory for building my Model objects from the data? Do you think I've misunderstood something? And are there any general patterns I should read up on for how to write my data access objects to create my Model objects?


title: What are build team responsibilities from developer point of view?

text: Lets assume that you are working for a corporation doing a lot of IT development. What do you think should be build team responsibilities that performs 'services' for developers? What do you expect to be doing by yourselves and what tasks would you gladly pass?


title: Is static universally "evil" for unit testing and if so why does resharper recommend it?

text: I have found that there are only 3 ways to unit test (mock/stub) dependencies that are static in C#.NET:   * Moles   * TypeMock   * JustMock Given that two of these are not free and one has not hit release 1.0, mocking static stuff is not too easy. Does that make static methods and such "evil" (in the unit testing sense)? And if so, why does resharper want me to make anything that can be static, static? (Assuming resharper is not also "evil".) **Clarification:** I am talking about the scenario when you want to unit test a method and that method calls a static method in a _different_ unit/class. By most definitions of unit testing, if you just let the method under test call the static method in the other unit/class then you are **not** unit testing, you are _integration_ testing. (Useful, but not a unit test.)


title: Is java.util.prefs.Preferences appropriate for accessing changes in state that need to be immediately accessed during runtime?

text: In my application, I'm currently creating a single instance of a `UserPrefs` object at startup, then passing a reference to that object to multiple other objects through their constructors. I am doing this because it's important that multiple classes have immediate access to any real-time changes the user makes to their preferences during runtime. The problem is that passing this object to many different constructors seems messy to me, and I'd like to move away from this. So I'm interested in possibly using the `java.util.prefs.Preferences` API in each class that needs access to this information. But I get the sense that the `Preferences` API is more commonly used to simply save a snapshot of user preferences at application shutdown, then to load them back in during startup. So my question is: Would `java.util.prefs.Preferences` be appropriate in this situation? If not, is there some other way I can share preferences state in real-time across multiple classes?


title: Persisting natural language processing parsed data

text: I've recently started experimenting with natural language processing (NLP) using Stanford's CoreNLP, and I'm wondering what are some of the standard ways to store NLP parsed data for something like a text mining application? One way I thought might be interesting is to store the children as an adjacency list and make good use of recursive queries (Postgres supports this and I've found it works really well). But I assume there are probably many standard ways to do this depending on what kind of analysis is being done that have been adopted by people working in the field over the years. So what are the standard persistence strategies for NLP parsed data and how are they used?


title: Using mod_rewrite for a Virtual Filesystem vs. Real Filesystem

text: I started working in a department that uses a CMS in which the entire "filesystem" is like this:   1. create a named file or folder - this file is given a unique node (ex. 2345) as well as a default "filename" (ex. `/WelcomeToOurProductsPage`) and apply a template   2. assign one or more _aliases_ to the file for a URL redirect (ex. `/home-page-products` \- can also be accessed by `/home-page-products.aspx`)   3. A new Rewrite command is written on the .htaccess file for _each and every alias_   4. Server accesses either `/WelcomeToOurProductsPage` or `/home-page-products` and redirects to something like `/template.aspx?tmp=2&node=2345` (here I'm guessing what it does - I only have front-end access for now - but I have enough clues to strongly assume)   5. Node 2345 grabs content stored in a SQL Db and applies it to the template. Note: There are no actual files being created on the filesystem. It's entirely virtual. This is probably a very common thing, but since I have never run across this kind of system before two months ago, I wanted to explain it in case it isn't common. I'm not a fan at all of ASP or closed-sourced systems, so it may be that this is common practice for ASP developers. My question, that has taken far too long to ask, is: what are the benefits of this kind of system, as opposed to creating an actual file hierarchy? Are there any drawbacks to having every single file server call redirected? To having the .htaccess file hold rewrite rules for _every single alias_?


title: How best to format text files of statutes in HTML with specific IDs

text: I'm trying to find the best way to process about 20,000 lines of a statute in text format into HTML so that it can be displayed and manipulated in a granular fashion, i.e. by clause. The format is essentially a nested list like (a)(1)(A)(i)(II)(aa) and is fairly consistent. Each clause begins with a new line and is enclosed in parenthesis like above. The goal is for each clause to be enclosed in a paragraph tag with a unique id like p id="sec101a1AiI" (sorry I can't figure out the code formatting). The point is to be able to refer to a specific clause later on. I've played with regular expressions but they don't seem to allow me to iterate through the entire statute and tag things in a unique fashion. I'm sure there are better options using a custom script but I don't know where to start looking for that. Any suggestions would be appreciated.


title: Design Pattern for Complex Data Modeling

text: I'm developing a program that has a SQL database as a backing store. As a very broad description, the program itself allows a user to generate records in any number of user-defined tables and make connections between them. As for specs:   1. Any record generated must be able to be connected to any other record in any other user table (excluding itself...the record, not the table). Yes, this creates a arbitrary user-generated relational map.   2. These "connections" are directional: Incoming, outgoing, and bi-directional.   3. The list of connections a record has is user ordered.    4. A record must "know" of connections made _from_ it to others as well as connections made _to_ it from others.    5. A record's field can also include aggregate information from it's connections (like obtaining average, sum, etc) that must be updated on change from another record it's connected to.   6. To conserve memory, only relevant information must be loaded at any one time (can't load the entire database in memory at load and go from there).   7. I cannot assume the backing store is local. Right now it is, but eventually this program will include syncing to a remote db.   8. I cannot depend on a specific implementation of a backing store. This means I cannot be certain the backing store is, in fact, relational. Thus all relational data is stored explicitly. The connections are kind of the point of this program, so there is a strong possibility that the number of connections made is very high, especially if the user is using the software as intended. Neither the user tables, connections or records are known at design time as they are user generated. I've spent a lot of time trying to figure out how to design the backing store and the object model to best fit these specs. In my first design attempt on this, I had one object managing all a table's records and connections. I attempted this first because it kept the memory footprint smaller (records and connections were simple dicts), but maintaining aggregate and link information between tables became....onerous (ie...a huge spaghettified mess). Tracing dependencies using this method almost became impossible. Instead, I've settled on a distributed smart graph where each record and connection is 'aware' of what's around it by managing it own data and connections to other records. Doing this increases my memory footprint but also let me create a faulting system so connections/records aren't loaded into memory until they're needed. It's also much easier to code: trace dependencies, eliminate cycling recursive updates, etc. My biggest problem is storing/loading the connections. I'm not happy with any of my current solutions/ideas so I wanted to ask and see if anybody else has any ideas of how this should be structured. Connections are fairly simple. They contain: fromRecordID, fromTableID, fromRecordOrder, toRecordID, toTableID, toRecordOrder. Here's what I've come up with so far:   1. Store all the connections in one big table. If I do this, either I load all connections at once (one big db call) or make a call every time a user table is loaded. The big issue here: the size of the connections table has the potential to be huge, and I'm afraid it would slow things down.   2. Store in separate tables all the outgoing connections for each user table. This is probably the worst idea I've had. Now my connections are 'spread out' over multiple tables (one for each user table), which means I have to load each table just to find all the incoming connections for a particular user table. I've avoided making "one big ass table", but I'm not sure the cost is worth it.   3. Store in separate tables all outgoing AND incoming connections for each user table (using a flag to distinguish between incoming vs outgoing). This is the idea I'm leaning towards, but it will essentially double the total storage for all the connections (as each connection will be stored in two tables). It also means I have to make sure connection information is kept in sync in both places (each 'from' connection has a corresponding 'to' connection in the appropriate table. This is obviously not ideal but it does mean that when I load a user table, I only need to load one 'connection' table and have all the information I need. This also presents a separate problem, that of connection object creation. Since each user table has a list of all connections, there are two opportunities for a connection object to be made. However, connections objects (designed to facilitate communication between records) should only be created once. This means I'll have to devise a common caching/factory object to make sure only one connection object is made per connection.  Does anybody have any ideas of a better way to do this? Once I've committed to a particular design pattern I'm pretty much stuck with it, so I want to make sure I've come up with the best one possible. I'll also note that my current backing store is SQLite. I've written the program to not depend on a specific backing store, though, by introducing an adapter layer to disassociate the data retrieval from the the rest of the program. So the backing store could be anything, even a simple text file. I use the backing store exclusively for storage and data retrieval, nothing else. I don't use any specific database/SQL relational features and I don't use the database to perform calculations (aggregate or otherwise). All of that is handled in program logic.


title: UML: Queue processor in a sequence diagram

text: Which is the appropriate way of representing a queue processor in a UML sequence diagram? I want to represent in the same diagram two systems that are loosely coupled through a queue. The first system, performs some actions and insert an action in a queue, the other system is always listening and when the event appears in the queue, it dequeues the event and processes it, generating new actions. They are both in the same diagram because it is to represent an integration use case that shows how both work together. Should I create a life line representing the queue? Should I represent the "listening" process as a loop box containing: a self- message with the label "listen", self-message for processing message and messages representing the sending of the outcome.


title: Can a webservice that uses JSON over POST be classified as RESTful?

text: Recently I have started using a new(to me) paradigm for web services. I use the controller to accept JSON strings sent over POST, process it and return JSON strings. GET, PUT, DELETE and other methods throw HTTP 405. This pattern is proving to be very efficient from the point of view of asynchronous web frameworks (vert.x and play to be particular), as well as from development effort point of view. What I am confused about is that this neither seems to be SOAP nor REST. I don't think it is even JSON-RPC, since I am using my own headers like: Request:               {       'requestId':<generated req Id>,       'token':<previously authenticated token>,       'action':<controller defined action>,       'parameters':[         <array of parameters>       ]          }      Response:               {       'result':'success/fail',       'payload':{          <payload>        }     }      EDIT: There is only one endpoint URL, something like https://my.domain.com/api Can anyone give any ideas about what this paradigm can be classified as?


title: available methods change with object state

text: I'm programming a graph object which can be in either a mutable or immutable state. In both states, it has a `get` method, but only in the mutable state is the `set` method allowed. The transition occurs when one invokes a method `compress` which optimizes the storage of the graph. **How do I deal with the fact that some methods are legal in some states but not others?** I can think of two approaches. The blunt way is to use the state pattern. If you invoke `set` when the graph is mutable, it executes as normally; but, if you invoke `set` when the graph is immutable, an error is thrown. This looks ugly to me because an immutable object still has a `set` method. Alternatively, I can make a `graph` type with a `mutable_graph` sub-type; only the second one has a `set` method. The state change is effected by changing the type of the graph. However, this also looks ugly to me; for every implementation of `graph` (of which there are several), I now have to make two types instead of just one. EDIT: I'm using the state pattern and throwing an exception; if neither solution is especially preferable, this one involves writing the least code. Thanks for the advice!


title: Throwing an exception for errors that can be fixed

text: Say I have a class like this:               public class MyObject     {         public List<string> MyCollection { get; set; }     }      And a method like this:               public void DoSomething(MyObject object)     {         if(object.MyCollection == null)         {             // MyCollection must not be null             // Should I...                  // a)             object.MyCollection = new List<string>();                  // b)             throw new ArgumentException("MyCollection can not be null");         }     }      I do not have control over MyObject. Normally I'd just instantiate the collection in the constructor and be done with it. Should I just instantiate the collection in my method, or throw an exception?


title: Best Practice - Loop Exit Via Iterator Modification

text: I had an interesting discussion with my boss today regarding exiting a loop before the terminal condition is met. He had a construct in some of his VB6 code that looked something like this:               Dim Termination As Int     Termination = 10          For Iterator1 = 1 To Termination         If Iterator1 = 5 Then             Iterator1 = Termination         End If     Next      I questioned this implementation, contending that an `Exit For` was the proper way to exit a loop prematurely based on a condition, like this:               For Iterator2 = 1 To 10         If Iterator2 = 5 Then             Exit For         End If     Next      I noted that in practice these probably both evaluate to the same machine language JMP opcode. My boss asserted that his implementation may be more efficient since it would have only one JMP, the one at the end of the loop, instead of two, one at the end and one in the middle for the `Exit For` statement. I prefer the second implementation for readability and semantics. Also, in the latest versions of Visual Studio for .Net if you add lines after the `Exit For` statement you'll be warned that there are unreachable lines in your code. However, you don't get this warning in VB6, which is where the debate started. So what's the best practice here? Is the first example better in VB6 or is the second example better in all situations? What are the advantages / disadvantages of each approach. **Edit** : Removed magic number from code example to enhance question clarity.


title: Is "If a method is re-used without changes, put the method in a base class, else create an interface" a good rule-of-thumb?

text: A colleague of mine came up with a rule-of-thumb for choosing between creating a base class or an interface. He says: > Imagine every new method that you are about to implement. For each of them, > consider this: **will this method be implemented by more than one class in > _exactly_ this form, without _any_ change?** If the answer is "yes", create > a base class. In every other situation, create an interface. For example: > Consider the classes `cat` and `dog`, which extend the class `mammal` and > have a single method `pet()`. We then add the class `alligator`, which > doesn't extend anything and has a single method `slither()`. > > Now, we want to add an `eat()` method to all of them. > > If the implementation of `eat()` method will be exactly the same for `cat`, > `dog` and `alligator`, we should create a base class (let's say, `animal`), > which implements this method. > > However, if it's implementation in `alligator` differs in the slightest way, > we should create an `IEat` interface and make `mammal` and `alligator` > implement it. He insists that this method covers all cases, but it seems like over- simplification to me. **Is it worth following this rule-of-thumb?**


title: What are the disadvantages of self-encapsulation?

text: # Background Tony Hoare's billion dollar mistake was the invention of `null`. Subsequently, a lot of code has become riddled with null pointer exceptions (segfaults) when software developers try to use (dereference) uninitialized variables. In 1989, Wirfs-Brock and Wikerson wrote: > Direct references to variables severely limit the ability of programmers to > reﬁne existing classes. The programming conventions described here structure > the use of variables to promote reusable designs. We encourage users of all > object-oriented languages to follow these conventions. Additionally, we > strongly urge designers of object-oriented languages to consider the effects > of unrestricted variable references on reusability. # Problem A lot of software, especially in Java, but likely in C# and C++, often uses the following pattern:               public class SomeClass {       private String someAttribute;            public SomeClass() {         this.someAttribute = "Some Value";       }            public void someMethod() {         if( this.someAttribute.equals( "Some Value" ) ) {           // do something...         }       }            public void setAttribute( String s ) {         this.someAttribute = s;       }            public String getAttribute() {         return this.someAttribute;       }     }      Sometimes a band-aid solution is used by checking for `null` throughout the code base:                 public void someMethod() {         assert this.someAttribute != null;              if( this.someAttribute.equals( "Some Value" ) ) {           // do something...         }       }            public void anotherMethod() {         assert this.someAttribute != null;              if( this.someAttribute.equals( "Some Default Value" ) ) {           // do something...         }       }      The band-aid does not always avoid the null pointer problem: a race condition exists. The race condition is mitigated using:                 public void anotherMethod() {         String someAttribute = this.someAttribute;         assert someAttribute != null;              if( someAttribute.equals( "Some Default Value" ) ) {           // do something...         }       }      Yet that requires two statements (assignment to local copy and check for `null`) every time a class-scoped variable is used to ensure it is valid. # Self-Encapsulation Ken Auer's _Reusability Through Self-Encapsulation_ (Pattern Languages of Program Design, Addison Wesley, New York, pp. 505-516, 1994) advocated self- encapsulation combined with lazy initialization. The result, in Java, would resemble:               public class SomeClass {       private String someAttribute;            public SomeClass() {         setAttribute( "Some Value" );       }            public void someMethod() {         if( getAttribute().equals( "Some Value" ) ) {           // do something...         }       }            public void setAttribute( String s ) {         this.someAttribute = s;       }            public String getAttribute() {         String someAttribute = this.someAttribute;              if( someAttribute == null ) {           someAttribute = createDefaultValue();           setAttribute( someAttribute );         }              return someAttribute;       }            protected String createDefaultValue() { return "Some Default Value"; }     }      All duplicate checks for `null` are superfluous: `getAttribute()` ensures the value is never `null` at a single location within the containing class. Efficiency arguments should be fairly moot -- modern compilers and virtual machines can inline the code when possible. As long as variables are never referenced directly, this also allows for proper application of the Open-Closed Principle. # Question What are the disadvantages of self-encapsulation, if any? (Ideally, I would like to see references to studies that contrast the robustness of similarly complex systems that use and don't use self- encapsulation, as this strikes me as a fairly straightforward testable hypothesis.)


title: Common test cases for XML schema validator

text: I just wrote my first SAX-based (Java) XML schema validator, where you pass it a schema URL (pointing to the `.xsd` file), and an XML instance, and it determines whether or not that instance is valid or not. I'm now looking to write several unit tests for the validator (TDD people, I _know_ , I know!) and was wondering what were some common reasons why XML fails validation. There are so many elements and attributes in this schema, I could literally write _thousands_ of test cases. I figured someone here might know of a way to simplify them all down to a manageable set.


title: How much functionality needed to create a new class?

text: Right now I am working on my own small project of a WPF file back up application. I have come to a point where I want to create a method that will copy files recursively from one place to another. This is not the first time that I ask myself the question: > Should this method be a part of an existing class, or should I store it in a > new class? What bothers me the most is that if I create a new class, it will most likely consist of solely this method, so it seems like a stretch to create a whole new type for just one action. On the other hand, I believe it is a good abstraction. Copying files doesn't have much to do with a WPF window. The example that I show here brings out a more general question. **How to balance between functionality/abstraction/readability to create code where OOP principles don't obscure common sense?** I am relatively new to programming, but I'd like to start following good coding practices as soon as possible, e.g. not implementing design patterns like crazy, because I have just read about them.


title: Getting into windows phone 7 development -- what is the cheapest way?

text: Probably it is necessary to have an actual device. But I'd rather not have to buy a phone with a contract. Is that possible?


title: Advantages of contracts over assert statements

text: Today I stumbled upon the python package called PyContracts. However, python has the `assert` statement which seems to allow you to do exactly those things. What advantages do contracts have over assert statements?


title: Remote Working & Relocation

text: Sorry if this question is a duplicate, I did some extensive searching and found nothing on quite the same topic (though a couple on partially- overlapping topics). Recently, whilst on holiday in Munich, Germany, I was taken aback by the sheer number of programming-related posts available in the city that I easily qualify for (both in terms of knowledge, and experience). The advertised working environments seemed good and the pay seemed to be at least as good as what I'd expect here in the UK. Probably 80% of the advertisements I saw on the underground were for IT-related jobs, and a good 60% of those I was easily qualified for. At the moment, I work as a freelancer mostly on web and small software projects, but seeing the vast availability of jobs in Munich versus my local area has me thinking about remote working. I'm unable to _relocate_ for a job for the next 3 years (my wife has a contract to continue being a doctor at her current hospital for that time) but would almost certainly be open to it after that (after all, my wife and I both love Munich). In the meanwhile, I would be _very_ interested in remote- working. So, my question is thus **do companies ever take on remote workers** (even with semi-frequent trips to the office) **from abroad, with a view to _later_ relocation?** And, if so, **how do you go about broaching the topic with a recruiter when getting in contact about a job posting?** Language isn't a barrier for me, here, as 90% of the jobs I've looked up in Munich don't require German speakers (seems they have a big recruiting market abroad). I'm also under no illusions about the disadvantages of remote working, but I'm more interested in the viability of the scenario rather than the intricacies (at least at this point). I'd really appreciate any contributions, especially from those who have experience with working in such a scenario!


title: Would this interpreter be considered a Virtual Machine?

text: _(I reworded my question to make it more specific)._ Consider a programming language, that it's programs may only be run inside a specific program that serves as an interpreter. The interpreter scans each line of the source code and executes it as it is. **Would the interpreter be considered a virtual machine?** Conceptually, a VM is a program that other programs use as a platform to run inside of. Thus this interpreter suits the definition. But this interpreter only interprets plain-text source code into executions (and not bytecode).


title: Future of WPF and free controls ?

text: I am willing to work on a personal project that I would like to release publicly. I am working with Silverlight and have experience with XAML, as it is my full-time job. It is enjoyably for me to create UIs in Blend and XAML. I am also a big fan of C# language. I don't know what I would do without LINQ now. Anyways, I was looking at using WPF for my personal project. It seems that a lot of the controls out on the web are pay for items. The only place I have found to have a significant number of free controls is the WPF extended framework on codeplex. I want to make a financial application and need a powerful datagrid type of control that will allow me to enter transaction data. I haven't found such control for free in the net. It doesn't seem like there is much free community libraries/controls out there for Microsoft products. So, I was wondering if WPF would be the right way for me to go. I couldn't find any information on WPF usage in Windows 8, which coming very soon. I don't know Microsoft's plans for this technology. Would it be a better idea to use something different for the UI instead of WPF?


title: Default Ant target: help or jar?

text: What would you choose as the default Ant target?   In the context of a small visual tool with a user interface, open source. I was thinking about `jar` because the project's distributable is the jar file. But someone prefers to have `help` as the default target, to show the available targets. Or maybe another target? I doubt anyone would really care, but would be the "least surprise" choice?


title: How to become a good team player?

text: I've been programming (obsessively) since I was 12. I am fairly knowledgeable across the spectrum of languages out there, from assembly, to C++, to Javascript, to Haskell, Lisp, and Qi. But all of my projects have been by myself. I got my degree in chemical engineering, not CS or computer engineering, but for the first time this fall I'll be working on a large programming project with other people, and I have no clue how to prepare. I've been using Windows all of my life, but this project is going to be very unix-y, so I purchased a Mac recently in the hopes of familiarizing myself with the environment. I was fortunate to participate in a hackathon with some friends this past year -- both CS majors -- and excitingly enough, we won. But I realized as I worked with them that their workflow was very different from mine. They used Git for version control. I had never used it at the time, but I've since learned all that I can about it. They also used a lot of frameworks and libraries. I had to learn what Rails was pretty much overnight for the hackathon (on the other hand, they didn't know what lexical scoping or closures were). All of our code worked well, but they didn't understand mine, and I didn't understand theirs. I hear references to things that real programmers do on a daily basis -- unit testing, code reviews, but I only have the vaguest sense of what these are. I normally don't have many bugs in my little projects, so I have never needed a bug tracking system or tests for them. And the last thing is that it takes me a long time to understand other people's code. Variable naming conventions (that vary with each new language) are difficult (__mzkwpSomRidicAbbrev), and I find the loose coupling difficult. That's not to say I don't loosely couple things -- I think I'm quite good at it for my own work, but when I download something like the Linux kernel or the Chromium source code to look at it, I spend hours trying to figure out how all of these oddly named directories and files connect. It's a programming sin to reinvent the wheel, but I often find it's just quicker to write up the functionality myself than to spend hours dissecting some library. Obviously, people who do this for a living don't have these problems, and I'll need to get to that point myself. **Question:** What are some steps that I can take to begin "integrating" with everyone else? Thanks!


title: Advice for nontraditional CS student?

text: I'm in a rather unique situation here. I am going to start school for computer science tomorrow (literally) at a local university in a BS program. However, I am starting as a **nontraditional** student. My background: > I already have the bachelor's and master's degrees in sociology, the latter > of which I gained during a PhD program that I left a half a year ago for > personal reasons (such as realizing the subject matter and the work involved > no longer held any meaning for me). After struggling for months to find > employment in this economy -- where years of graduate school and my > experience serving as a teaching assistant (and teaching classes) seem to > count for very little -- I decided to go back to school for CS. Between a > teaching gig at a local college, a part-time job at a local restaurant, and > a loan, I can afford this semester's tuition and my living expenses. I haven't been coding since an early age, like some CS students. Nearly ten years ago, I took a lot of advanced math and science in high school and a couple of programming classes, where I used Java and C++ -- and achieved a respectable level of performance, enough to make an A in each class. I can use a computer competently enough, but I can't do most of the nifty things that true computer nerds and geeks, hackers, etc. can do. I can do some stuff with HTML, but I'm just now learning about the uses of CSS -- nevermind JavaScript, PHP, XML, Ruby on Rails, etc. So far, I have been reading several threads on this site (as well as pages outside of here) that are geared towards college students in computer science. Thus, I am picking up a lot of general advice -- such as learning to write well, getting internships and independent projects, coding a lot, reading books, keeping current in the field, etc. I do, of course, plan to do all these things. I'm also trying to learn (re)learn HTML (specifically, XHTML) and add CSS, PHP, and MySQL to my repertoire. (Though, from what I've been reading and hearing from friends in technical fields, I should probably be focusing on HTML5 and CSS3.) I've also started reading a book about Python and playing around with coding some. I can tell right now it will be rough sailing for the next couple of years, but I'm going to do my best. I'm trying to glean as much advice as I can from the various sites I've found and from the threads already started here. Still, I have a few concerns that I was hoping some of you might be willing to address (for me and for any **other** nontraditional students that might be reading):   * Can you recommend any good ways to compensate for all those years **not** spend coding every chance I got? Or is it simply a matter of playing "catch up"?   * How can I balance the need to code with other responsibilities (schoolwork, jobs, etc.)? _Oh, how I fondly remember the days when all my tuition and expenses were paid for by scholarships and the like, haha!_   * One thing I feel like I probably **could** do is get accepted to a funded summer research program for undergraduates, doing research projects under professorial supervision. Would that look good to potential employers, you think?   * Because I already have degrees now, I could possibly go into the computer science department's MS program after taking some undergrad classes. The MS program has an emphasis on software development and includes a software engineering final project. Should I just try to go into that program once I've completed enough undergrad material?   * Do you have any other advice (outside of my own questions) that would be particularly relevant to nontraditional CS students who may have different situations than more traditional students? Any advice or input you could offer will be greatly appreciated. Thank you very much for your time and consideration.


title: Which are the alternatives to using a stack to represent function call semantics?

text: We all know and love that function calls are usually implemented using the stack; there are frames, return addresses, parameters, the whole lot. However, the stack is an implementation detail: calling conventions may do different things (i.e. x86 fastcall uses (some) registers, MIPS and followers use register windows, and so on) and optimizations can do even other things (inlining, frame pointer omission, tail-call optimization..). Sure, the presence of convenient stack instruction on many machines (VMs like JVM and the CLR, but also real machines like x86 with their PUSH/POP etc.) make it convenient to use it for function calls, but in some cases it is possible to program in a way in which a call stack is not needed (I am thinking about Continuation Passing Style here, or Actors in a message passing system) So, I was beginning to wonder: is it possible to implement function call semantics without a stack, or better, using a different data structure (a queue, perhaps, or an associative map?)   Of course, I understand that a stack is very convenient (there is a reason why it is ubiquitous) but I recently bumped into an implementation that made me wonder.. Do any of you know if it has ever been done in any language/machine/virtual machine, and if so which are the striking differences and shortcomings? EDIT: My gut feelings are that different sub-computation approaches can use different data structures. For example, lambda calculus is not stack based (the idea of function application is captured by reductions) but I was looking at a real language/machine/example. That's why I am asking...


title: Selling scripts/CMS modules on the internet

text: While it's almost impossible to apply for a freelance job without a sufficient portfolio/work experience, I see selling my scripts as a solution. Problem is, so far I've seen only one forum, where such trade is going on - DigitalPoint. Are there any more +/- trusted places to offer your scripts for sale?


title: Starting a new project in python and qt. Where can I find a good code layout for build scaffolding?

text: I am in the process of starting a new project with python and Qt. The project starts from zero, and it may become a commercial application. While the programming of the code in itself is a task, another task I have to handle first is how to deploy a proper development layout (makefiles, packaging for release on multiple platforms, and so on). I am looking for an already deployed open-source software with commercial quality from which I can learn the best practices in order to organize a commercial application, or alternatively, a suggestion on good practices on this regard. I did my research and I am still open on this question. I want a decent example to know how this is done in an appropriate way. All the repos I found generally are either made by people who do not care about quality (it's just a bunch of really hacked up scripts) nor platform transferability, nor addressing the different phases (development, testing, deployment, installing). In alternative, they give you fully CI/IDE solutions that are unreachable by a single developer.


title: Breaking Up A Model Class - MVC

text: I am not sure whether there is a 'right' or 'wrong' answer to this one, but I was curious about the general consensus. I have a User model that currently performs user functions (such as retrieving user details from the database, inserting new users to the database, updating user details etc.) This leads to a fairly large class. Is there any accepted thought on the breaking up of models, when the model already relates to one kind of entity? Or are large classes permissible in this case? At the moment, the class will resemble something like this:                   <?php     class Users_Model     {              public function userExists($user_id)         {             //Code to check if user exists         }              public function fetchUser($user_id)         {             //code to fetch User object from ID...         }              protected function fetchUserPassword($user_id)         {             return $this->fetchUserValue($user_id, "password");         }              protected function fetchUserLowercaseUsername($user_id)         {             return $this->fetchUserValue($user_id, "lower");         }              private function fetchUserValue($user_id, $value)         {             //fetch a user value from the database         }                   public function logout()         {             //code to log user out         }              public function doesPasswordMatch($user_id, $password)         {             //checks if inputted password matches that which is on record...         }              public function createSession($user_id)         {             //creates sessions for DATABASE         }              private function createCookie($code, $user_id)         {             //create cookies for session         }          }     ?>      My concern was doing too many things (it was performing retrieval of user information from the database, and handling the database side of logging out and sessions for the user).


title: Core competencies for software developers in the financial sector?

text: I have an interview coming up for a company operating in the financial markets. Other than generic skills like OOD, refactoring, testing and so on, what are the core areas that a financial software developer specifically needs? I can think of some obvious ones like rounding modes, differences between floating point data types etc. What other areas should I be brushing up on?


title: Psychological problems - overcoming shyness and boredom?

text: I have been programing for about 11 months. I've learned some things,and evaded some. I know some advanced things and I don't know some basic stuff. I easily get bored with programing when I program in a programing language I know, but it's different when I program in a new language. I like to learn to program and not to make apps, but I'd like that to change. Also, I am not very consinstent. I start one thing and after a few days end with something that has nothing to do with the thing I started. I am also a loner and a shy person, so I try not to ask for help (stuborn?) and as time passes I lose my confidence and patience. When I visit sites that host open- source projects, I want to join some team, but it seems like everyone is using some language/tools I don't even know they existed. Is this lack of confidence or am I still a beginner? And as I said, I try to do stuff alone, which is very often completely demotivating. So can anyone tell me how to feel more confident, how to gain willpower to join some team? If you find this question to be misplaced, don't downvote me, just tell me how to erase it or how to send it to StackExchange.


title: How do you know when to stop adding features?

text: Some time ago I wrote a very small python script that periodically checked an xml feed for new entries, and alerted the user to new entries when present. I wrote this for myself, so it was essentially a console based program that anyone comfortable with a console interface could have used. After a while I decided it could be of more use to other people and began to tidy it up, sanitize inputs, remove bugs. It occurred to me that because I'd written the script I knew how to use it efficiently, accurately etc. Others might not, so I started adding a GUI. This started out as a simple menu, and then expanded to a more full GUI with both an interface and options menu. I then added stored user preferences and also storage for previously searched xml feeds to speed up repeat searches. I added logging to help debug the application in case things go wrong, brought the application up to the latest available stable python codebase for my chosen platform and improved dialog features. I've bugfixed and commented my code clearly, and yet I still have things I think can be done to improve the app before I make it available to alpha testers. It's a far far cry from my original 20-30 line script. What I anticipated would take me just an hour or two to go from proof of concept to an acceptable use program has taken 10-20 times that. (I'm still a noob, and stuff takes me a long time, but still....) How do you know when to stop adding/tweaking/fixing stuff and let your baby crawl out in the open?


title: How does multitasking work

text: I am completely clueless about the inner workings of an operating system, but I can more or less guess the approximate behaviour of many functions. One thing that I am not able to figure out, though, is multitasking. In theory, the operating system manages time, according the CPU for small intervals to the various programs running. But it is not clear how this **really** works. Say the operating system wants to start my program. The machine code is loaded somewhere in RAM, starting at a certain address. I guess then a jump should be performed to that address, allowing my code to execute. But in this way, the OS cannot regain control until I jump back. Basically, I can imagine just two ways of making this work, but neither seems really suitable:   * The operating system could read the machine instructions I want to perform and emulate them instead of executing them directly. I am intentionally vague, since I do not know how this would work, but it seems like it would slow down the program considerably.   * Alternatively, the operating system could wait until I make a system call. In that moment it regains control and can check how long I have been running and do its timesharing stuff. This may work, but it seems unreliable, as I could make a long calculation which does not involve system calls and hang everything for a while. So, it seems neither mechanism would work very well. How is multitasking actually performed?


title: How could a human factors degree help a computer scientist?

text: I'm wrapping up a masters in CS and already have half the credit hours needed for a degree in Human Factors. I just recently discovered how useful understanding about cognition can help someone that creates user interfaces and am thirsty for more knowledge in the area. For me, it seems that having both a masters in Human Factors and CS would be very marketable but would there be jobs out there that would allow me to apply both? Meaning what I would really like to do is take the requirements for some application, apply different Human Factors theories( GOMS, CE+ ) to developing the interface, maybe do cognitive walk through with users to optimize the UI, then develop the application. Do jobs out there exist like this? The reason I ask, is because I'm wondering if most places just want you to be either a Human Factors Expert or a Developer but not both.


title: Benchmarking ORM associations

text: I am trying to benchmark two cases of self referential many to many as described in datamapper associations. Both cases consist of an Item clss, which may require many other items. In both cases, I required the ruby benchmark library and source file, created two items and benchmarked require/unrequie functions as below:               Benchmark.bmbm do |x|       x.report("require:")   { item_1.require_item item_2, 10 }       x.report("unrequire:")   { item_1.unrequire_item item_2 }     end      To be clear, both functions are datamapper add/modify functions like:               componentMaps.create :component_id => item.id, :quantity => quantity     componentMaps.all(:component_id => item.id).destroy!      and               links_to_components.create :component_id => item.id, :quantity => quantity     links_to_components.all(:component_id => item.id).destroy!      The results are variable and in the range of 0.018001 to 0.022001 for require function in both cases, and 0.006 to 0.01 for unrequire function in both cases. This made me suspicious about the correctness of my test method. # Edit I went ahead and compared a "get by primary key case" to a "finding first matching record case" by:               (1..10000).each do |i|       Item.create :name => "item_#{i}"     end          Benchmark.bmbm do |x|       x.report("Get") { item = Item.get 9712 }       x.report("First") { item = Item.first :name => "item_9712" }     end      where the results were very different like 0 sec compared to 0.0312, as expected. This suggests that the benchmarking works. I wonder whether I benchmarked the two types of associations correctly, and whether a difference between 0.018 and 0.022 sec significant?


title: How robust are Git commits when the power goes out?

text: One day I was using Git (I'm still using it) and the electricity went down while I was committing. When I (actually, the electricity) came back, the git repo was corrupt. I don't remember the exact name, but it was something like "invalid refs" or something like that. It's easy to guess that the commit was broken in the middle of the operation (I was committing through IntelliJ, which does the index additions automatically). It was also easy to guess that, actually, 'commit' is not as ACID as the DBMS operation with the same name. **Q** : Is there a way to ensure repo-altering operations respect atomicity? i.e. if the electricity goes down again, and I'm committing, I'd like my filesystem to not be in a corrupt state.


title: Should I use git for project files, other than the actual source?

text: I have a lot of small projects, and while their source code is backed up and tracked with git, I don't know what to do with the rest of the files associated with a project. These consist of small text files, some images, maybe a prototype or proof of concept, etc. They're not necessary to build or deploy, but I need them while working on the project. It's not really documentation, but rather todo lists, bugs to be fixed, a few screenshots, that sort of thing. As I said before, they're small projects so I don't think I should create a wiki/bugtracker for each one, especially since I'm the only developer :) I backup these, but I feel they could benefit from git as well (in another repository). I've sorted these files in three main folders, "current", "abandoned", and "finished". **Should I use git and just`git mv` the files when the project is finished or abandoned ? I'm a bit new to git, and I don't know how well tools "like" whole folders that move.** If you have a better way of keeping track of those files, I'm interested. It's probably too broad for a SE question, though.


title: Can you overuse delegates and events

text: I've just started getting to grips with event driven programming and I'm finding delegates and events to be very useful. Since starting to see the potential I've began using them all the time to solve problems such as updating displays between controls and calling stored procedures following updates etc. I'm starting to use them so frequently that I'm creating and subscribing to events more than I'm actually calling methods manually within the code. Are there any rules to follow in order to know when an event should be used or just a plain old simple function call? Any advice is greatly appreciated. Thanks


title: How to handle the fear of future licensing issues of third-party products in software development?

text: The company I work for recently purchased some third party libraries from a very well-known, established vendor. There is some fear among management that the possibility exists that our license to use the software could be revoked somehow. The example I'm hearing is of something like a patent issue; i.e. the company we purchased the libraries from could be sued and legally lose the ability to distribute and provide the libraries. The big fear is that we get some sort of notice that we have to cease usage of the libraries entirely, and have some small time period to do so. As a result of this fear, our ability to use these libraries (which the company has spent money on...) is being limited, at the cost of many hours worth of development time. Specifically, we're having to develop lots of the features that the library already incorporates. Should we be limiting ourselves in this way? Is it possible for the perpetual license granted to us by the third party to be revoked in the case of something like a patent issue, and are there any examples of something like this happening? Most importantly, if this is something to legitimately be concerned about, how do people ever go about taking advantage third-party software while preparing for the possibility of losing that capability entirely? P.S. - I understand that this will venture into legal knowledge, and that none of the answers provided can be construed as legal advice in any fashion.


title: Production or Custom Test Data for Unit Testing?

text: I've recently had a little disagreement with fellow developers. We're transforming various ontologies from the original source format (Pica+, RDF, etc) into our data format and have several converters dedicated to exactly this task. The argument came whether or not we should use the full ontology- data file, or create a subset specifically used for testing. I argued the case for a subset: a custom-created file of all use-cases required to confirm the converters are running correctly. They argued that a production file is always up-to-date and any change in the production file will break the tests. True, I said, but if a change of production files is needed, then invariable the requirements are changed, therefore this is not a fault of using test data. They considered this a very weak argument and summarily decided against the use of a custom-created test-file. The question, as it boils down to, is whether or not to use the in-production file for testing our converters, or a subset of data. What are the pros- and cons? I'm very much in favor of using a test-file for converting, but I'm willing to assume that my premise is flawed. If I am correct, is there any way in which I can more eloquently and persuasively argue my case?


title: How does one design his various architecture/business models?

text: I'm currently learning about various application design approaches and there's one thing I can't really get my head around. Let's say I have a physical device in my network, an IP surveillance camera. I need a model that represents 'IP surveillance cameras' to work with them in my application, which might look like this:               public class IPCamera {              public string     Token      { get; set; }         public IPAddress  IPAddress  { get; set; }         public string     RtspUri    { get; set; }          }      Now, if I want to store the IPCamera into a database (e.g. with Entity Framework), I need maybe another properties and thus, another model with:                  public int         Id         { get; set; }      Oh.. I want to access my application with via a WCF service. I can't use the object "IPAddress" here because it's not very serialization friendly, hence I need another model with a custom IP class that stores the IP address as string. And last, an Android clients wants to access my data. I design a RESTful API using WebApi2. The client isn't interested in the cameras RTSPUri, but wants to know about the current state (is online, is offline). I'm wondering: How to name all these models that they don't come in conflict? Should I design a model per each purpose/layer/service? And how to link/map them? With the adapter pattern?


title: Regarding little endian and big endian conversion

text: I have a query regarding big endian and little endian. Basically the conversion is used to `reverse the byte order in memory` . When we need to do the conversion, do we need convert each and every data types?


title: Missed question in technical phone interview and the follow up letter

text: I may have just bombed a C++ technical phone interview. The interviewer asked mostly about data structures and I was able to go into detail about each of the data structures he asked about. Score one for me I'm thinking. Wrong. Then he asks to join me on a collaboration website where he can see what I am typing. This was the same process as interview #1 which went well, not perfect, but well. So the question was: How do you reverse a linked list? he gave a function prototype similar to               Node *reverse(Node *head)      I struggled with this for about 10-15 minutes until the hour was up. I was able to get the general idea across but was not able to reverse the link list. My question is that after remembering the answer post interview do I mention this in the thank you letter, if I even should write one?


title: How do you outsource website design?

text: I am planning to start a website. I am not good at designing. I am planning to outsource the designing part. How should I do it? Should I program first and then ask the designers to work on it? Or should I get a design from them and then work on it? What do you prefer?


title: Test to confirm message with random component

text: I'm writing an authentication system which uses XML formatted messages between client/server. A successful username/password authentication needs to return a randomly generated session ID to the client:               <?xml version="1.0"?>     <amhAPI>         <auth>             <sessionId>728c91ea-2ead-4fa9-93c5-3a8453174bea</sessionId>         </auth>     </amhAPI>      How do I write a unit test which can confirm the format of the success message, since I can't simply do a straight string match due to the random component?


title: Where to implement thread-safety logic for my queue data structure?

text: I will immediately confess that I do _very_ little multithreading, so questions of style and organization in this domain a little fresh to me. I've written a data structure (in Python, if that matters) which implements a special kind of a queue. I'd like to use this queue to pass messages between threads. Currently, the only logic I have has nothing to do with threads, and simply implements the "special sauce" of organizing messages in this queue. I like having this queue as a data structure that has nothing to do with threads, just like any other data structure. However, I need to use mutexes, condition variables, etc. to implement the thread safety logic. The question is, where does this logic go? Do I write a class, say, `SpecialQueueConcurrent` derived from `SpecialQueue`? Do I write a class that wraps `SpecialQueue` instead of deriving from it? Do I provide an option to make it concurrent in the constructor? How is this usually done?


title: Java/C# - When should AOT be considered if reverse engineering is a concern?

text: Long and short is really in the question title. For a language which compiles to an intermediate language like MSIL or Java byte-code, if there's concern about something like reverse engineering or hacking to disable security features, should AOT (ahead of time) compilation be considered rather than just obfuscation? Obviously, there's a bit of wiggle room in this question as there's no one answer I wouldn't imagine, but when would you start looking at performing an AOT compilation before distributing something versus sending it out obfuscated?    For anyone that stumbles across this and isn't familiar: Wikipedia Entry on AOT Compilers: http://en.wikipedia.org/wiki/AOT_compiler Mono AOT Compiler feature: http://www.mono-project.com/AOT


title: How to handle conflicts between developers in your team?

text: This is happening in every team. For some reasons, conflicts arise in the team and they affect the overall motivation and productivity. What is your recommended approach to solve that common problem? _Examples_ :   * one part of the team wants to implement dependency injection, the other part think it's a waste of time.   * some developers think the rest of the team is slowing down development (which explains why they are late on the schedule)   * personal incompatibilities between one or more developers   * one developer refuse to talk to another one (without apparent reason)


title: Describe the best deployment environment you've worked with

text: The Joel Test includes the question: > Can you make a build in one step? Which is important, but I'm wondering, how streamlined have some of the _deployment_ processes been? All software from shrink-wrap to web applies: what's the best deployment environment you've worked with, and what steps were involved?


title: Why do XML namespace URIs use the http scheme?

text: A XML namespace should be a URI, but it can use any URI scheme, including those that are not URLs. Then why do all widely used XML namespaces use the http scheme (e.g. `http://www.w3.org/XML/1998/namespace`), considering that trying to use the URI as an URL by retrieving that document using the HTTP protocol is not guaranteed to do anything useful (and often doesn't)? I understand the usefulness of DNS domains in namespace names to help guarantee uniqueness. But that doesn't require the http scheme, there could be a separate scheme for that (something like `namespace:w3.org/XML/1998/namespace`). This would avoid the confusion between URIs and URLs, while maintaining domain-based uniqueness.


title: How can I make a universal construction more efficient?

text: A "universal construction" is a wrapper class for a sequential object that enables it to be linearized (a strong consistency condition for concurrent objects). For instance, here's an adapted wait-free construction, in Java, from [1], which presumes the existence of a wait-free queue that satisfies the interface `WFQ` (which only requires one-time consensus between threads) and assumes a `Sequential` interface:               public interface WFQ<T> // "FIFO" iteration     {         int enqueue(T t); // returns the sequence number of t         Iterable<T> iterateUntil(int max); // iterates until sequence max     }     public interface Sequential     {         // Apply an invocation (method + arguments)         // and get a response (return value + state)         Response apply(Invocation i);      }     public interface Factory<T> { T generate(); } // generate new default object     public interface Universal extends Sequential {}          public class SlowUniversal implements Universal     {         Factory<? extends Sequential> generator;         WFQ<Invocation> wfq = new WFQ<Invocation>();         Universal(Factory<? extends Sequential> g) { generator = g; }          public Response apply(Invocation i)         {             int max = wfq.enqueue(i);             Sequential s = generator.generate();             for(Invocation invoc : wfq.iterateUntil(max))                 s.apply(invoc);             return s.apply(i);         }     }      This implementation isn't very satisfying, however, since it presumes determinism of a `Sequential` and is really slow. I attempted to add memory recycling:               public interface WFQD<T> extends WFQ<T>         { T dequeue(int n); } // dequeues only when n is the tail, else assists other threads     public interface CopyableSequential extends Sequential { CopyableSequential copy(); }          public class RecyclingUniversal implements Universal     {         WFQD<CopyableSequential> wfqd = new WFQD<CopyableSequential>();         Universal(CopyableSequential init) { wfqd.enqueue(init); }          public Response apply(Invocation i)         {             int max = wfqd.enqueue(i);             CopyableSequential cs = null;             int ctr = max;             for(CopyableSequential csq : wfq.iterateUntil(max))                 if(--max == 0) cs = csq.copy();             wfqd.dequeue(max);             return cs.apply(i);         }     }      **Here are my specific questions regarding the extension:**   1. Does my implementation create a linearizable multi-threaded version of a `CopyableSequential`?   2. Is it possible extend memory recycling without extending the interface (perhaps my new methods trivialize the problem)?   3. My implementation only reduces memory when a thread returns, so can this be strengthened?   4. [1] provided an implementation for `WFQ<T>`, not `WFQD<T>` \- one does exist, though, correct? [1] Herlihy and Shavit, _The Art of Multiprocessor Programming_.


title: What is "using namespace" pollution?

text: I was looking at the google coding guide [here] and they do not recommend that one use the `using namespace or`namespace:function` - if I did not misinterpret it. Does this apply to `std` as well? `cout<<` does not work without it. This book, recommends the same. So how do I go about using `cout<<` without `using namespace std;` or `std::cout<<` ? What is the recommended way? `std::cout<<`? Most c++ text books teach beginners with `using namespace std;` are they propagating poor coding practice?


title: When is it OK to sacrifice the "neatness" of the design to get a project done?

text: When working on a product that needs to be done soon and work well, when is it OK to sacrifice maintainability and "neatness" of design in order to get the thing done and out the door quickly? And to what degree is it OK, especially when the techniques used to make it "neat" are new to me?


title: Multi-Branch Retail System,how to control items quantity for various branches?

text: Currently I am developing Multi-Branch Retail software. All branches have the same set of items. However, each one has its own stock quantity. My question is, what is the best practice to apply in branch quantity control for items? I am currently thinking about the following design:               Item Table      ========     -Id      -Description          Branch Table      ========     -Id     -Description          Branch Quantities Table      ========     -Id      -ItemId (FK to Item Table)     -BranchId (Fk to Branch Table)     -Quantity (This contains the quantity for a specific item)           Is this a good design? or any suggestions?


title: MVC Communication Pattern

text: This is kind of a follow up question to this http://stackoverflow.com/questions/23743285/model-view-controller-and- callbacks, but I wanted to post it separately, because its kind of a different topic. I'm working on a multiplayer cardgame for the Android platform. I split the project into MVC which fits the needs pretty good, but I'm currently stuck because I can't figure out a good way to communicate between the different parts. I have everything setup and working with the controller being a big state machine, which is called over and over from the gameloop, and calls getter methods from the GUI and the android/network part to get the input. The input itself in the GUI and network is set by inputlisteners that set a local variable which I read in the getter method. So far so good, this is working. But my problem is, the controller has to check every input separately,so if I want to add an input I have to check in which states its valid and call the getter method from all these states. This is not good, and lets the code look pretty ugly, makes additions uncomfortable and adds redundance. So what I've got from the question I mentioned above is that some kind of command or event pattern will fit my needs. What I want to do is to create a shared and threadsafe queue in the controller and instead of calling all these getter methods, I just check the queue for new input and proceed it. On the other side, the GUI and network don't have all these getters, but instead create an event or command and send it to the controller through, for example, observer/observable. Now my problem: I can't figure out a way, for these commands/events to fit a common interface (which the queue can store) and still transport different kind of data (button clicks, cards that are played, the player id the command comes from, synchronization data etc.). If I design the communication as command pattern, I have to stick all the information that is needed to execute the command into it when its created, that's impossible because the GUI or network has no knowledge of all the things the controller needs to execute stuff that needs to be done when for example a card is played. I thought about getting this stuff into the command when executing it. But over all the different commands I have, I would need all the information the controller has, and thus give the command a reference to the controller which would make everything in it public, which is real bad design I guess. So, I could try some kind of event pattern. I have to transport data in the event. So, like the command, I would have an interface, which all events have in common, and can be stored in the shared queue. I could create a big enum with all the different events that a are possible, save one of these enums in the actual event, and build a big switch case for the events, to proceed different stuff for different events. The problem here: I have different data for all the events. But I need a common interface, to store the events in a queue. How do I get the specific data, if I can only access the event through the interface? Even if that wouldn't be a problem, I'm creating another big switch case, which looks ugly, and when i want to add a new event, I have to create the event itself, the case, the enum, and the method that's called with the data. I could of course check the event with the enum and cast it to its type, so I can call event type specific methods that give me the data I need, but that looks like bad design too.


title: Is there an alternative to the term "calling object"?

text: Let's suppose you've got a class defined (in pseudocode):               class Puppy {         // ...         string sound = "Rawr!";              void bark() {             print(sound);         }     }      And say, given a `Puppy` instance, you call it's `bark()` method:               int main() {            Puppy p;       p.bark();          }      Notice how `bark()` uses the member variable `sound`. In many contexts, I've seen folks describe `sound` as the member variable of the "calling object." My question is, what's a better term to use than "calling object?" To me, the object is not doing any calling. We know that member functions are in a way just functions with an implicit `this` or `self` parameter. I've come up with "receiving object," or "message recipient," which makes sense if you're down with the "messaging" paradigm. Do any of you happy hackers have a term that you like to use? I feel it should mean "the object upon which a method is called" and TOUWAMIC just doesn't cut it. As for who the "caller" is, I would say that `main` instantiates a Puppy object and calls its `bark()` method.


title: How can I make an app using mobile's camera to detect words?

text: I am trying to make an app that will capture the video from the mobile's camera and detect in real time all the text that will be captured. I would like to make it in C# (for e.g. Windows Mobile) but I can also try to do it in Java (for e.g. Android). Can anyone help me how can I start with it?


title: Can someone explain to me C#'s coding convention?

text: I recently started working with Unity3D and primarily scripting with C#. As, I normally program in Java, the differences aren't too great but I still referred to a crash course just to make sure I am on the right track. However, My biggest curiosity with C# is that is capitalises the first letter its method names (eg. java: getPrime() C#: GetPrime() aka: Pascal Case?). Is there a good reason for this? I understand from the crash course page that I read that apparently it's convention for .Net and I have no way of ever changing it, but I am curious to hear why it was done like this as opposed to the normal (relative?) camel case that, say, Java uses. Note: I understand that languages have their own coding conventions (python methods are all lower case which also applies in this question) but I've never really understood why it isn't formalised into a standard.


title: Why is there a 20 and not 21 in some versions of Planning Poker?

text: In Planning Poker, cards usually contain numbers of the Fibonacci sequence, which is 0,1,1,2,3,5,8,13,21,34,55 etc. However, you can see on the Wikipedia page (and this has been confirmed to me by people that work at several positions where Planning Poker is applied) in some editions the cards stray away from Fibonacci sequence after 13. They lower 21 to 20 and then continue with 40 and 100. Is there some rationale on why these values have been changed, specifically 21 to 20? (Also note that some other cards are added, such as ? and 1/2, but these are easier for me to understand, compared to the 21 -> 20 shift.)


title: Class design issue

text: I'm new to OOP and a lot of times I become stumped in situations similar to this example: Task: Generate an XML document that contains information about a person. Assume the information is readily available in a database. Here is an example of the structure:               <Person>         <Name>John Doe</Name>         <Age>21</Age>         <Address>             <Street>100 Main St.</Street>             <City>Sylvania</City>             <State>OH</State>         </Address>         <Relatives>             <Parents>                 <Mother>                     <Name>Jane Doe</Name>                 </Mother>                 <Father>                     <Name>John Doe Sr.</Name>                 </Father>             </Parents>             <Siblings>                 <Brother>                     <Name>Jeff Doe</Name>                 </Brother>                 <Brother>                     <Name>Steven Doe</Name>                 </Brother>             </Siblings>         </Relatives>     </Person>        * Ok lets create a class for each tag (ie: Person, Name, Age, Address) Lets assume each class is only responsible for itself and the elements directly contained    * Each class will know (have defined by default) the classes that are directly contained within them    * Each class will have a process() function that will add itself and its children to the XML document we are creating    * When a child is drawn, as in the previous line, we will have them call process() as well   * Now we are in a recursive loop where each object draws their children until all are drawn   * But what if only some of the tags need to be drawn, and the rest are optional? Some are optional based on if the data exists (if we have it, we must draw it), and some are optional based on the preferences of the user generating the document   * How do we make sure each object has the data it needs to draw itself and its children? We can pass down a massive array through every object, but that seems shitty doesn't it? We could have each object query the database for it, but that's a lot of queries, and how does it know what its query is?    * What if we want to get rid of a tag later? There is no way to reference them. I've been thinking about this for 20 hours now. I feel like I am misunderstanding a design principle or am just approaching this all wrong. How would you go about programming something like this? I suppose this problem could apply to any scenario where there are classes that create other classes, but the classes created need information to run. How do I get the information to them in a way that doesn't seem messy?


title: How to Avoid a Busy Loop Inside a Function That Returns the Object That's Being Waited For

text: I have a function which has the same interface as Python's `input` builtin, but it works in a client-server environment. When it's called, the function, which runs in the server, sends a message to the client, asking it to get some input from the user. The user enters some stuff, or dismisses the prompt, and the result is passed back to the server, which passes it to the function. The function then returns the result. The function must work like Python's `input` [that's the spec], so it must block until it has the result. This is all working, but it uses a busy loop, which, in practice, could easily be spinning for many minutes. Currently, the function tells the client to get the input, passing an id. The client returns the result with the id. The server puts the result in a dictionary, with the id as the key. The function basically waits for that key to exist.               def input():              '''simplified example'''              key = unique_key()         tell_client_to_get_input(key)         while key not in dictionary: pass         return dictionary.pop(pin)      Using a callback would be the normal way to go, but the `input` function must block until the result is available, so I can't see how that could work. The spec can't change, as Python will be using the new `input` function for stuff like `help` and `pdb`, which provide their own little REPLs. I have a lot of flexibility in terms of how everything works overall, but just can't budge on the function acting exactly like Python's. Is there any way to return the result as soon as it's available, without the busy loop?


title: How PHP manages memory in this case?

text: I have a **very** basic question, so sorry if this is not the place for it. If I have a file "config.php" with some configurations in some variables and in some page I include this file, each time the variables will be loaded again in the memory of the server? I think the answer is yes, but I'm not sure, I don't know to much of the PHP lifecycle. I don't know if I made myself clear, so here is an example. Suppose, I have the config.php file as:               <?php          $databaseConfig = array();          /* Sets the configurations inside the array */     ?>      Then my index.php page includes the file config.php. Each time the index is loaded the $databaseConfig array will be loaded into memory or just the first time and so when the page is requested again it doens't need to load it again? I really think that since PHP is stateless it will load again each time. Thanks very much in advance!


title: How to match responses from a server with their corresponding requests?

text: There is a server that responds to requests on a socket. The client has functions to emit requests and functions to handle responses from the server. The problem is that the request sending function and the response handling function are two unrelated functions. Given a server response X, how can I know whether it's a response to request X or some other request Y? I would like to make a construct that would ensure that response X is definitely the answer to request X and also to make a function requestX() that returns response X and not some other response Y. This question is mostly about the general programming approach and not about any specific language construct. Preferably, though, the answer would involve Ruby, TCP sockets, and PHP. My code so far:               require 'socket'          class TheConnection         def initialize(config)             @config = config         end         def send(s)             toConsole("--> #{s}")             @conn.send "#{s}\n", 0          end         def connect()             # Connect to the server             begin                 @conn = TCPSocket.open(@config['server'], @config['port'])             rescue Interrupt             rescue Exception => detail                 toConsole('Exception: ' + detail.message())                 print detail.backtrace.join('\n')                 retry             end         end         def getSpecificAnswer(input)             send "GET #{input}"         end         def handle_server_input(s)             case s.strip                 when /^Hello. (.*)$/i                     toConsole "[ Server says hello ]"                     send "Hello to you too! #{$1}"                               else                     toConsole(s)             end         end         def main_loop()             while true                 ready = select([@conn, $stdin], nil, nil, nil)                 next if !ready                 for s in ready[0]                     if s == $stdin then                         return if $stdin.eof                         s = $stdin.gets                         send s                     elsif s == @conn then                         return if @conn.eof                         s = @conn.gets                         handle_server_input(s)                     end                 end             end         end         def toConsole(msg)             t = Time.new             puts t.strftime("[%H:%M:%S]") + ' ' + msg         end     end     @config = Hash[         'server'=>'test.server.com',         'port'=>'2020'     ]     $conn = TheConnection.new(@config)     $conn.connect()     $conn.getSpecificAnswer('itemsX')          begin         $conn.main_loop()     rescue Interrupt     rescue Exception => detail         $conn.toConsole('Exception: ' + detail.message())         print detail.backtrace.join('\n')         retry     end


title: Relative Scoring system - How to solve this?

text: I am trying to assign scores to phone's specifications to calculate a final rating score for each phone. However, when I was scoring based on megapixels, I found that one of the phones 'A' has a 41MP camera. But all other phones have 8MP or less, which is pretty good for a phone. Right now, when I grade relatively wrt phone A (rating 5/5), all other phones get a score of 1 or 2 out of 5. I would like it to be a little more fair, as it was just one phone with a very high value. Could you suggest me the best way to go about solving this issue where the relative grading is more fair?