title: Classic inheritance problem?

text: I keep seeing the following pattern when people learn about OOP: Problem: How do I put objects of different but related types into a container? Solution: Inherit from a common base class. New problem: I have a bunch of base class objects, how do I get the real type? Solution: ??? The classic inheritance example is to make a graphics program that deals with geometric objects. We have `Circle`s, `Ellipse`s and `Triangle`s. All these objects have a common base `Drawable`. ![Drawable](http://i.stack.imgur.com/LuLXm.png) In C++ this might look something like this:               struct Drawable{         virtual ~Drawable(){}         virtual void draw() const = 0;     };          struct Triangle : Drawable{         Point p1, p2, p3;         void draw() const override;         void stretch(double xfactor, double yfactor);         std::touple<double, double, double> getAngles() const;         //...     };          struct Circle : Drawable{         double radius;         void draw() const override;         //...     };          struct Ellipse : Drawable{         double radius;         void draw() const override;         //...     };          std::vector<Drawable *> drawables = {new Circle, new Triangle, new Ellipse};     for (const auto &d : drawables)         d->draw();      So far so good. Now I want to increase the radius of my `Circle`s and `Ellipse`s. As far as I know there are 4 ways to do that: 1: Put everything into the base class. The base class gets the virtual functions `getAngles`, `getRadius`, `stretch` and `getEccentricity`. There is a default implementation for each so that for example `getRadius` returns some dummy value when you are dealing with a `Triangle`. After this is done you can easily iterate over the `Drawable`s and increase their radius. This makes the base class ridiculously huge and working on a `vector<Drawable *>` becomes inefficient because the functions do nothing for most elements. 2: Use `dynamic_cast` hacks.               for (const auto &d : drawables){         if (dynamic_cast<Circle *>(d))             ((Circle *)d)->radius++;         else if (dynamic_cast<Ellipse *>(d))             ((Ellipse *)d)->radius++;     }      Unfortunately you need to repeat this ugly syntax every time you need to do something like this. You cannot put it in a function or macro. Every time a new `Drawable` is added you have to go through the whole code base and add it where appropriate. Also the `if`/`else`-chain is fairly inefficient. 3: Add a Tag as the first member variable and cast accordingly.               for (const auto &d : drawables){         switch(d->tag){             case Tag::Circle:                 ((Circle *)d)->radius++;                 break;             case Tag::Ellipse:                 ((Ellipse *)d)->radius++;                 break;         }     }      Slightly more efficient due to a switch instead of an `if`/`else`-chain, but there is already a kind of tag that shows the dynamic type, so the tag is redundant. Also it has the same problem as 2: since you need to change the whole code base whenever a new `Drawable` comes along. 4: Just keep the objects in separate containers.               vector<Circle> circles;     vector<Triangle> triangles;     vector<Ellipse> ellipses;     for (auto &c : circles)         c.radius++;     for (auto &e : ellipses)         e.radius++;      This is very efficient memory layout wise and you only iterate over objects that matter. It is my favorite, but unfortunately it breaks the first solution in that you do not keep differently typed objects in a single container. I tried to solve the problem by creating a variadic template that internally has a `vector` per type and forwards insertions to the right container. Ideally it would completely hide the fact that there are different containers under the hood. Usage would look something like this:               MultiVector<Triangle, Circle, Ellipse> mv;     mv.push_back(Triangle());     mv.push_back(Circle());     mv.push_back(Ellipse());     for (auto &d : mv.get<Circle, Ellipse>())         d.radius++;      The solution is not perfect, for example different types do not keep their order and implementing the iteration is tricky. I presented this problem and solution attempt to my (university) research group and got the reactions " _If you design your classes right this is not a problem_ " and " _The proposed solution is a very specific tool to solve a very specific problem and it is questionable at best to add even more complexity to c++ for such a minor detail_ ". In my opinion this is a very basic problem that needs fixing and the usual solution of better class design only tries to find the least evil of the 4 workarounds in the specific case without actually solving the problem. The problem comes up almost every time inheritance is used. So finally here is the question: Did you run into this problem too / is this a real problem? Do you know of another workaround/solution? Do other languages deal better with the problem? I want to simulate a poll using 2 comments below so feel free to upvote either " _I never had this problem / The problem is easily solved._ " or " _I also had this problem and never solved it to my satisfaction._ " Edit: To prevent a close due to primarily opinion based / discussion: I want a clear answer that solves the problem or some resource that says that there is none. Edit: Related: Do I really have a car in my garage?


title: Using lambdas to improve encapsulation

text: Just as many people believe tenaciously in small functions, some people believe lambdas should only contain small code fragments. An often overlooked advantage of lambdas however, is using them you can **encapsulate behavior which you would otherwise have to make available to the entire class**. Isn't it is a true advantage to maintain proper encapsulation, regardless of line count? Which possible disadvantages of using anonymous functions with a lot of lines of code am I overlooking? * * * The following is an actual example. `argumentsMatch` does very specific argument matching, highly dependent on the behavior of the function in which it is defined. The following code IMHO follows the Single Responsibility Principle. Moving `argumentsMatch` to a private method would result in it only being called from within this method.               /// <summary>     ///   Get the first found matching generic type.     ///   The type parameters of the generic type are optional.     ///   E.g. Dictionary<,>     ///   When full (generic) type is known (e.g. Dictionary<string,string>),     ///   the "is" operator is most likely more performant,     ///   but this function will still work correctly.     /// </summary>     /// <param name = "source">The source for this extension method.</param>     /// <param name = "type">The type to check for.</param>     /// <returns>     ///   The first found matching complete generic type,     ///   or null when no matching type found.     /// </returns>     public static Type GetMatchingGenericType( this Type source, Type type )     {         Type[] genericArguments = type.GetGenericArguments();         Type rawType = type.IsGenericType ? type.GetGenericTypeDefinition() : type;              // Used to compare type arguments and see whether they match.         Func<Type[], bool> argumentsMatch             = arguments => genericArguments                 .Zip( arguments, Tuple.Create )                 .All( t => t.Item1.IsGenericParameter || // No type specified.                            t.Item1 == t.Item2 );              Type matchingType = null;         if ( type.IsInterface )         {             // Traverse across all interfaces to find a matching interface.             matchingType =                  (from t in source.GetInterfaces()                  let rawInterface = t.IsGenericType ? t.GetGenericTypeDefinition() : t                  where rawInterface == rawType &&                        argumentsMatch( t.GetGenericArguments() )                  select t).FirstOrDefault();         }         else         {             // Traverse across the type, and all it's base types.             Type baseType = source;             while ( baseType != null && baseType != typeof( object ) )             {                 Type rawCurrent = baseType.IsGenericType                     ? baseType.GetGenericTypeDefinition()                     : baseType;                 if ( rawType == rawCurrent )                 {                     // Same raw generic type, compare type arguments.                     if ( argumentsMatch( baseType.GetGenericArguments() ) )                     {                         matchingType = baseType;                         break;                     }                 }                 baseType = baseType.BaseType;             }         }              return matchingType;     }


title: sizeof style: sizeof(type) or sizeof variable?

text: I've seen two styles of using `sizeof` for memory-related operations (such as in `memset` or `malloc`):   * `sizeof(type)`, and   * `sizeof variable` or `sizeof(variable)` Which one would you prefer, or would you use a mix of the two styles, and when would you use each style? What are the pros and cons of each style and when you use them? As an example, I can see the following pair of situations where one style helps and the other doesn't: When you get the pointer indirection wrong:               type *var;     ...     memset(var, 0, sizeof var);    /* oops */      When the type changes:               new_type var;    /* changed from old_type to new_type */     ...     memset(&var, 0, sizeof(old_type));    /* oops */


title: Keeping track of all objects of a class

text: I'm new to object-oriented programming, and I keep running into this issue. (I'm programming in Java) I've been a bit reluctant to ask about this, since it seems like such a basic issue, but I can't find any information on it, or questions about it here, and none of the textbooks I have read (on a quite basic level of course) have touched on this issue: Often I need to keep track of all objects of a class that have been created, to iterate through them for various purposes. They way I currently write programs, many objects are only referenced from other objects, meaning I have no array or collection with which to reference them all. I imagine that, as this seems like such a very basic necessity in OOP, there should be a quite institutionalized, and simple, way to go about this? Is it usual practice to keep a separate list of all the objects of a class? I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited? I realize this question might not have one easy answer; I just hope someone can enlighten me a bit on this subject. I feel like if I'm lacking a central piece of knowledge here.


title: IXRepository and test problems

text: Recently had a doubt about how and where to test repository methods.   Let the following situation: I have an interface `IRepository` like this:               public interface IRepository<T>         where T: class, IEntity     {         IQueryable<T> Query(Expression<Func<T, bool>> expression);         // ... Omitted     }      And a generic implementation of `IRepository`               public class Repository<T> : IRepository<T>         where T : class, IEntity     {         public IQueryable<T> Query(Expression<Func<T, bool>> expression)         {             return All().Where(expression).AsQueryable();         }     }      This is an implementation base that can be used by any repository. It contains the basic implementation of **my ORM**. Some repositories have specific filters, in which case we will `IEmployeeRepository` with a specific filter:               public interface IEmployeeRepository : IRepository<Employee>     {         IQueryable<Employee> GetInactiveEmployees();     }      And the implementation of `IEmployeeRepository`:               public class EmployeeRepository : Repository<Employee>, IEmployeeRepository // TODO: I have a dependency with ORM  at this point in Repository<Employee>. How to solve? How to test the GetInactiveEmployees method     {         public IQueryable<Employee> GetInactiveEmployees()         {             return Query(p => p.Status != StatusEmployeeEnum.Active || p.StartDate < DateTime.Now);         }     }      ## Questions   1. Is right to inherit `Repository<Employee>`?   The goal is to reuse code once all implementing `IRepository` already been made. If `EmployeeRepository` inherit only `IEmployeeRepository`, I have to literally copy and paste the code of `Repository<T>`.   2. In our example, in `EmployeeRepository : Repository<Employee>` our `Repository` lies in our ORM layer. We have a dependency here with our ORM impossible to perform some **unit test**.   3. How to create a **unit test** to ensure that the filter `GetInactiveEmployees` return all Employees in which the Status != Active and StartDate < DateTime.Now. I can not create a Fake/Mock of `IEmployeeRepository` because I would be testing? Need to test the actual implementation of `GetInactiveEmployees`. The complete code can be found on Github


title: The Request/Response Cycle

text: When User A decides he want to pay a visit to http://example.com/ it all begins with a Request. A short moment later he is given a Response. In this cycle Request-Response a lot is going on, in different frameworks it's decoupled in different components among them Routing, Dispatching, etc. I'm looking to make a simple experimental MVP Framework for my learning, trying to use as many best practices, heck who knows it might even be worth using when I'm done. I'm not sure how I should decouple this cycle in to these different components and I'm not even sure of what each component is responsible for (Thinking SOLID, DRY, SRP, etc). That is what I am asking, looking at different frameworks these components seem to have different use-areas from time to time. What is each of these components responsible for and in what order are the used? Request, Response, Dispatcher, Router, Front Controller, Bootstrap, Events.


title: Difficulties With TDD & Refactoring (Or - Why Is This More Painful Than It Should Be?)

text: I wanted to teach myself to use the TDD approach and I had a project I had been wanting to work on for a while. It wasn't a large project so I thought it would be a good candidate for TDD. However, I feel like something has gone awry. Let me give an example: At a high level my project is an add-in for Microsoft OneNote that will allow me to track and manage Projects more easily. Now, I also wanted to keep the business logic for this as decoupled from OneNote as possible in-case I decided to build my own custom storage and back end some day. First I started with a basic plain words acceptance test to outline what I wanted my first feature to do. It looks something like this (dumbing it down for brevity):   1. User clicks create project   2. User types in title of project   3. Verify that the project is created correctly Skipping over the UI stuff and some intermediary planning I come to my first unit test:               [TestMethod]     public void CreateProject_BasicParameters_ProjectIsValid()     {         var testController = new Controller();         Project newProject = testController(A.Dummy<String>());         Assert.IsNotNull(newProject);     }      So far so good. Red, green, refactor, etc. Alright now it needs actually save stuff. Cutting out some steps here I wind up with this.               [TestMethod]     public void CreateProject_BasicParameters_ProjectMatchesExpected()     {         var fakeDataStore = A.Fake<IDataStore>();         var testController = new Controller(fakeDataStore);         String expectedTitle = fixture.Create<String>("Title");         Project newProject = testController(expectedTitle);              Assert.AreEqual(expectedTitle, newProject.Title);     }      I'm still feeling good at this point. I don't have a concrete data store yet, but I created the interface how I anticipated it would look. I'm going to skip a few steps here because this post is getting long enough, but I followed similar processes and eventually I get to this test for my data store:               [TestMethod]     public void SaveNewProject_BasicParameters_RequestsNewPage()     {         /* snip init code */         testDataStore.SaveNewProject(A.Dummy<IProject>());         A.CallTo(() => oneNoteInterop.SavePage()).MustHaveHappened();     }      This was good until I tried to implement it:               public String SaveNewProject(IProject project)     {         Page projectPage = oneNoteInterop.CreatePage(...);     }      And THERE is the problem right where the "..." is. I realize now at THIS point that CreatePage requires a section ID. I didn't realize this back when I was thinking at the controller level because I was only concerned with testing the bits relevant to the controller. However, all the way down here I now realize I have to ask the user for a location to store the project. Now I have to add a location ID to the datastore, then add one to the project, then add one to the controller, and add it to ALL of the tests that are already written for all of those things. It has become tedious very quickly and I can't help but feel like I would have caught this quicker if I sketched out the design ahead of time rather than letting it be designed during the TDD process. Can someone please explain to me if I've done something wrong in this process? Is there anyway this kind of refactoring can be avoided? Or is this common? If it is common are there any ways of making it more painless? Thanks all!


title: Multiple arguments in function call vs single array

text: I have a function that takes in a set of parameters, then applies to them as conditions to an SQL query. However, while I favored a single argument array containing the conditions themselves:               function searchQuery($params = array()) {         foreach($params as $param => $value) {             switch ($param) {                 case 'name':                     $query->where('name', $value);                     break;                 case 'phone':                     $query->join('phone');                     $query->where('phone', $value);                     break;             }         }     }      My colleague preferred listing all the arguments explicitly instead:               function searchQuery($name = '', $phone = '') {         if ($name) {             $query->where('name', $value);         }              if ($phone) {             $query->join('phone');             $query->where('phone', $value);         }     }      His argument was that by listing the arguments explicitly, the behavior of the function becomes more apparent - as opposed to having to delve into the code to find out what the mysterious argument `$param` was. My problem was that this gets very verbose when dealing with a lot of arguments, like 10+. Is there any preferred practice? My worst-case scenario would be seeing something like the following: `searchQuery('', '', '', '', '', '', '', '', '', '', '', '', 'search_query')`


title: Is it worth to move from ASP webforms to ASP MVC?

text: I have one year experience on ASP.net webforms and now I decided to move to another company where ASP MVC is the architecture. I decided because I always felt its not the real way to develop apps on web.(single form architecture and viewstate). But I know that I can accomplish everything on MVC on webforms with a controlled architecture? Will it give a value in job market if I moved to ASP MVC?


title: How viable is it to switch stacks for setting up a startup

text: I am currently employed with a company for 2.5 years and I have been working with the .net stack for the entire duration mainly on the MVC framework. I _believe_ I have some cool ideas for a startup but I am not sure if I should continue in this stack or switch to some other stack like Ruby on Rails. The reason why I am consider this switch is due to the Infrastructure required to host a dot net application and scaling it successfully as compared to setting up a live running site on some other stack. I have a really good domain expertise in dot net at this moment but I believe it should be not so hard to move onto a new stack and adopt the best practices that I have picked up in the past two years. Let me know if I am missing something in the puzzle and if I am taking the right decision? Are there any complications of learning a new stack and building on it? Please guide me in the right direction.


title: Using a try-finally (without catch) vs enum-state validation

text: I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible. My dilemma on the best practice is whether one should use a try/catch/finally to return an enum _(or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case)_ so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it? From what I can gather, this might be different depending on the case, so the original advice seems odd. For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself. Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside? **Update:** I was expecting a fatal/non-fatal exception for the main classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback. Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are _designing_ it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead? Synopsis: **How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?**


title: Syncing chat on android device with web application

text: I am trying to make a chat application in android. Just a one on one chat. However I also want the chat to be synced with the web app that runs on the browser. I am confused about how to go about it. So I want my web app as well as the android app to be in sync. I have 2 things in mind. One,use metoerjs for frontend and php for backend connected with a mongodb. I am inclined towards metoerjs for front end because it seamlessly syncs with the mongodb object and is a good real time js library. This would require me hosting my php script on an apache server and the front end running on node. Is it possible to make http post requests to the meteor js server(and add stuff to my database) through my android device? If it is then I can do away with using php, and develop both the client and server side in javascript. Second, use some xmpp client to set up the chat on android.But I have no idea how am I supposed to connect it to my webserver. I am a complete beginner with server side scripting in javascript, noSQL databases and the xmpp protocol. So I would really appreciate if someone could point me in the right direction.


title: Optimizing sorting large amounts of text stored in a database

text: How would you store text information - in a relational database or maybe using NoSQL? The problem is that the text should be divided into various parts, each of which satisfies to some requirement, e.g. the same text should be contained in several "places". Is there another way to organize this? I have several books (each of them about 600 pages), which should be stored in a database, but there will be a mechanism which should sort the content of the books by some criteria. The criteria are complex, so I wonder if it is becoming a big problem. Would it help to store the same text in various "tables", each of which would satisfy a concrete "condition" Do I need to save the same text in various "tables", each of which satisfies a specific set of criteria?


title: How do software development methodologies fit in the field of consulting?

text: I work for a fairly small consulting company, roughly 100 employees, and I've been with them for about a year currently. This is my first job out of college. As a company we do not specialize in any specific technology, but my day-to-day usually consists of some sort of .NET programming, whether it be ASP.NET, custom SharePoint development, etc. Our projects generally consist of adding features to, or expanding, a client's existing code-base. Rarely we will build web applications from the ground up. Something that has been bothering me is the distinct lack of any sort of methodology or framework that helps us deliver quality solutions to clients. We do not conduct code reviews, the testing we do seems weak, technical direction seems lackluster. It seems that little effort is made to ensure the code the team commits to a project meets any sort of standard of extensibility and maintainability or adheres to any best practices for the given environment. From my experience thus far, leaving that responsibility solely up to the individual programmer yields some lackluster results especially when inexperienced members of the team are involved. I would like to know if this is business as usual in the consulting world. If you work at a consulting firm, I would like to hear about any techniques, processes, or approaches that are used to make sure the solution your team is developing avoids becoming a mess, all the while under the restriction that you are working on a client's existing code-base that you may not have complete control of. What can I do as a junior member of the team to promote a culture of producing better software?


title: Philosophy behind the memento pattern

text: I have been reading up on memento pattern from various sources of the internet. Differing information from different sources has left me in confusion regarding why this pattern is actually needed. The dofactory implementation says that the primary intention of this pattern is to restore the state of the system. Wiki says that the primary intention is to be **able** to restore the changes on the system. This gives a different impact - saying that it is possible for a system to have memento implementation with no need to restore. And that ability of restore is a feature of this. OODesign says that > It is sometimes necessary to capture the internal state of an object at some > point and have the ability to restore the object to that state later in > time. Such a case is useful in case of error or failure. So, my question is why exactly do we use this one? Is it to save previous states - or to promote encapsulation between the Caretaker and the Memento? Why is this type of encapsulation so important? Edit: For those visiting, check out this Implementation! **Edit** : I am working in implementing a memento solution to my problem. I will post another question regarding that and link that question to this one. Thanks all for responding with valuable suggestions! **Edit 3** : Here is the link to my sample implementation


title: Non-transactional Database and Integration Testing

text: One issue I think I am going to run into with my integration testing is having multiple tests accessing the same database. While this is not a problem now, I know we have multiple applications here that access the same database and I am just trying to think of a way to prevent this issue before it happens. An idea I have seen a lot is using transactions. In the start up you start a transaction and then in the teardown you rollback the transaction. This means that multiple tests accessing the same database tables and will not effect each other which is great. The issue I have is that in my case, 85-95% of the tables I am working with in MySQL are MyISAM which don't support transactions. Are there any ways to get around storage engines that don't support transaction but still allowing multiple test to access the same tables without them effecting each other? From what I hear, the ruby on rails testing framework uses transactions in this way, how do they get around this issue (or do they)?


title: How does Ruby, Python, PHP manage without Spring?

text: I write enterprise Java applications and web services at work (Spring, Hibernate, Maven, RESTEasy) and PHP (CakePHP) and Python (Django) for my side projects. While I do see the value that Inversion of Control, Aspect Oriented Programming etc. that Spring brings in, I am not sure how massive web applications that are not on the Java stack manage without a framework like Spring. So, do the developers just have to "put up with" tightly coupled components and other grievances that Spring eliminates or am I missing something? For those unfamiliar with Spring, the features we use the most are:   * Inversion of Control container: configuration of application components and lifecycle management of Java objects,   * Aspect-oriented programming: enables implementation of cross-cutting routines,   * Transaction management: unifies several transaction management APIs and coordinates transactions for Java objects.


title: Why we should (not) develop on a server via RDP

text: I have a client who is requesting that we develop their fairly small web application directly in their environment by RDP to the server that will host the app. They have had a contractor do this for a while and it has worked "fine" for them, so they are comfortable with that approach. The client's biggest concern at this point is cutting costs - they have a very tight budget. My manager does not seem to care or think that it makes a difference. However, I strongly do not agree with that practice. How best can I convince the client that it is bad practice to do things that way? I need to use "management" language, not developer language. I can think of a few advantages of developing locally (as a developer):   1. We can not guarantee code quality in the remote environment (why not?)   2. Internal team collaboration increases efficiency (how?)   3. Internally, we can take better advantage of source control (although that can also be installed on the server)   4. Internally, we can follow better quality control processes   5. With RDP, only one developer can work on project at a time   6. Developing locally increases a developer's efficiency (how? maybe because it is their comfort zone? maybe with multiple monitors? how does that benefit the client?) Unfortunately, these do not necessarily translate to something management appreciates (e.g. dollars and cents) Please help.


title: Why isn't there an html tag "field"?

text:
There is a `<fieldset>` tag for a set of fields. Why isn't there a hierarchical child for fieldsets?               <form>         <fieldset>             <legend>Thin Sandwich Options</legend>             <field>                 Meat
                                              <input type="radio" name="meat" value="turkey" />Turkey                                              <input type="radio" name="meat" value="monkey" />Monkey

Pick one meat for the thin sandwich.
             </field>             <field>                 Cheese
                                              <input type="checkbox" name="cheese" value="chedder" />Cheddar                                              <input type="checkbox" name="cheese" value="swiss" />Swiss

Pick one meat for the thin sandwich.
             </field>         </fieldset>         <fieldset>             <legend>Beverage Options</legend>             <field>                 Carbonated
                                              <input type="radio" name="carbonated" value="coke" />Coke                                              <input type="radio" name="carbonated" value="mtn-dew" />Dew

Pick one beverage per combo.
             </field>             <field>                 Non Carbonated
                                              <input type="radio" name="non-carbonated" value="tea-sweet" />Tea (non sweetend)                                              <input type="radio" name="non-carbonated" value="tea" />Tea
             </field>         </fieldset>     </form>      http://jsfiddle.net/5dC8c/ I keep coming back to this question whenever I am working on my HTML form layouts. As MDN defines it: > The HTML `<fieldset>` element is used to group several controls as well as > labels () within a web form. I see a `<field>` element as grouping a single control (or set of radio buttons) with a single label and a description. The field tag would have some of the same attributes that the input tag has, readonly, required, etc. Why does bootstrap use the class 'form-group'? Why does Wufoo use li tags for each field? Enclosing related form elements into fields would add clarity. Every major front-end framework has some class or tag to differentiate each field. Why the heck don't we have a single HTML tag to bring some normality to form design? **Update:** added a better HTML example of the usage of a `<field>` tag.


title: How to indicate reliability when reporting availability of competencies

text: We have employees with competencies:               Pete      Welder               Carpenter     Melissa   Carpenter            Assume they both work 40 hours/week, and have not yet been assigned work.   We need to report the availability of these competencies, expressed in hours.   As far as I can see now, we can report this in two ways: Method A. When someone has multiple competencies, count them both.               Welder    40 hours     Carpenter 80 hours      Method B. When someone has multiple competencies, count an equal division of hours for each               Welder    20 hours     Carpenter 60 hours      Method A has our preference:   \- A good planner will know to plan the least available competency first. If 30 hours of welding is planned, we will be left with 10 _welder_ , 50 _carpenter_.   \- Method B has the disadvantage that the planner thinks he cannot plan the job when 30 hours of welding is required. However, if we report this **we would like to give an estimate of the reliability of the numbers for each competency** , i.e. how much are these over-reported? In my example A, would I say that _carpenter_ is 100% over-reported, or 50%, or maybe another number?   How would I calculate this for large numbers of competencies?   I'm sure we are not the first ones dealing with this, is there a 'usual' way of doing this in planning? Additionally:   \- Would there be an even better method than A or B?   \- Optionally, we also have an _preference order_ of competencies (like: use him/her in this order), Pete could be 1. _welder_ 2\. _carpenter_. Does this introduce new options?


title: Are the "practical" chapters at the end of the Siebel's PCL book supposed to be skipped during the first pass?

text: Just completed the first pass through Peter Siebel's Practical Common Lisp. I'm fairly comfortable with C#, Ruby, Java; The chapters that teach Lisp and the early 'practical' chapters were easy on my brain. However towards the end of the book, the practical chapters (on binary serialization, id3 parsing, web programming and the HTML generating DSL) seemed to be just out of reach - I recognized the primitives and methods being used ; but the means of combination left me flabbergasted. e.g. Given the specs, I couldn't sit down and write that code on my own.. I skipped some of them and strafed through the rest. Are there other who felt that there was a missing level between the first 22 chapters and the practicals ? Or is it just me ? Should I read the basics again? Or is there another book that will help me cross the chasm ?


title: Choosing a programming language allowing that affinities of the customer?

text: I would like to have some professional opinion about the programming language used for a project in a company. Let's explain me... In my company, the first argument to choose Java as the main language is its name and its popularity from the perspective of the customer. It appears that if you propose to develop the client's software in Python/Ruby/..., he is less convinced. I would like to know if you are experiencing this kind of situation and what you think about that ?


title: What makes one language any better than another when both are designed for the same goals?

text: I'm in the process of creating a grammar for a scripting language but as I'm working on it I started to wonder what makes a language good in the first place. I know the goals for my script but there are always 1000 different ways to go about doing things. Goals:   * Easy to use and understand (not my grandma could do it easy, but the secretary at the front desk could do it or the VP of marketing could do it type of easy)   * No user defined functions or subroutines.   * Its use would be in events of objects in a system similar to HyperCard. Conceptually I was thinking of a language like this:               set myVariable to 'Hello World'     set counter to 0     repeat 5 times with x     begin         set counter to counter add x     end     set myVariable to myVariable plus ' ' plus counter     popup myVariable          set text of label named 'label' to 'new text'     set color of label named 'label' to blue      The end result would popup a dialog with the contents `Hello World 15` it would also change the text of a label and make it blue. But I could do the same thing 1000 different ways. So what makes one language any better than another when both are designed for the same goals?


title: Whole Solution Complexity ... vs Development Complexity

text: I am generally a PHP Developer that deals in a few different MVC frameworks. I am being tempted (like most) to break out of my comfortable LAMP environment in pursuit of a "prettier" and "more simple" language, attached to frameworks that are becoming more and more popular. I agree with most arguments to switching to a (the) ruby framework or a python framework, and would trade out PHP for Python in the LAMP acronym any day of the week. But as I've found in trying to get started with these, it's not quite that simple... In my attempts to figure out the spaghetti of dependencies, versions, and install procedures, I've found that while final development time/simplicity is a benefit, in my mind it is almost overshadowed by the complexity of deployment... Especially being use to the copy/paste deployment to the ever numerous lamp hosting services. I am specifically speaking of   * Ruby on Rails   * Django (python) To those that work in these platforms, was your initial experience similar? if so how did you overcome it?


title: how to tell users to wait, becase page is loading

text: On my webpage, i have to generate some excel and pdf files but the user has to wait until the file is generated. the scenario is this: user press a link and waits until the files are generated and displayed as a links on the raports page. how can i 'tell' to the user to wait?


title: How to document/verify consistent layering?

text: I have recently moved to the dark side: I am now a CUSTOMER of software development -- mainly websites. With this new role comes new concerns. As a programmer i know how solid an application becomes when it is properly layered, and I want to use this knowledge in my new job. I don't want business logic in my presentation layer, and certainly not presentation stuff in my data layer. Thus, I want to be able to demand from my supllier that they document the level of layering, and how neat and consistent the layering is. The big question is: How is the level of layering documented to me as a customer, and is that a reasonable demmand for me to have, so I don't have to look in the code (I'm not supposed to do that anymore)?


title: A RESTful way to verify server state

text: I'm interested in building verifications into a REST service to help with service monitoring. For example, one could run assertions like `http://example.com/posts/verify?min-posts=5&since=1-hour-ago` which would respond with an error unless 5 new posts had been created in the past hour. Are there any existing services like this, or best practices? I'm particularly interested in a recommended error code for failed verifications, as I can't really see anything appropriate in the 4xx series. Errors like "Precondition Required" and "Internal Server Error" are more about the actual request or processing of it, than the meaning of it.


title: Should POCO domain classes contain collections?

text: The question title is not good, but I couldn't think of a way to word it better. I am used to develop using POCO classes in my projects, that is, domain objects contain absolutely no logic, only data. I am wondering which is the best approach when dealing with class relationships - to put a collection inside the class or to request it later. For example, consider we have an e-commerce application, that has Orders, and Items inside those Orders. So we could have (pseudo-code)               class Order     {          int id;          List<OrderItem> Items;     }          class OrderItem     {          Product product;          int quantity;     }      And then use it (1)               var o = LoadOrder(id);     foreach (var i in o.Items) {      ...or we could do:               class Order     {         int id;     }      And use it this way: (2)               var odr = LoadOrder(id);     var itms = LoadItemsOfOrder(odr);     foreach (var i in itms) {          .....      The first way is more compact and more "OOP-ish", but the second way gives more control on how and when items are requested, e.g. what if now I need to request only the items that have quantity > 3 ? And what if I don't use the Items collection at all (e.g. to display only a list of orders) - I will be doing unnecessary queries to the database. In my older, big projects I've gone with a hybrid approach - the domain classes are of the first flavor but there are various "load" methods, like "LoadOrder" and "LoadOrderWithItems" or "FillOrderObject". Now I am working on a small, toy project, no customers and crazy deadlines and got time to think on these issues. I tried searching the web but it is very hard to find a POCO answer not related to Entity Framework. (I am not working in .net this time, but would like to apply these concepts.) **Question** : is there a method which is clearly _better_ than the other, or both are valid and "it depends" on my project, if I am aiming for performance or for code clarity and maintainability?.


title: I feel lost among the various web technologies and I'm looking for pointers

text: In the last 3-5 months I was thinking about which web programming language I should use. PHP? Ruby? C#? Python? Perl? And you know what? Every time I keep changing my mind like crazy! I learn some things about each one of them and then move to another. Now I'm totally lost, totally lost guys. :) What I want form you is to help me to decide, not to decide for me, and give me some recommendations. It would be more than helpful if you can tell me a short story about yourself, how you got started, where you are now and what web programming technologies you are using.


title: UML Diagrams of Multi-Threaded Applications

text: For single-threaded applications I like to use class diagrams to get an overview of the architecture of that application. This type of diagram, however, hasn’t been very helpful when trying to understand heavily multi- threaded/concurrent applications, for instance because different instances of a class "live" on different threads (meaning accessing an instance is save only from the one thread it lives on). Consequently, associations between classes don’t necessarily mean that I can call methods on those objects, but instead I have to make that call on the target object's thread. Most literature I have dug up on the topic such as _Designing Concurrent, Distributed, and Real-Time Applications with UML_ by Hassan Gomaa had some nice ideas, such as drawing thread boundaries into object diagrams, but overall seemed a bit too academic and wordy to be really useful. I don’t want to use these diagrams as a high-level view of the problem domain, but rather as a detailed description of my classes/objects, their interactions and the limitations due to thread-boundaries I mentioned above. I would therefore like to know:   1. What types of diagrams have you found to be most helpful in understanding multi-threaded applications?   2. Are there any extensions to classic UML that take into account the peculiarities of multi-threaded applications, e.g. through annotations illustrating that      * some objects might live in a certain thread while others have no thread-affinity;     * some fields of an object may be read from any thread, but written to only from one;     * some methods are synchronous and return a result while others are asynchronous that get requests queued up and return results for instance via a callback on a different thread.


title: What did Stallman mean in this quote about implementing other languages in Lisp?

text: I just read the following quote from Stallman as part of a speech he gave many years ago. He's talking about how it is feasible to implement other programming languages in Lisp, but not feasible to implement Lisp in those other programming languages. He seems to take for granted that the listeners/readers understand why. But I don't see why. I think the answer will explain something about Lisp to me, and I'd like to understand it. Can someone explain it? Here's the quote: > "There's an interesting benefit you can get from using such a powerful > language as a version of Lisp as your primary extensibility language. You > can implement other languages by translating them into your primary > language. If your primary language is TCL, you can't very easily implement > Lisp by translating it into TCL. But if your primary language is Lisp, it's > not that hard to implement other things by translating them." The full speech is here: http://www.gnu.org/gnu/rms-lisp.html Thanks.


title: SQL IN() versus OR

text: I was working with a query I wrote today had to change the code from the `WHERE` clause to use a IN(list of stuff) filter instead of using something like               item_desc = 'item 1'     OR item_desc = 'item 2'     OR item_desc = 'item 3'     OR item_desc = 'item 4'      The above ran for 15 minutes and returned nothing, yet the following gave me my result set in 1.5 minutes               item_desc IN (     'item 1'     ,'item 2'     ,'item 3'     ,'item 4'     )      I did this in SQL and am wondering why the IN(list of items) performed so much faster then the OR statement. \-- EDIT -- SQL Server 2008, I do apologize for not putting this bit of info in in the first place. **Here is the Query in its entirety using the`OR` statements:**               DECLARE @SD DATETIME     DECLARE @ED DATETIME     SET @SD = '2013-06-01';     SET @ED = '2013-06-15';          -- COLUMN SELECTION     SELECT PV.PtNo_Num AS 'VISIT ID'     , PV.Med_Rec_No AS 'MRN'     , PV.vst_start_dtime AS 'ADMIT'     , PV.vst_end_dtime AS 'DISC'     , PV.Days_Stay AS 'LOS'     , PV.pt_type AS 'PT TYPE'     , PV.hosp_svc AS 'HOSP SVC'     , SO.ord_no AS 'ORDER NUMBER'     --, SO.ent_dtime AS 'ORDER ENTRY TIME'     --, DATEDIFF(HOUR,PV.vst_start_dtime,SO.ent_dtime) AS 'ADM TO ENTRY HOURS'     , SO.svc_desc AS 'ORDER DESCRIPTION'     , OSM.ord_sts AS 'ORDER STATUS'     , SOS.prcs_dtime AS 'ORDER STATUS TIME'     , DATEDIFF(DAY,PV.vst_start_dtime,SOS.prcs_dtime) AS 'ADM TO ORD STS IN DAYS'          -- DB(S) USED     FROM smsdss.BMH_PLM_PtAcct_V PV     JOIN smsmir.sr_ord SO     ON PV.PtNo_Num = SO.episode_no     JOIN smsmir.sr_ord_sts_hist SOS     ON SO.ord_no = SOS.ord_no     JOIN smsmir.ord_sts_modf_mstr OSM     ON SOS.hist_sts = OSM.ord_sts_modf_cd          -- FILTER(S)     WHERE PV.Adm_Date BETWEEN @SD AND @ED     AND SO.svc_cd = 'PCO_REMFOLEY'     OR SO.svc_cd = 'PCO_INSRTFOLEY'     OR SO.svc_cd = 'PCO_INSTFOLEY'     OR SO.svc_cd = 'PCO_URIMETER'          AND SO.ord_no NOT IN (         SELECT SO.ord_no         FRROM smsdss.BMH_PLM_PtAcct_V PV         JOIN smsmir.sr_ord SO         ON PV.PtNo_Num = SO.episode_no         JOIN smsmir.sr_ord_sts_hist SOS         ON SO.ord_no = SOS.ord_no         JOIN smsmir.ord_sts_modf_mstr OSM         ON SOS.hist_sts = OSM.ord_sts_modf_cd         WHERE OSM.ord_sts = 'DISCONTINUE'         AND SO.svc_cd = 'PCO_REMFOLEY'         OR SO.svc_cd = 'PCO_INSRTFOLEY'         OR SO.svc_cd = 'PCO_INSTFOLEY'         OR SO.svc_cd = 'PCO_URIMETER'     )     ORDER BY PV.PtNo_Num, SO.ord_no, SOS.prcs_dtime      Thank you,


title: Open-sourcing a proprietary library without certain features

text: I hope I'm in the right place to ask that. I have a question regarding the practice of open-sourcing a proprietary library that we built and use at work. The licence will probably be MIT. I like the idea, but here comes the unusual part : I have been tasked to remove some of the most advanced features. Those will remain on our servers, available as a service. We will open-source the (JavaScript in case it is of interest) library, along with a minimal associated server code. I am _not_ asking a question about the technical problems (I imagine we will have to maintain and synchronize somehow different repositories, maybe with incompatible pull requests, but this question is for another day). What I would like to know is:   * How that would be perceived by the community at large ? Does it risk killing the eventual interest in this library?   * I don't personally know of any library that works like that. I'm pretty sure it is possible however, but any evidence of such a library is welcome (successful if possible). That's also because I'd like to see how they present it.   * More importantly, what could be the rationale for/against it? I'm not sure I understand the consequences of doing it so. **EDIT** After learning a thing or two from the answers and comments, I've collected here a few examples :   * http://www.jfrog.com/home/v_artifactorypro_overview   * http://www.easyrtc.com/pricing/   * http://rapidminer.com/the-core-of-rapidminer-is-open-source/ (note the angry comments on this one - but we're doing the opposite, from proprietary to open-core) As a developer, I would use the product we are going to release it in personal projects, so I think it's useful. But I have been working on it and I have an obvious bias. Also, most feedback I've seen basically says "you can try, but it won't work". See also http://blogs.gartner.com/brian_prentice/2010/03/31/open-core-the- emperors-new-clothes/ If someone is able to find a successful product doing open-core, I'd be grateful.


title: How to handle updated configuration when it's already been cloned for editing

text: Really sorry about the title that probably doesn't make much sense. Hopefully I can explain myself better here as it's something that's kinda bugged me for ages, and is now becoming a pressing concern as I write a bit of software with configuration. Most software comes with default configuration options stored in the app itself, and then there's a configuration file (let's say) that a user can edit. Once created/edited for the first time, subsequent updates to the application can not (easily) modify this configuration file for fear of clobbering the user's own changes to the default configuration. So my question is, if my application adds a new configurable parameter, what's the best way to aid discoverability of the setting and allow the user (developer) to override it as nicely as possible given the following constraints:   * I actually don't have a canonical default config in the application per se, it's more of a 'cascading filesystem'-like affair - the config template is stored in `default/config.json` and when the user wishes to edit the configuration, it's copied to `user/config.json`. If a user config is found it is used - there is no automatic overriding of a subset of keys, the whole new file is used and that's that. If there's no user config the default config is used. When a user wishes to edit the config they run a command to 'generate' it for them (which simply copies the `config.json` file from the `default` to the `user` directory).   * There is no UI for the configuration options as it's not appropriate to the userbase (think of my software as a library or something, the users are developers, the config is done in the user/config.json file).   * Due to my software being library-like there's no simple way to, on updating of the software, run some tasks automatically (so any ideas of look at the current config, compare to template config, add ing missing keys) aren't appropriate. The only solution I can think of right now is to say "there's a new config setting `X`" in release notes, but this doesn't seem ideal to me. If you want any more information let me know. The above specifics are not actually 100% true to my situation, but they represent the problem equally well with lower complexity. If you do want specifics, however, I can explain the exact setup. * * * Further clarification of the type of configuration I mean: think of the Atom code editor. There appears to be a default 'template' config file somewhere, but as soon as a configuration option is edited `~/.atom/config.cson` is generated and the setting goes in there. From now on is Atom is updated and gets a new configuration key, this file cannot be overwritten by Atom without a lot of effort to ensure that the addition/modification of the key does not clobber. In Atom's case, because there is a GUI for editing settings, they can get away with just adding the UI for the new setting into the UI to aid 'discoverability' of the new setting. I don't have that luxury. * * * Clarification of my constraints and what I'm actually looking for: The software I'm writing is actually a package for a larger system. This larger system is what provides the configuration, and the way it works is kinda fixed - I just do a `config('some.key')` kinda call and it knows to look to see if the user has a config clone and if so use it, otherwise use the default config which is part of my package. Now, while I _could_ make my application edit the user's configuration files (there is a convention about where they're stored), it's generally not done, so I'd like to live with the constraints of the system I'm using if possible. And it's not just about discoverability either, one large concern is that the addition of a configuration key won't actually work as soon as the user has their own copy of the original template. Adding the key to the template won't make a difference as that file is never read. As such, I think this is actually quite a big flaw in the design of the configuration cascading system and thus needs to be taken up with my upstream. So, thinking about it, based on my constraints, I don't think there's going to be a good solution save for either editing the user's configuration or using a new config file every time there are updates to the default configuration. Even the release notes idea from above isn't doable as, if the user does not follow the advice, suddenly I have a config key with no value (user-defined _or_ default). * * * So the new question is this: what is the general way to solve the problem of having a default configuration in template config files and allowing a user to make user-specific version of these in order to override the defaults? A per- key cascade (rather than per-file cascade) where the user only specifies their overrides? In this case, what happens if a configuration value is an array - do we replace or append to the default (or, more realistically, how does the user specify whether they wish to replace or append to)? It seems like configuration is kinda hard, so how is it solved in the wild?


title: Multithreading: am I doing it wrong?

text: I'm working on an application that plays music. During playback, often things need to happen on separate threads because they need to happen simultaneously. For example, the notes of a chord need to be heard together, so each one is assigned its own thread to be played in. (Edit to clarify: calling `note.play()` freezes the thread until the note is done playing, and this is why I need three separate threads to have three notes heard at the same time.) This kind of behavior creates many threads during playback of a piece of music. For example, consider a piece of music with a short melody and short accompanying chord progression. The entire melody can be played on a single thread, but the progression needs three threads to play, since each of its chords contains three notes. So the pseudo-code for playing a progression looks like this:               void playProgression(Progression prog){         for(Chord chord : prog)             for(Note note : chord)                 runOnNewThread( func(){ note.play(); } );     }      So assuming the progression has 4 chords, and we play it twice, than we are opening `3 notes * 4 chords * 2 times` = 24 threads. And this is just for playing it once. Actually, it works fine in practice. I don't notice any noticeable latency, or bugs resulting from this. But I wanted to ask if this is correct practice, or if I'm doing something fundamentally wrong. Is it reasonable to create so many threads each time the user pushes a button? If not, how can I do it differently?


title: Is gettext appropriate for internationalizing user help documentation?

text: On my project, we have po files to internationalize/translate various labels, error messages, button-text etc. We also have separate po files for the entirety of our help documentation, which is included in the product. Is this an appropriate use of gettext - putting entire documents in po files as opposed to just labels and messages? The format has been made all the more complicated because sometimes (for tooltips or "what's this" icons) only a small part of the help doc is needed, resulting in single phrases/paragraphs being entries in the po file, which are then concatenated together when the user views the help... making the actual act of translation challenging. Is there a better way to internationalize end user help documentation?


title: Use open-source programs in your company?

text: Is there any cons of making your employees use open-source programs in your company? I am planning to start a bussiness and I wonder why companies usually work with proprietary software, as _Microsoft Word_ to quote the most famous one. Why do not they use _Open Office_ (or _Libre Office_ ) etc.? From my point of view, you can save a lot of money and help the open-source community by, for instance, giving them part of your benefits in form of donations. I do not know any (medium-big) company that does this. Probably you could give me some examples, just to prove that this model of open-source usage/collaboration ~~works~~ rocks.


title: How can I set "no subprocess" for Python IDLE other than shortcut

text: I have been able to get my favorite Python tool, Python iDLE, to work by starting it with a windows shortcut to IDLE.BAT with a -n (no subprocess) at the end of the TARGET string. Is there a different/better way to do it so I don't need to use a windows shortcut?


title: How to Implement Restricted Access to Application Features

text: I'm currently developing a web application, that provides some ' ** _service_** ' to the user. The user will have to select a ' ** _plan_** ' according to which she/he will be allowed to perform application specific actions but up to a limit defined by the plan.   A Plan will also limit access to certain features, which will not be available at all for some plans.      As an **example** : say there are 3 **plans** , 2 **actions** throughout the application   * users in plan-1 can perform action-1 3 times, and they can't perform action-2 at all   * users in plan-2 can perform action-1 10 times, action-2 5 times   * users in plan-3 can perform action-1 20 times, action-2 10 times So I am looking for the best way to get this done, and my main concerns besides implementing it, are the following(in no particular order)   * **maintainability/changeability** : the number of plans, and type of features/actions **will** change in the final product   * **industry standard/best practice** : for future readiness   * **efficiency** : of course, I want fast code!! I have never done anything like this before, so I have **no clue** about how do I go about implementing these functionalities. **Any tips/guides/patterns/resources/examples?**   I've read a little about ACL, RBAC, are they the patterns that I need to follow?   Really, any sort of feedback will help.


title: What is good (neat) architecture in programming?

text: When I build a simple website, e.g. a contact book where I can add, delete and update contacts, I create an `index.php` file where a user, if he's not logged in, is requested to enter a password and if he enters the right password, he's assigned a session and can do certain things with the contacts. I have two files:   1. The first (`contacts.php`) is for the HTML code to be shown. Above the HTML code I include the second file and create the class.   2. The second (`contacts_class.php`) contains all methods for adding, deleting and updating. I think that's ok, but when it comes to implement a big project, how should I do it? Do I have to create folders for every page and put files in them (like above, HTML and class), and how should I do it? What is a good and neat architecture for building large projects that every other programmer would understand perfectly?


title: What is the "best practice" for converting an external API's data structure?

text: When an API's data structure does not fit well with an angular app, I am trying to determine the best-practice in my specific design and implementation for converting it to a usable structure. I was doing this on an 'as needed' basis within the app controllers/directives, which quickly lead to spaghetti code. Now I'm thinking this belongs in the service/factory which interacts with the API. Are there drawbacks or benefits to the Factory pattern over a more service oriented architecture when it comes to handling data structure conversion?


title: Databases and the CI server

text: I have a CI server (Hudson) which merrily builds, runs unit tests and deploys to the development environment but I'd now like to get it running the integration tests. The integration tests will hit a database and that database will be consistently being changed to contain the data relevant to the test in question. This however leads to a problem - how do I make sure the database is not being splatted with data for one test and then that data being override by a second project before the first set of tests complete? I am current using the "hope" method, which is not working out too badly at the moment, but mostly due to the fact that we only have a small number of integration tests set up on CI. As I see it I have the following options:   * Test-local (in memory) databases    I'm not sure if any in-memory databases handle all the scaryness of Oracles triggers and packages etc, and anything less I don't feel would be a worth while test.   * CI Executor-local databases   A fair amount of work would be needed to set this up and keep 'em up to date, but defiantly an option (most of the work is already done to keep the current CI database up-to-date).   * Single "integration test" executor   Likely the easiest to implement, but would mean the integration tests could fall quite far behind.   * Locking the database (or set of tables) I'm sure I've missed some ways (please add them). How do you run database- based integration tests on the CI server? What issues have you had and what method do you recommend? (Note: While I use Hudson, I'm happy to accept answers for any CI server, the ideas I'm sure will be portable, even if the details are not). Cheers,        Mlk


title: Layer style applied, but intuition is different

text: Currently, I'm developing an architecture for a system of the following kind: There are a couple of existing applications (front end) with which one can define UML profiles capturing some specific domain aspects. Since the tools are proprietary the produced models are not exchangeable by default. On the other hand there are a couple of tools which can analyze the produced frontend models (back end). These also have their own mechanisms (which are different from the frontends) to represent the domain aspects. Since this would produce m*n model transformations with m frontends and n backends, I chose to introduce an exchange model which captures all relevant information from the frontends and nevertheless allows the backend to have enough information for analysis. This approach results in only m+n transformations. My bird-eye view on the architecture: ![Architecture Overview](http://i.stack.imgur.com/uCyfx.jpg) Things go like that: Transformation is possible between frontend model<->exchange model and exchange model<->backend model. Analysis tasks are triggered in the frontend and are delegated to the backend, where they are executed. At the first glance, it looked for me like a layered style, but the more I thought about it, the intuition of the problem is not to make different layers exchangeable, where the layers achieve separation of concerns and focus on portability. It is rather to introduce an intermediate layer, which decouples the two others and targets mainly at extendability. Another point is that the highest abstraction is not found on the highest layer but on the intermediate layer, i.e. the exchange format should be the core of the architecture where frontends and backends can be attached to. It should not need to know anything about its attached frontends or backends. This also means that the backend layer must know how to transform the exchange format into its own model representation, which is a upward usage not allowed in the layered style. This boils down to the **questions** :   1. Do you know some architectural style which is similar to the one I depicted and also follows its intuition?   2. Why isn't this a good example for layered style (apart from the upward usage)?   3. Since the application is mainly model-driven, are there some specific architectural patterns/styles for systems of this kind? Thanks for help in advance! EDIT: Actually I am concerned with layers, because the coarse vision of this architecture is embedded in an existing project and is communicated there as "layers". But from an architectural point of view, it doesn't fit the style. The problem lies between the documentation and the communication of the architecture. If most of the stakeholders talk about a layered architecture and I introduce the layered view into it, although it isn't applied correctly, wouldn't this confuse all stakeholders, who have the right understanding of a layered architecture? The goal is to document the views of the style which is really applied to have a correct basis for communicating the architecture.


title: Authorization and Authentication using multiple types of authentication in MVC

text: Currently I am managing a team where we're building a new SaaS application. The way it is currently structured is that we have a solution that has our business logic and data, and a solution that holds our website (and related projects) In our current user base, there are clients that use different types of authentication:   * username/password using the aspnet membership architecture   * Homegrown SOAP web services that allow a developer to connect via SSO   * SAML Clients may have different settings for logging in, but users within the clients log in the same way. The big challenge with our legacy system is that these are somewhat 'hacked' together and very hard to manage. I want to make sure we are much more scalable for the future. I've looked into claims-based authentication using the MVC framework and understand that pretty well, so I'm confident our team can build the framework to support it. My challenge is with the STS (identity server), so I have a few questions:   1. Fundamentally, am I going in the right direction?    2. What system owns the knowledge of where a user should be authenticated? I would suspect the STS because that would mean the claims-based system can truly not worry about authentication or authorization   3. I've looked into OpenAM, OpenIDM and IdentityServer for the STS, but cannot really figure out how to plug them in. Are these even STS systems?   4. I am willing to spend money on a solution as well, is there any other solutions I should be looking into?


title: Writing a superset of a programming language as a transcompiler

text: My idea is to write a superset of C# (but question is not language-specific), so that it source-to-source compiles (transcompiles) to C# itself (fall- through switch clauses, default method parameters etc., nothing impossible in C#). First idea was to parse it, make syntax trees, abstract trees etc. but it seems as a bit of an overkill to me, mostly because large portions of code will remain the same. **My question:** Is there a simpler way to do this? One of my ideas was to search for tokens that need modifying (e.g. `switch` in case of fall-through) and then rewrite the code (add `goto case NEXT_CASE` where needed) but is there a better and cleaner way to do this?


title: Issues with the intended behavior of a Service layer?

text: This analysis makes sense, and states anything that avoids code duplication and simplifies maintenance speaks for a service layer. What is the technical behavior?   1. When a service client references a service, does it do so at runtime, or does it happen at compile time?    2. When I change something in the service layer code, will this change be automatically taken into account in all it's clients, or do they need to be individually recompiled?    3. How does this make sense from a testing point of view - I have working code, based on some code from a service, but if that service changes, my code might break?!


title: What to do when issue-tracker is down?

text: It has happened in our team that our issue-tracker is down. Happens about once a week now (yes, wow), and there's not really much we can do to get it back up, since it's hosted by our client in a different timezone. It sometimes takes several hours for it to be operative again. In the meanwhile, we can't really tell which issues we were working on, and in case we do, we cannot update those issues, as in moving them through the workflow, logging used hours, checking the issue's description, leaving comments, and so on. So the question is: how can we, as a team, work in the meanwhile so that when the issue-tracker is up again, we have the least possible hassle updating it with what we've been working?


title: Why no client-side HTML include tag?

text: I had a question posed to me the other day by another programmer. I remember (a very long time ago) wondering the very same. **Why was a browser-side include tag never considered? Or was it?** Specifically with a tag that instructed the browser to include additional HTML from other sources. e.g. `<include src="http://server/foo/bar.html">`. Many folks will make javascript calls and fill `innerHTML` to accomplish the same, when the same outside a the javascript engine could be accomplished by the browser. It would have been painful to have nested `<HTML>`s `<BODY>`s (i.e.) but we have to consider that aspect anywhere anyway.


title: Python web frameworks comparisons

text: I recently asked a question on SO about Python web frameworks: http://stackoverflow.com/questions/4909306/python-web-frameworks-vs-java-web- frameworks-how-is-web-development-in-python-do I want to learn one just for fun but it also has to be able to help me deliver a proper working application. I am looking for a framework with lots of features, powerful, mature, with large community, good documentation, books etc. I need something that will help me be more productive in developing my app and not waste time figuring out how to do a certain thing in the framework or how to write workaround around the limitations of the framework. I was thinking one of the following: django, zope, turbogears, pylons. Off course the war is raging out there and there are other alternatives but seems Django is at the top... or is it just hype? I am interested in pros and cons of each. What was the best feature you think the framework has? What is the thing it lacks? What could have been done differently. Help me chose one to learn for starters.


title: Learning the GO programming language and its prospects

text: > **Possible Duplicate:**   >  What are the chances of Google's Go becoming a mainstream language? Recently I've started experimenting with The GO programming language by Google. Its a programmer-friendly language having the simplicity of Python. I was wondering whether companies other than Google would also start using Go for development, and if they do , what would be the prospects of being a Go programmer?


title: What is the motivation that makes you to stick with current job?

text: There are lot of people who are still working in the same company for more than 10 years. What is the motivation that makes you to stick with current job ?


title: Employers paying for fresh graduates for MS Degree?

text: Is this still an option nowadays (aside from working for govt) that in private business a company will help pay for some/all of an MS degree? What is the likelihood of a company paying for a fresh grad to get an MS degree w them helping to pay for it?


title: Why is 0 false?

text: This question may sound dumb, but why does `0` evaluates to `false` and any other [integer] value to `true` is most of programming languages? # String comparison Since the question seems a little bit too simple, I will explain myself a little bit more: first of all, it may seem evident to any programmer, but why wouldn't there be a programming language - there may actually be, but not any I used - where `0` evaluates to `true` and all the other [integer] values to `false`? That one remark may seem random, but I have a few examples where it may have been a good idea. First of all, let's take the example of strings three-way comparison, I will take C's `strcmp` as example: any programmer trying C as his first language may be tempted to write the following code:               if (strcmp(str1, str2)) { // Do something... }      Since `strcmp` returns `0` which evaluates to `false` when the strings are equal, what the beginning programmer tried to do fails miserably and he generally does not understand why at first. Had `0` evaluated to `true` instead, this function could have been used in its most simple expression - the one above - when comparing for equality, and the proper checks for `-1` and `1` would have been done only when needed. We would have considered the return type as `bool` (in our minds I mean) most of the time. Moreover, let's introduce a new type, `sign`, that just takes values `-1`, `0` and `1`. That can be pretty handy. Imagine there is a spaceship operator in C++ and we want it for `std::string` (well, there already is the `compare` function, but spaceship operator is more fun). The declaration would currently be the following one:               sign operator<=>(const std::string& lhs, const std::string& rhs);      Had `0` been evaluated to `true`, the spaceship operator wouldn't even exist, and we could have declared `operator==` that way:               sign operator==(const std::string& lhs, const std::string& rhs);      This `operator==` would have handled three-way comparison at once, and could still be used to perform the following check while still being able to check which string is lexicographically superior to the other when needed:               if (str1 == str2) { // Do something... }      # Old errors handling We now have exceptions, so this part only applies to the old languages where no such thing exist (C for example). If we look at C's standard library (and POSIX one too), we can see for sure that maaaaany functions return `0` when successful and any integer otherwise. I have sadly seen some people do this kind of things:               #define TRUE 0     // ...     if (some_function() == TRUE)     {         // Here, TRUE would mean success...         // Do something     }      If we think about how we think in programming, we often have the following reasoning pattern:               Do something     Did it work?     Yes ->         That's ok, one case to handle     No ->         Why? Many cases to handle      If we think about it again, it would have made sense to put the only neutral value, `0`, to `yes` (and that's how C's functions work), while all the other values can be there to solve the many cases of the `no`. However, in all the programming languages I know (except maybe some experimental esotheric languages), that `yes` evaluates to `false` in an `if` condition, while all the `no` cases evaluate to `true`. There are many situations when "it works" represents one case while "it does not work" represents many probable causes. If we think about it that way, having `0` evaluate to `true` and the rest to `false` would have made much more sense. # Conclusion My conclusion is essentially my original question: why did we design languages where `0` is `false` and the other values are `true`, taking in account my few examples above and maybe some more I did not think of? **Follow-up:** It's nice to see there are many answers with many ideas and as many possible reasons for it to be like that. I love how passionate you seem to be about it. I originaly asked this question out of boredom, but since you seem so passionate, I decided to go a little further and ask about the rationale behind the Boolean choice for 0 and 1 on Math.SE :)


title: Evolutionary behavioural programming resources

text: A while ago I made Conway's Game of Life. I'd like to make something similar (in C++), where each cell would exhibit behaviours such as:   * Movement   * Reproduction   * Killing of other cells (moving onto another cell, for example) Over time, the cells would 'learn', and I'd (hopefully) end up with a set of behaviours that are beneficial to the ecosystem as a whole, rather than the individual cell. I'm 100% sure that this isn't new, but I don't know:   1. What technical terms cover what it is I'm trying to do (what keywords cover my aim such that I can search for other implementations),    2. Resources, preferably online, although dead-tree style is also good, which would be beneficial reading for this type of programming.    3. How I should implement this (#2 would help with this); I can modify my cells to do some things (moving, for example), but I'm not sure how I should implement the learning; should I be using a genetic algorithm or is some other type of evolutionary algorithm better suited?


title: How should I setup a UI for editing a binary tree?

text: I need to allow the user to create an binary tree. I have a Backbone Model populating properly from the database, the problem I am stuck on is how do I setup the ui elements in a way that is fairly easy to use? The general idea is I want to create a boolean expression that contains logic and tokens. The tokens will be replaced later at runtime with appropriate model data when the expression is evaluated. You end up with a final expression like this:               ((({Claim.State})=(TX))||(({Claim.PolicyState})!=(UT)))      Ie, Evaluate to true if the State = TX or the Policy State is not UT Each expression can be a terminating node, and will have a value, or will have no value, and the left and right will point to the next respective expressions and an Operator The database structure looks something like this:   1. State Check: Left: **2** Right: **3** Operator: OR   2. State is TX: Left: **4** Right **5** Operator: Equals   3. State not UT: Left: **6** Right **7** : Operator: Not   4. Claim State: Left: nil Right: nil Value: {Claim.State}   5. Texas Literal: Left: nil Right: nil Value: "TX"   6. Policy State: Left: nil Right: nil Value: {Claim.PolicyState}   7. Utah Literal: Left: nil Right: nil Value: "UT" I am imaging something like for the Above expression, making a panel with 3 select lists, and a Label above it:               ----------------------------------------------------------------      Name: |State Check|                     [.] Value [0] Expression                 Left (Edit/New)   Operator Right (Edit/New)      Expression: [ State is TX ]   [ Or ]   [ State is not UT ]      (Save)     ----------------------------------------------------------------      At this point I'm stuck. What should happen when say, the user wants to edit the left hand value? Do I open a new popup window to rerender the same form, just starting with **2** instead of **1** for the starting expression key? Should I replace the existing form with the new values, and somehow keep track of where the user is in reference to the starting expression? Maybe slide a new editor panel down below the current? What do you guys think? I'm really stuck on what to do.


title: Deploying a very simple application

text: I have a very simple working console application written in C++ linked with a light static library. It is just for testing purposes. Now that the coding part is done, I would like to know the process of actually deploying the program. I wrote a very basic CMakeLists.txt that create makefiles or VS projects to build the sources. I also have a program that calls the static library in order to make some google tests. To me, the distribution of this application goes like this: >   * to developers : the src directory with the CMakeLists.txt file (multi- > platform distribution) with a README.txt and an INSTALL.txt >   * to users : the executable and a README.txt >   * git repo : everything mentioned above plus the sources for testing and > the gtest external lib > A this point : considering the complexity of my application, am I doing it right? Is there any reference that would formalize this deployment process so I can get better and go further ? Say I would like to add dynamic libraries that can be updated, external libraries like boost : how should I package this to deploy it in a professional way?


title: What programming language would be the best fit for small browser games?

text: I want to make small web apps containing little games (multi-user dungeons, tower defense games, and roguelikes) or talent calculators for MMOs etc. After some research I have had people say that ASP.NET MVC would be perfect for these tasks. After looking at it I am unsure as to whether or not this is the right path to to achieve these goals. Which technology would be best to create small, web based browser games?


title: Are there software options (preferabbly .NET) for doing distance and speed analysis of footballers moving on video?

text: Editing Question for Clarity Thanks for feedback so far, very insightful. I'm not sure how far along this part of the software community is, and what if any libraries exist for me to leverage from. Heres what I'm trying to do. Problem: Take an existing video of a game of rugby league. The Rugby League field is 100 metres long, 70 metres wide, and has white line markings every 10 metres running along the width of the field, as well as along the sidelines. Each side has 13 players on the field. Players on each team have identical jerseys that normally constrast strongly against background colours (green/brown field colour) and the referee's colour (usually yellow) and the designated water runner (orange). All players have a unique number in thick white lettering on their backs for identification. Video is taken with a high definition camera. Currently only one camera is used (2D) and existing video does not contain a foreground object of fixed spatial dimensions (as suggested in one answer for comparision measurements, however I could add this to future filming sessions if it is worthwhile). The player's do not run in a straight line 50% of the time but will go sideways on on a diagonal to the play the ball. The distance measured always starts from the spot of the previous "tackle", which ends where the player stops forward movement. It is not always possible to determine the players number from the video (facing other direction, sunlight, others standing in the way of the camera). But this isn't important as the software could allow for manual inputting of unknown "runs" at a later point after analysis. Determine the distance between two points (i.e. where the player started his "run" and where he finished it). I'm guessing that this would be quite doable if I manually marked the start and end point in the video. But how would I use landmarks in the background to determine the distance (assuming the person taking the video has kept it from jerking around). Question: Do software packages or libraries exist that are specialised enough to assist with writing analysis software to determine a sports persons distance travelled based on video taken of the performance?


title: How can I implement an EPUB reader in JavaScript?

text: I'm wondering if I can create an EPUB (free and open e-book standard) reader in JavaScript. The basic requirements would be:   1. Server parts of the EPUB reader from a server API.    2. Read the EPUB data in JavaScript.    3. Render it on page.    4. Provide some extra functionality, like text highlights or page notes.  I have no information about how I could do this. I'm willing to try a prototype project. What are the steps that I could take towards implementing such a thing?


title: Does software testing methodology rely on flawed data?

text: It’s a well-known fact in software engineering that the cost of fixing a bug increases exponentially the later in development that bug is discovered. This is supported by data published in _Code Complete_ and adapted in numerous other publications. However, it turns out that this data never existed. The data cited by _Code Complete_ apparently does not show such a cost / development time correlation, and similar published tables only showed the correlation in some special cases and a flat curve in others (i.e. no increase in cost). **Is there any independent data to corroborate or refute this?** And if true (i.e. if there simply is no data to support this exponentially higher cost for late discovered bugs), **how does this impact software development methodology?**


title: Which order to define getters and setters in?

text: Is there a best practice for the order to define getters and setters in? There seems to be two practices:   * getter/setter pairs   * first getters, then setters (or the other way around) To illuminate the difference here is a Java example of getter/setter pairs:               public class Foo {         private int var1,         var2,         var3;              public int getVar1() {         return var1;         }              public void setVar1(int var1) {         this.var1 = var1;         }              public int getVar2() {         return var2;         }              public void setVar2(int var2) {         this.var2 = var2;         }              public int getVar3() {         return var3;         }              public void setVar3(int var3) {         this.var3 = var3;         }     }      And here is a Java example of first getters, then setters:               public class Foo {         private int var1,         var2,         var3;              public int getVar1() {         return var1;         }              public int getVar2() {         return var2;         }              public int getVar3() {         return var3;         }              public void setVar1(int var1) {         this.var1 = var1;         }              public void setVar2(int var2) {         this.var2 = var2;         }              public void setVar3(int var3) {         this.var3 = var3;         }     }      I think the latter type of ordering is clearer both in code and in class diagrams but I do not know if that is enough to rule out the other type of ordering.


title: How are new[] and malloc implemented in Windows?

text: So when you call malloc or new [] from your C/C++ application, how does the CRT translate it into Windows API calls?


title: How to explain to my customer that the hosting provider is terrible, security-wise?

text: As a freelance developer, I sometimes have to access the administration panels of hosting providers of my customers. It is an astonishingly frightening experience. Below are some points I noticed when accessing recently a not-so- unpopular hosting provider based in UK which has the word "secure" mentioned in large on the home page:   * The default administrative account is created with a **terrible password: five lowercase and digits only characters** , no uppercase, no symbols.   * The password is displayed in several locations in the administration panel, which is a good sign that it's **saved in plain text** in the database.   * This administrative account is used to access _everything_ : FTP, MySQL and the administration panel itself (including personal information, invoices, etc.).   * It is impossible to create additional accounts, which forces the customer to **give the same administrative password to any freelancers who work on the project** (giving them unlimited access to everything).   * The **MySQL database can be accessed from anywhere** , not just locally. This behavior cannot be changed.   * There is **no audit**.   * Nothing helps or invites the customer to do **regular backups**.   * The hosting uses **PHP 5.2.4, a version released on August 30 th, 2007** and cannot be upgraded to a more recent version. For those who are unfamiliar with PHP, the language has frequent updates due to lots of security issues discovered regularly, and running a website in 2012 even with the version released in 2011 is a very bad idea. My experience with other well-known hosting companies in UK, USA and France is similar. Some are slightly better, security-wise, but too many are doing everything they can to enforce worst practices. Then, they claim being secure and easy to use, which gives the feeling that the customer can rely on the hosting provider for everything related to security. * * * What should be the professional response from a developer to the customer regarding such hosting companies? As a developer who have a duty to inform the less technologically knowledgeable customers about the risks they encounter, what should I do?   * Saying shortly that the hosting provider sucks because it's not secure is not a solution: if the hosting provider is not unpopular, the customer will trust the large hosting company, rather than some freelance developer.   * Explaining in details every aspect of security and risk management wouldn't help neither, since it would be too long and boring for the customers to read. Spending hours reconfiguring stuff would be frightening for them too.


title: GO instead of C/C++ with cgo

text: Is it possible to replace C and C++ with Go + cgo and interface frameworks such as Qt or DirectX with Go? Any potential pitfalls I should be aware of? UPDATE: I see that my question was not precise enough. Of course I expected problems with Go concepts that aren't available in C/C++ e.g. goroutines. What I really wanted to know was if you could use Go to replace standard C++ functionality. I hope I can convey my idea: I thought of Go as a "scripting language" to leverage C/C++ libraries with a new language. I'd like to know:   * Can you register Go methods as C/C++ callbacks ?   * Can I supply Go variables as parameters to C/C++ functions ?   * Are their pointers compatible ? Go runs on a native Vm, so I guessed there might be an abstraction layer over the memory that invalidates C/C++ pointers Have you ever used cgo or know about its abilities ?


title: Scalable solution for website polling

text: I'm looking to add push notifications to one of my iOS apps. The app is a client for a website which doesn't offer push notifications. What I've come up with so far:   * App sends a message to home server when transitioning to background, asking the server to start polling the website for the logged in user.    * The home server starts a new process to poll for that user. Polling happens every so many seconds / minutes.   * When the user returns to the iOS app, the app sends a message to the home server to stop polling.   * The home server kills the process polling for the user.   * Repeat. The problem is that this soon becomes stupid: 100s of users means 100s of different processes. It's just not scalable in the slighest. What I've written so far is in PHP, using CURL to do the polling and I started with PHP a few days ago, so maybe I'm missing something obvious that could help me with this. Some advice would be great.


title: Business/Development Liaison Wanting To Enhance Understanding In Programming

text: I lead software development for a team of of about 20 devs and we're primarily a .net/sql server shop. We've recently created a new role in our organization for a more business like role to assist in prioritization of development and this business liaison has asked me if there are any books or resources he could use to better understand software concepts in a meaningful way. Any suggestions or advice would be greatly appreciated.


title: Why can't we write nested shorthand functions in Clojure?

text: I tried to evaluate a Clojure expression with nested shorthand functions today, and it wouldn't let me. The expression was:               (#(+ % (#(+ % (* % %)) %)) 5) ; sorry for the eye bleed      The output was:               IllegalStateException Nested #()s are not allowed  clojure.lang.LispReader$FnReader.invoke (LispReader.java:630)     ...and a bunch of other garbage


title: When should I use static variables with primitive types?

text: Recently I came across the question NSString: Why use static over literal? and in the comments arrived a new question. In Objective-C there some "special" types that are just maps to C primitives. Like the `NSInteger`.               #if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64     typedef long NSInteger;     #else     typedef int NSInteger;     #endif      I know how to use the `static` keywords for objects but I don't understand the implications on C primitive types. When should I use a `static NSInteger x` instead of `NSInteger x`? What happens with the memory in both cases?


title: Has the syntax of any programming language been usability tested?

text: Before being release to the public, has the syntax of any programming language undergone usability testing? If so, what kinds of testing was performed, what were the results, and what impact did the testing results have on the design of the language?


title: CakePHP pair programming practise

text: We are on the stage of planning a CakePHP project. It is a relatively a big project for us, as a developer+project manager, I want to hire someone to work with me. But what I really want is to spend less time on actual coding, without losing control of the code quality. What I want to do is that I will design all the functions of the project in CakePHP, at least all the model's functions, and leave the implementation part to the coder who I am going to hire. But my worry is still if I am going to lose control of the code quality using this approach? is it feasible to do so or it is going to turn this project to a chaos. Thank you all in advanced for reading my question and give me answers.


title: Should you fix preexisting defects while working on something else?

text: Conundrum: During the course of working on a new feature or fixing a defect, you find a legacy problem in code. What should you do? Fix it and risk altering the behavior of the code. It has either been working up until now by some fluke, or else the defect has not been detected or worth anyone's time to report. Should you leave it alone and allow the problem to make the code harder to work with later? Fixing the problem will only add to the time of your original task and force you to regression test. Few will appreciate the work. Fixing it, however, seems right somehow. Code with fewer problems is easier to refactor and build upon. I've been finding myself in this situation time and time again as we work to modernize a web application. I can't tell if I'm being obsessive or honorable when I go off-tangent working on these old bugs. How do you handle these situations? Thanks, Corey


title: In MVC should a model handle validation?

text: I am trying to re-architect a web application I developed to use the MVC pattern, but I'm not sure if validation should be handled in the model or not. For example, I'm setting up one of my models like this:               class AM_Products extends AM_Object      {         public function save( $new_data = array() )          {             // Save code         }     }      **First Question:** So I'm wondering if my save method should call a validation function on $new_data or assume that the data has already been validated? Also, if it were to offer validation, I'm thinking some of the model code to define data types would look like this:               class AM_Products extends AM_Object     {         protected function init() // Called by __construct in AM_Object         {             // This would match up to the database column `age`             register_property( 'age', 'Age', array( 'type' => 'int', 'min' => 10, 'max' => 30 ) );          }     }      **Second Question:** Every child class of AM_Object would run register_property for each column in the database of that specific object. I'm not sure if this is a good way of doing it or not. **Third Question:** If validation should be handled by the model, should it return an error message or an error code and have the view use the code to display an appropriate message?