title: Codeigniter + JQuery + Processing.js to replace a Delphi App

text: So, I've got a mandate to make our aged trillion lined Delphi app web based and it needs to make heavy use of the `<canvas>` element (HTML5 compatibility doesn't seem to be a big issue since we can just make our clients use a compatible browser the way we'd make them use a compatible version of Windows in the win32 environment). The Delphi app in question is almost completely database driven and will still pretty much continue to be developed as the main product. What I am tasked with is pretty much recreating a scaled down version of the program that performs the major functions of the whole program. I couldn't find any frameworks that simulate windows forms using the canvas element, I'm assuming this is probably by design since it is easier just to use HTML, well, be that as it may, I still think it would be cool to have a few of my cool controls on the web (TRichView and TVirtualTree, etc...) So my question is, to anyone who has tried this before, A.) What can we use for an IDE to code this web app (I just use emacs, but no one else in my company does)? B.) Is it a good idea to mix PHP and Processing.JS? It seems like I'm using a lot of AJAX to get anything to happen. 3 calls just for one dialog box to pop up,   1. Loads the HTML for the dialog,    2. Loads the XML to populate the database info on the form   3. Loads the processing.js PJS file which draws the database info to the canvas.  Is three a lot, do people usually combine all their gets into one?


title: .c FIle Dedicated to Data

text: Is it completely unheard of to have a `.c` file dedicated to just data? In my case, I'd be using it for global variables that are shared across two other `.c` files. Here's specifically how I'm using it.               // serverth.h          struct serverth_parameters {         struct { // right now, this is the only struct needed             char * root,                  * user,                  * public,                  * site;         } paths;              // I anticipate needing another struct here          };          #ifndef SERVERTH_SOURCE     extern struct serverth_parameters parameters;     #endif      * * *               // serverth.c          #define SERVERTH_SOURCE     #include "serverth.h"          struct serverth_parameters parameters = {         .paths = { // macros are actually used here             "/srv",             "/user",             "/public"             "/site"         }     };      * * * `parameters` is a struct that's used for a websockets server, in two files:   * One for HTTP (uses `parameters.paths.site`)   * Two for proprietary protocols (both use `.paths.user`, one uses `paths.public`) Is this a bad practice? Do people do this? Or, is it more conventional to just keep the data in the source file in which it is most relevant?


title: What are some easy-to-implement scaffolding systems?

text: Often when stating a new project I'll require a _"quick 'n' dirty"_ content management solution. Ideally something that can read my database schema and generated HTML forms. Previously I've used; phpMyEdit and phpMyAdmin but they are lacking is key areas. My wish list woulds be:   1. Database independent   2. Foreign key aware   3. Handles views as-well-as tables   4. Generates modern HTML and CSS   5. AJAX interface. What's your swiss army knife when it comes to CMS on a project?


title: Should I expect my peers to read or practice on a regular basis?

text: I've been debating asking this question for some time. Based several of the comments I read in this question I decided I had to ask. This feels like I'm stating the obvious, but I believe that regular reading (of books, blogs, StackOverflow, whatever) and/or practice are required just to _stay current_ (let alone excel) in whichever stack you use to pay the bills, not to mention playing with things outside your comfort zone to learn new ways of doing things. Yet, I virtually never see this from many of my peers. Even when I go out of my way to point out useful (and almost always free) learning material, I quite often get a sense of total apathy from those I'm speaking to. I'd even go so far as to say that if someone doesn't try to improve (or at least stay current), they'll atrophy as technology advances and actually become less useful to the company. I don't expect people to spend hours a day studying or practicing. I have two young kids and hours of practice simply aren't feasible. Still, I find **some** time; perhaps on the train, at lunch, in bed for a few minutes, whatever. I'm willing to believe this is arrogance or naivete on my part, but I'd like to hear what the community has to say. **So here's my question:** Should I expect (and encourage) the same from my peers, or just keep my mouth shut and do my own thing?


title: How to move a car around an environment with hills in C++?

text: I don't have any code for this since I don't know how I am meant to do this. I have a car and I am able to move it around on a flat plane and I have that working correctly. However, I want it to also be able to move up hills accurately. So that when I drive up a hill the front wheels start going up first and then the back wheels follow like a normal car would. So far all I have managed to be able to do is when one point of the car reaches an incline the whole car moves to that new y value instead of just the section of the car that is supposed to. Does it require some kind of translation and rotation applying to it so that it reacts correctly?


title: Modelling highly specific business requirements

text: How can one go about modelling highly specific business requirements, which have no precedent in the system? Take for example the following requirement: ` When a purchase order contains N lines, is over X value in total and is being recorded against project Y, an email needs to be sent to persons A and B with the details ` This requirement supplements other requirements surrounding purchase orders, but comes in at a much later date in response to some ongoing problem elsewhere in the business. Persons A and B are not part of any role or group in the system, and don't hold any specific responsibility; they are simply the two people the business has appointed to receive these emails in this very specific case. Projects are also data driven, so project Y has no special properties to distinguish it from any other project. The only way to identify it is to compare its identifier to a magic number. **How can one go about modelling this kind of case without introducing too much additional complexity?** That I can think of right now, there are a couple of options.   1. **Perform the checks and actions inline with the existing code.** Here we find the correct spot in the code, check the conditions in the requirement and send the emails to hardcoded addresses. Of course this is fraught with issues. At the very least it stops working if one of these people leaves or changes their email address. At worst you have to ensure that any tests and test data are aware that additional actions are taken for a specific set of criteria.   2. **Introduce some form of events system.** Here we introduce an eventing system, so that we might react to some event, and fulfil the requirement outside of the usual path of execution. This sounds like a cleaner solution than option 1, but the work involved is ultimately probably slightly overkill for this one small requirement. That said, having it in place does allow the system to handle these kinds of specific requirements consistently and easily in the future. **Are there any other (good/better) ways of handling highly specific requirements?** I mean other than telling the other parts of the business no!


title: How to design console application with good seperation of UI from Logic

text: 1. Is it considered an overkill for console application to be design like MVC , MVP or N tier architecture? If not which is more common and if you can link me to simple example of it.    2. I want to implement a tic tac toe game in console application.   I have a solution which hold two projects: `TicTacToeBusinessLogic (Class library project)` and `TicTacToeConsoleApplication (Console application project)` to represent the view logic. In the `TicTacToeConsoleApplication` I've `Program.cs` class which holds the main entry point (`public static void Main`).   Now I face a problem.   I want the game to handle its own game flow so I can: Create new GameManager class (`from BL`) but this causing the view to directly know the `BL` part. So I'm a little confused how to write it in an acceptable way. Should I use delegates? Please show me a simple example.


title: MySQL setup for remote site failover

text: I'm designing a custom web-based inventory management and workflow system for a client of mine. One of their remote sites has fairly sketchy internet access, and needs to have no (or very little) interruption of business when their connection to the universe goes down. I'm picturing some sort of local installation of the web app with MySQL replication keeping their local DB up to date. When their connection out of the building fails, they can manually kick over to the local URL, which is configured to hit their local MySQL, and they stay in business. Question is, replicating those changes back up to the real master. I know of such a thing as master-master replication, but will that really hot-sync divergent tables back together when the connection comes back up? It's some help that the remote site's use case is fairly unique, and it's likely (though not guaranteed) to write only to tables related to their wing of the business. I could perhaps limit the "failover mode" local application to only those pieces of the app that are unique to their location, which would be enough to keep them in business. How would you approach this?


title: Specifying Query in Unit Test

text: When writing unit tests, should I specify the query that will be performed for interacting with the database? I can see both sides of this. On one hand, I want to make sure that the query that I specify is being performed. But I can be making the test more brittle due to the formatting of the query. **EDIT:** Basically the code would be a mapper object that interacts with the db layer. But I am wondering how specific do I need to be in my interactions with a Db object. **Edit:** As I want to mock any external dependencies to my objects when I am mocking my Database connection. Should I specify the query that is going to be performed. For example:               testGettingUsers() {         $mockDb = $this->getMockBuilder('My_DB_Connection')              ->setMethods(array('query'))              ->getMock();              $mockDb->expects($this->once())              ->method('query')              ->with('SELECT id, name FROM USERS WHERE name = foo')              ->will($this->returnValue($dbReturn));      Here I have specified my query as the parameter that I am going to call my DB connection with. Is that necessary?


title: What .NET objects should I use to create a cookie based session in MVC?

text: I'm writing a custom password reset application that uses a validation technique that doesn't fit cleanly with ASP.NET Membership Provider's challenge questions. Namely I need to invoke a workflow and collect information from the end user (backup phone number, email address) after the user logs in using a custom form. The only way I know to create a cookie-based session (without too much "innovation" on my part) is to use WIF.   * What other standard objects can I use with ASP.NET MVC to create an authenticated session that works with non-windows user stores? Ideally I can store "role" or claim information in the session object such as "admin", "departmentXadmin", "normalUser", or "restrictedUser" * * * The workflow would look like this:   1. User logs in with username and password   2. If the username and pw are correct a (stateless) cookie based session is created   3. The user gets redirected to a HTML form that allows them to enter their backup phone number (for SMS dual factor), or validate it if already set.   4. The user can then change their password using the form provided The "forgot password" would look like this   1. User requests OTP code to be sent to the phone   2. User logs in using username and OTP   3. If the OTP is valid and not expired then create a cookie based session and redirect to a form that allows password reset   4. Show password reset form, and process results.


title: How to backup data and images in this project?

text: I have MS C# and MS SQL 2008 database project. It can capture employees' records with pictures of more than 1000 records. Presently, I'm able to capture say 150 records on PC1 using my installed C# application, save the records into XML or CSV file format. My friends are able to continue registration or entering (i.e from 151 to 1000) after restoring or uploading the information contained in that XML or CSV using another copy of my C# application installed on their laptops at another location.   1. How can the content be hidden or locked from user viewing its content except for my C# app reading or writing to it (not necessarily in XML or CSV format)?   2. If I still use same XML or CSV, how can the file be compressed to smaller sizes?


title: What is the clean way to pass my LoginContext down through the layers to the data access layer?

text: I have inherited an API implemented using ASP.NET WebApi 2. The actions on the controllers are all like this:               public object Get(long id) {         LoginContext loginDetails = GetLoginDetails();         if (loginDetails.IsAuthorised) {             return _dependency.DoSomething(loginDetails, id);         }              return new HttpResponseMessage(HttpStatusCodes.Unauthorised);     }      The `_dependency` will have many methods all with similar signatures, and it will have dependencies of its own, and those will also use the `LoginContext` class until you finally reach the bottom of the call stack at the data access layer, where the `LoginContext` class is actually used. Dependencies are currently all injected into the constructor by the IoC container. So there are a number of issues here that bother me - the repetitive checking in each controller action that the user is authorized, and the need to have a `LoginContext` on every method of every dependency referenced anywhere by the controller. Now in the first case, I have created an action filter that handles the authentication, and writes a custom identity (which contains the `LoginContext` details) back to the `HttpContext`. That then leaves the meat of my question - what is the best way to pass my `LoginContext` down through the layers to the data access layer? **UPDATE:** just to clarify, in response to some of the questions below, authentication itself is not being checked by the data access layer (although the business layer will obviously do things differently based on the caller's authorisation claims); but rather we are passing data gathered during the authentication process to the data access layer, where it is then being used to access particular resources, or for infrastructure concerns such as auditing. The problem still remains though, should every method of my business layer and every method of my data layer, take a LoginContext as one of its parameters, or are there better ways?


title: Is it okay to mock multiple objects in one class?

text: For developers with extensive experience using mocks, **is it okay to mock multiple objects in one class (ie satisfy multiple interfaces) or is this not recommended?** I am wondering because mocks are stubs anyway, from a testing perspective, it doesn't seem to make a big difference if I consolidate mocks. However, I do wonder if there are negative impacts from a maintenance/clarity POV.


title: What is the best strategy for quickly implementing small business applications?

text: I'm not a software developer, but I have previously developed a project- specific Access application for another employer. My current employer would like me to help organize their workflow and data for an upcoming project, and I was considering using Access again. In previous projects the staff used large piles of Excel spreadsheets; now they would like to keep their data more organized as well as automate some processes. I've found that it is difficult to create forms in Access that are pleasant and usable, due to the limited control over forms. Are there better options for quickly developing a business application, such as MS LightSwitch, Delphi, or .NET? The team that will be using the application is small - less than five users.


title: Is path in Set-Cookie URL encoded?

text: I'm writing some code that sets cookies and I'm wondering about the exact semantics of the `Set-Cookie` header. Imagine the following HTTP header line:               Set-Cookie: name=value; Path=/%20      For with path does this set the cookie? `/` or `/%20`(unescaped) (`/%20` or `/%2520` escaped)? The reason I'm asking is that I should support non-ASCII paths. Since HTTP header must only be ASCII my plan was to URL escape the path value but the HTTP specification is not as clear as I'd hoped for. **Edit** I know what Path is supposed to do. My question is: Is the value interpreted as percent encoded or not?


title: App Store: Why did I get paid less than it says in iTunes Connect?

text: Ok so not really a programming question... but it is very relevant for any non-US Apple Devs. - Basically, iTunesConnect lists my last payment as $248 NZ (I live in NZ, I signed the basic US tax contract that says I do not live in the US). The payment I received in my bank account a while ago was $221. That's about a 10% difference, maybe because of some type of tax? However, I was under the impression that I should not be getting taxed, and that it was up to me to declare and pay the tax in my own country. - So for any other non-US iOS devs - do you also see this 10% difference - if so, where does the 10% go to (NZ, US, or my bank?). If not, what am I doing wrong, and how should I be doing it? Any help is much appreciated! Thanks :)


title: Versioned Resources to Improve Cacheability

text: Here's an API concept which could be useful for performance optimisation. It's an example of key-based cache expiry applied to a broader internet-wide context instead of the internal Memcached-style scenario it seems to be mostly used for. I want to make API calls almost as cacheable as static images. Using a news/feed subscriber as an example, which we might poll hourly, the idea is to send a last-updated timestamp along with each topic (it could just as easily be a version number or checksum):               {       username: "Wendy",       topics: [{         name: "tv",         updated: 1357647954355       },       {         name: "movies",         updated: 1357648018817       },       {         name: "music",         updated: 1357648028264       }]     }      To be clear, this resource itself comes directly from the server every time and is not cached on the edge or by the client. It's our subsequent calls for topics that we can aggressively cache, thanks to the timestamp. Assuming we want to sync all topics, we'd have "N" further calls to make in a naieve implementation (`/topics/tv` etc). But because of the timestamp, we can construct a URL like `/topics/tv/1357647954355.json`. The client usually doesn't make a call at all if it's already seen (and cached) the same version of that resource. Furthermore, even if it's new to the client, an edge cache (e.g. a reverse-proxy like Squid, Varnish, or service like Cloudflare) probably _has_ seen it before, because some other user has probably opened the latest version of this topic already. So we still bypass the application server; the server only ever creates topic JSON once after the underlying resource has updated. So instead of N+1 calls to the server, the client probably makes a much smaller number of calls, and those calls will rarely hit the app server anyway. **Now for my question** All this seems feasible and worth doing, but my question is if there's any prior art for this kind of thing and in particular, any HTTP standards to support it. I initially thought of conditional caching (ETags and modified dates), and I think they'd help to optimise this setup further, but I don't believe they are the answer. They are subtly different, because they require calls to be passed through to the application server in order to check something's changed. The idea here is the client saying "I already know the latest version, please send that resource back to me". I don't think there's any HTTP standard for it, which is why I propose a URL scheme like /topics/tv/1357647954355.json instead of some ETag-like header. I believe some CDNs work this way and it's surprising to me if there's no real HTTP standard around it. **Update:** On reflection, an important special case of this is what a web browser does when it fetches a new HTML page. We know it will immediately be requesting CSS+JS, so the same versioning/timestamp trick can be used to ensure those static resources are cache-friendly. That this trick has not been formalised by the spec gives me confidence that unfortunately there is no HTTP standard for it. http://www.particletree.com/notebook/automatically-version- your-css-and-javascript-files/


title: Fiscal quarter vs calendar quarter

text: I'm building a Date/Time class with a "configurable quarter" system as follows.   * User specifies which month the quarter starts at (config)   * Set of functions to deal with quarters (next quarter, prev quarter, etc)   * All quarter functions respect the config Now this class is primarily to be used for fiscal quarter calculations. So assuming I have this class with a configurable "quarter" system, would I need another parallel set of functions for calendar quarters too? What are the applications for calendar quarters anyways? By calendar quarters I mean where Q1 is Jan-Mar, and Q4 is Oct-Dec. By fiscal quarters I mean whatever standard your Country uses (in India Q1 starts in April)


title: Use a template to get alternate behaviour?

text: Is this a bad practice?               const int sId(int const id);          // true/false it doesn't matter     template<bool i>     const int sId(int const id) {         return this->id = id;     }                       const int MCard::sId(int const id){         MCard card = *this;              this->id = id;              this->onChange.fire(EventArgs<MCard&, MCard&>(*this, card));              return this->id;     }                       myCard.sId(9);          myCard.sId<true>(8);      As you can see, my goal is to be able to have an alternative behaviour for sId.   I know I could use a second parameter to the function and use a if, but this feels more fun (imo) and might prevent branch prediction (I'm no expert in that field). So, is it a valid practice, and/or is there a better approach?


title: Dynamic Query Generation : suggestion for better approaches

text: I am currently designing a functionality in my Web Application where the verified user of the application can execute queries which he wishes to from the predefined set of queries with where clause varying as per user's choice. For example,Table ABC contains the following Template query called SecretReport "Select def as FOO, ghi as BAR from MNO where " SecretReport can have parameters XYZ, ILP. Again XYZ can have values as 1,2 and ILP can have 3,4 so if the user chooses ILP=3, he will get the result of the following query on his screen "Select def as FOO, ghi as BAR from MNO where ILP=3" Again the user is allowed permutations of XYZ / ILP My initial thought is that User will be shown a list of Report names and each report will have parameters and corresponding values. But this approach although technically simple does not appear intuitive. I would like to extend this functionality to a more generic level. Such that the user can choose a table and query based on his requirements. Of course we do not want the end user to take complete control of DB. But only tables and fields that are relevant to him. At present we are defining what is relevant in the code. But I want the Admin to take over this functionality such that he can decide what is relevant and expose the same to the user. On user's side it should be intuitive what is available to him and what queries he can form. Please share your thoughts what is the most user friendly way to provide this feature to the end user.


title: How do you keep focused through long compiles

text: I find it fairly simple keep focused on a task at hand whilst I am actively engaged on it, however, during a long compile (and our current main project can compile in 5-10 mintues on a bad day) that my focus will drift. I'll start procrastinating, check the web, talk to someone, start thinking about something else, and just generally lose my attention, and realise that the compile had finished a while back and I have lost my train of thought, or worse, a lot of time. This is hurting my productivity, and whilst it has not been mentioned by anyone, I think it's a habit I should stop. I have tried white-noise generators (brilliant whilst I have something to focus on), shutting down my web connection and the like, however, through long compiles what can I do rather than stare at the monitor? What tricks or tips can be used to keep focused without spending large amounts of your day starting at a compile in boredom, just to ensure you don't miss it finishing? Hang on, my build broke 10 minutes ago ... :) Finally, I am fairly sure this question isn't a dup of this, as as I am talking specifically about compile times, rather than waining motivation. Foosball is not an option, rather the problem :) **EDIT** People trying to gloat about their language of choice compiling faster are not really helping, nor being particularly amusing. Thanks anyway.


title: Experience With Similar Technologies: Convincing HR People?

text: Let's say that a job posting asks for experience in technology X. You have no experience in X but you do have experience in technology Y, which you're convinced is similar enough that the learning curve to be productive in X would be extremely short. How do you get hiring people, especially HR people without much technical background, to look past your lack of experience in X and take you seriously? Examples:   * You're applying for a Java job and have never used Java except for some very small toy projects. However, you do have substantial experience in C#, which is clearly derivative of Java and promotes the same style of programming (class-based OO, static typing, autoboxing, etc.)   * You're applying for a C job. You've never worked on anything written in straight C, but you have done substantial work in C++ and used the C-like subset (raw pointers, malloc/free memory management, void* pointers, etc.) for some of the low-level parts of the project.   * You're applying for a C++ job and you've done extensive work in D. D is intended to be a reengineering of C++ and includes the key concepts like RAII, templates, the ability to manage memory manually and do low-level work, etc. Furthermore, you're aware of exactly where the differences lie from extensive discussions on language design in the D community. Edit: I guess my more fundamental question that inspired this post is, "Why do most job ads place so much emphasis on specific technologies (which aren't hard to learn on the fly if you grasp the underlying concepts) instead of fundamental language-agnostic skills?" If I were running a language X shop, I'd much rather hire a top notch programmer regardless of specific technologies and assume he'd pick up X pretty fast than hire an expert in X who had mediocre fundamental, language-agnostic programming skills.


title: Translating between Python-Django and Javascript

text: I have a conceptual question about 'translating' between objects I have stored in Django (in Postgres) that I want to use on the front-end. So I have a user object in Python that holds basic things: an id, a username, a password. Let's say I want to output all of that information using Javascript on the client side. Can I just give JS a python object and it will make it into a JS object? I know JS is known for being 'fast and loose' with typing but that just seems absurd! I'm not looking for syntax, but just an overview of how this would work. Can I put Python objects in AJAX requests, then translate them client side, or is this going to be a basic break-down-things-on-server-side, ship them off, and recombine them on the client side type of thing?


title: Looking for an algorithm to connect dots - shortest route

text: I have written a program to solve a special puzzle, but now I'm kind of stuck at the following problem: I have about 3200 points/nodes/dots. Each of these points is connected to a few other points (usually 2-5, theoretical limit is 1-26). I have exactly one starting point and about 30 exit points (probably all of the exit points are connected to each other). Many of these 3200 points are probably not connected to neither start nor end point in any way, like a separate net, but all points are connected to at least one other point. I need to find the shortest number of hops to go from entry to exit. There is no distance between the points (unlike the road or train routing problem), just the number of hops counts. I need to find all solutions with the shortest number of hops, and not just one solution, but all. And potentially also solutions with one more hop etc. I expect to have a solution with about 30-50 hops to go from start to exit. I already tried: 1) randomly trying possibilities and just starting over when the count was bigger than a previous solution. I got first solution with 3500 hops, then it got down to about 97 after some minutes, but looking at the solutions I saw problems like unnecessary loops and stuff, so I tried to optimize a bit (like not going back where it came from etc.). More optimizations are possible, but this random thing doesn't find all best solutions or takes too long. 2) Recursively run through all ways from start (chess-problem-like) and breaking the try when it reached a previous point. This was looping at about a length of 120 nodes, so it tries chains that are (probably) by far too long. If we calculate 4 possibilities and 120 nodes, we're reaching 1.7E72 possibilities, which is not possible to calculate through. This is called Depth-first search (DFS) as I found out in the meantime. Maybe I should try Breadth-first search by adding some queue? The connections between the points are actually moves you can make in the game and the points are how the game looks like after you made the move. What would be the algorithm to use for this problem? I'm using C#.NET, but the language shouldn't matter.


title: Should one reject over-scoped projects?

text: I spoke to my first potential client today and he told me about the requirements of his project - an Android app. He is a well-known designer / photographer in my country and now wants me to "convert the website into an app, custom-tailored". So the requirements, details stripped out, are as follows:   * eCommerce   * Aggregating all his content like videos, blogs, tweets, etc. into the app   * Live streaming any of his studio demos   * Augmented reality. So that people can see what his painting will look like on their wall before they buy it   * Taxi Sharing Now, for a freelance project, it seems too over-scoped. I am not saying that I cannot do it. I can. But let me be realistic:   * There is a steep learning curve when it comes to VR.   * I am not a tester. I have never white-box tested my own apps. I always black-box test.   * Since he is a renowned artist, something short of perfect _might_ harm his public image So, I asked him for 2 weeks' worth of time before I give him the final answer. Now knowing whom to consult for advise, I am posting the question here. Although interesting and personally challenging, I am split-minded about accepting a project like this. I will be **the only developer** for this. **Should one reject a project that seems to be over-scoped for one's own abilities?**


title: How to model a many to many from a DDD perspective in UML?

text: I have a two entity objects Site and Customer where there is a many to many relationship. I have read you try not to model this in DDD as it is in the data model and go for a unidirectional flow. If I wanted to show this in UML, would I show it as it is in the data model: `Site * ----->*Customer` but the direction arrow gives the flow? or as following `Site ----->*Customer` But then this would imply that Customer can only go in one site.


title: How to measure the quality of my use cases?

text: When I'm coding something I know that there are many ways to see if my code is good or not. First is testing: I can do unit tests or even test the software by myself and see that it works or not. After getting it working, I can analyze the coupling of the code and so on to refactor and make it better. In that sense, I'm confident when coding because I have a way to know if what I did works or not and ways to think it better if it doesn't work. When designing the software though I'm mainly having difficulties to analyze whether the uses cases I write are good or not. I've read lots of theory on use cases, but the practice is being a little hard because I always find myself questioning things like: "should this be included? is this necessary to say here? isn't it missing something?" and all sorts of things like that. So, how can I "test" my use cases? How do I know if they are well written or not? I know in OOAD iterative approach, we don't try to get it right on the first iteration, however it should at least contain the exact information to get me started in coding, and I don't now how to discover if it does contain that information.


title: C# vector class - Interpolation design decision

text: Currently I'm working on a vector class in C# and now I'm coming to the point, where I've to figure out, how i want to implement the functions for interpolation between two vectors. At first I came up with implementing the functions directly into the vector class...               public class Vector3D     {         public static Vector3D LinearInterpolate(Vector3D vector1,             Vector3D vector2, double factor) { ... }              public Vector3D LinearInterpolate(Vector3D other, double factor { ... }     }      (I always offer both: a static method with two vectors as parameters and one non-static, with only one vector as parameter) ...but then I got the idea to use extension methods (defined in a seperate class called "Interpolation" for example), since interpolation isn't really a thing only available for vectors. So this could be another solution:               public class Vector3D { ... }          public static class Interpolation     {         public static Vector3D LinearInterpolate(this Vector3D vector,             Vector3D other, double factor) { ... }     }      So here an example how you'd use the different possibilities:               {         var vec1 = new Vector3D(5, 3, 1);         var vec2 = new Vector3D(4, 2, 0);         Vector3D vec3;              vec3 = vec1.LinearInterpolate(vec2, 0.5); //1         vec3 = Vector3D.LinearInterpolate(vec1, vec2, 0.5); //2              //or with extension-methods              vec3 = vec1.LinearInterpolate(vec2, 0.5); //3 (same as 1)         vec3 = Interpolation.LinearInterpolation(vec1, vec2,         0.5); //4     }      So I really don't know which design is better. Also I don't know if there's an ultimate rule for things like this or if it's just about what someone personally prefers. But I really would like to hear your opinions, what's better (and if possible why ).


title: Does OpenMp have support for Real Time Multiprocessor Computing?

text: I am working on a real time multiprocessor scheduling algorithm. I found very few results via google research related to it. A few simulators are available but are not robust enough. OpenMp is an API I have previously used for small parallel application development. But I am not sure if it provides any support for real time parallel computing which involves time related parameters such as task period, deadline etc. Are those features available in OpenMp? If not, are the underpinnings available so I could extend OpenMp instead?


title: How to inherit from two parent classes

text: I have many classes with many relationship I draw Uml that relation between them: > ![enter image description here](http://i.stack.imgur.com/tw1H9.jpg) Is this relation true and how to implement this?


title: How is major software protected?

text: I am a new software developer and I wish to sell my software. I recently realized that from C++ code we can not stop the user seeing parts of the code that are related to scripts or system commands. Would you make some comments on how software written in C++/JAVA (distributed via CD-ROMs or available via download) is protected from reverse engineering, scanners for when the code is in memory and direct copy of parts (as system commands). What a small software company which just starts producing software should do to protect its product from the technological point of view (it should not be able to pay legal fees …)?


title: Will giving new recruits a separate subproject from experienced developers help the newbies ramp up more quickly?

text: We have 7 developers in a team and need to double our development pace in a short period of time (around one month). I know there is a common sense rule that "if you hire more developers, you only lose in productivity for the first few months". The project is an e-commerce web service and has around 270K lines of code. My idea for now is to divide the project in two more or less independent sub- projects and let the new team work on the smaller of the two sub-projects, while the current team works on the main project. Namely, the new team will work on checkout functionality, which will eventually become an independent web service in order to decrease coupling. This way, the new team works on a projects with only 100K lines of code. My question is: will this approach help newbie developers to adapt easily to the new project? What are other ways to extend the development team rapidly without waiting two months until newbies start producing more software then bugs?


title: Using a binary from a project that violates GPL

text: There is an open source project which uses GPLv2. It had numerous releases that complied with GPL in the past where source code was available for given binaries. The newest source code is about 18 months old and is being called a last "official release". Since that OSed "last version" further development has been done by a single main developer. Features have been added and it is clearly visible that the code must have been changed. The main developer only holds part of the copyright for the whole package (it is not 100% his work, the project was started as a fork of another GPLed project). Lets call the ongoing development a TRUNK branch. The problem is that the latest development is done as closed source and **only binaries are being distributed for the TRUNK branch and no source code** was revealed yet. While this most likely is a GPL violation and is a bad thing itself, I dont mind this (even as I should) because I want to use the TRUNK binaries. My question is - **what is the legal status of such TRUNK binaries** that have no source available to them? Are these poised somehow? I want to use the binaries in my project which is open source itself but the binaries would be used in a standalone working unit that only is used for data acquisition so I most likely wont need to modify the unavailable TRUNK source code anyway.


title: Purpose of the csx folder in Azure projects?

text: I'm fairly new to Azure but I noticed that Visual Studio auto-creates the following folders (among others)               ...     /<nameOfAzureProject>/bin     /<nameOfAzureProject>/obj     /<nameOfAzureProject>/csx <==     ...      Now the bin and obj folders are fairly standard. But I'm not clear about the purpose of the **csx** folder. Any ideas?


title: How would you feel if your code editor formatted your code for you as you typed, without tabs/spaces?

text: As with most things, I'm sure this concept has been tried before - I just haven't come across editors that use what I've termed 'Virtual Formatting'. The principle is that there's a floating left-margin that simulates the effect of the padding space/tab characters that are conventionally inserted by the developer or the editor itself to format the code. The editor continously parses code (even when commented-out) as you type and calculates the required indent based on the context where each line-feed is found I'm developing this idea working specifically with an XML editor as XML has some peculiar problems with formatting characters and it tends to be heavily nested, however I believe many of the principles still hold for conventional code. Have you experience coding with such a tool or do you have a view on whether it would help or hinder? Would it cause problems with version-control systems? (it detects and strips out all existing padding characters) Unless you've tried it, the behavior of such a tool is hard to describe, it looks conventional until you actually start editing. I've put up a screencast video showing a prototype in action which demonstrates editing XML, changing it's hierarchy and doing drag/drop and copy and paste operations, and then how formatting is broken/fixed when invalid characters are typed. **Edit** All answers/comments have so far been negative - so to attempt to redress balance, some benefits of virtual-formatting to think about:   * No more debates on formatting standards, just place line-feeds where that conforms to your chosen/mandated convention   * Where space is at a premium (in a book/blog/documentation) you can word-wrap but still getting perfect indentation   * Each code-block can have a 'mouse-handle' immediately adjacent to where it starts, not squeezed into the screen edge - click this to select the whole block or inner-block   * Drag, drop and forget - becomes viable for the first time   * No time spent reformatting other peoples code   * No incorrectly formatted code (in the sense that there is none - just the rendering)   * Using Backspace instead of Ctrl+Backspace keeps your fingers on the keyboard guide-keys   * Flexible rendering - adapt rendered formatting to your environment, anyone tried reading code on a mobile phone/small-screen tablet?   * Consider that there are roughly 25% fewer editable characters (in a sample XSLT), doesn't that have efficiency benefits? **Edit - Conclusions so far**   1. Developers have established tools and working methods that efficiently overcome most of the disadvantages inherent in the use of padding characters used for indentation.   2. There is concern that removal of formatting characters will detrimentally affect some differencing tools.   3. Developers want the flexibility to 'fine-tune' formatting in such a way that automated rendering could not handle.   4. The removal of leading spaces/tabs means that a 'code-aware' tool capable of code-formatting is needed to review such code efficiently - a plain-text editor would show no formatting.   5. Those that feel there may be some hypothetical benefits (to virtual-indentation), have a view that the disadvantages outweigh those potential benefits - _conclusively_. **Edit - Verdict** The perception of the obstacles and few (if any) benefits is such that it would be unwise for me, as a sole-developer, to pursue this space-free editing concept for general languages. For XML/XSLT, however (because of its special treatment of whitespace), there seems to be some agreement of potential at least. **Edit - Product Shipped** In spite of the generally negative sentiment found here, I went ahead and shipped the editor. I made a free version in the hope it would bring criticism in the form of more concrete issues, based on real experience. Somewhat frustratingly, there have been no complaints so far (in fact barely any feedback considering download volume). I'd like to think this was because users adjusted to the idea so well that they see this as a 'so what?' kind of feature - but there's no way of telling...


title: What's the rationale of not simply disclosing the license fees for a commercial libary or tool?

text: Some companies selling software or libraries simply put their licensing model on their web page and be done with it. (Many also contain a disclaimer that there are volume discounts and special arrangements possible.) Other companies (most notably those placing themselves in the "enterprise" market) don't disclose their fees, some don't even disclose their licensing model! When you are interested in their product and contact sales, you then discover that their price calculation is simply a per site / per developer / per core / per whatever thing and they could just as well have put that info on their webpage. Can fellow programmers give me an insight as to why I have to exchange 3 emails and 2 phone calls with a sales representative to find out if a product even remotely fits into our development price tag? I have found that me (and some of my co-workers) are extremely reluctant to even evaluate a product that doesn't disclose it's costs up front, so I cannot understand why anyone would do that for "simple" products - that is for libraries and software that really doesn't have negotiated license fees. Note again: I'm talking about single-installation software or libraries that are licensed per-site or per-developer and not about stuff that requires complicated licensing agreements.


title: How to move to Java enterprise development after Python and Ruby?

text: I used to develop in Django/Python and Rails/Ruby (and before that C/C++ and C#), and I'm now at a job where we do enterprise Java development (Spring, Hibernate, RESTEasy, Maven, etc.) for web applications and web services. Coming from the Convention over Configuration world, what's the best way to get up to speed doing enterprise Java web services development? I know Java (the language) well, and I've written GUIs in Swing and basic JSP before, but nothing of the kind I'm doing now. Are there any recommended tutorials to get up to speed on popular Java enterprise development tutorials?


title: Should I achieve validation by handling errors in classic ASP?

text: I came across this while modifying an old ASP application:               ON ERROR RESUME NEXT          ivalue = CDATE(ivalue)          IF err.number > 0 THEN       ivalue = CDATE(date)     END IF     err.clear      This doesn't look like good practice. What is the purpose of doing it this way, and is there a better way to go about it? For example, I would've just used `ISDATE()`: is there something I'm missing?


title: Best books on Managing a Software Development Team?

text: The canonical books on software development is fairly well established. However, after reading through a dreadful book full of bad advice on managing programming teams this weekend I am looking for recommendations for really good books that focus on the management side of programming (recruiting, performance measurement/management, motivation, best practices, organizational structure, etc.) and not as much on the construction of software itself. Any suggestions?


title: Implement Generic DataSet Builder with C#

text: I want to create a data access library that can build a DataSets with relations which can easily be written to XML with `dataset.WriteXML()`. This is a get to know C# endeavor that will hopefully gain me some productivity as well (lots of converting relational tables to XML from different data sources for document generation) So far the only difference I see between the Data Access technologies (SQL, OLEDB, ODBC) with regards to how I will use them for this is that they require a type specified Connection and Adapter (SqlAdapter, OleDbAdapter, OdbcAdapter, etc). So in my mind I envision classes with two methods and a public data set that will be filled.               public DataSet DataSet { get; set; }          public void InsertTables(string ConnectionString, string[] TableNames, string[] Commands)          public void AddRelations(string[] PrimaryTables, string[] PrimaryKeys, string[] ChildTables, string[] ForeignKeys, bool[] NestingRules)      I already started with an OleDb Implementation that works well, and I want to set up something similar for other Data Access technologies. However, I want to be as efficient as possible with the code so am looking for advice on how to accomplish. I was thinking that the Template Method Design pattern could be a solid approach, but then I also thought that a single class that utilizes generics might work as well (I am new to C# and not that familiar with them). I am looking for a general example of how I could accomplish this with a good design pattern and/or generics. Here is what I have for the OleDbDesign. Any advice is greatly appreciated.                public class OleDbDataSetBuilder     {         private DataSet _DataSet;              public DataSet DataSet { get { return _DataSet; } }              public OleDbDataSetBuilder(string DataSetName)         {             this._DataSet = new DataSet(DataSetName);         }              public void InsertTables(string ConnectionString, string[] TableNames, string[] Commands)         {                  if (TableNames.Length != Commands.Length)             {                 throw new Exception("Error: Must provide a table name for each command.");             }                  OleDbConnection cn = new OleDbConnection(ConnectionString);                  OleDbDataAdapter adapter = new OleDbDataAdapter("", cn);                  adapter.SelectCommand = new OleDbCommand("", cn);                  for (int i = 0; i < TableNames.Length; i++)             {                 adapter.SelectCommand.CommandText = Commands[i];                      adapter.Fill(_DataSet, TableNames[i]);             }                  cn.Close();              }              public void AddRelations(string[] PrimaryTables, string[] PrimaryKeys, string[] ChildTables, string[] ForeignKeys, bool[] NestingRules)         {                  for (int i = 0; i < PrimaryTables.Length; i++)             {                 DataColumn pk = _DataSet.Tables[PrimaryTables[i]].Columns[PrimaryKeys[i]];                      DataColumn fk = _DataSet.Tables[ChildTables[i]].Columns[ForeignKeys[i]];                      DataRelation relation = _DataSet.Relations.Add(pk, fk);                      relation.Nested = NestingRules[i];             }         }     }


title: GWT vs JSF vs ZK vs Restful+JS

text: I'm planning to develop a web based ERP, which should be full-ajax and with desktop-like UI. It will be a data-entry & data-report application. For developing it I'm considering all technologies. GWT: I saw that with GWT Designer you could create cool UIs, but databinding seems to be too complex JSF: Netbeans no longer supports the visual web editor ZK: supports databinding in a relatively easy way, and has got an Eclipse- based visual editor Some people talk about REST + javascript as a winning choice I'd like to have your opinion about what could be the right choice. Thank you very much in advance!


title: Is it a good idea to provide different function signatures that do the same thing?

text: Here is a C++ class that gets constructed with three values.               class Foo{              //Constructor         Foo(std::string, int, char);          private:         std::string foo;         char bar;         int baz;     };      * * * All of the parameter types are different.   I could overload the constructor so that order doesn't matter.               class Foo{              //Constructors         Foo(std::string, char, int);         Foo(std::string, int, char);         Foo(char, int, std::string);         Foo(char, std::string, int);         Foo(int, std::string, char);         Foo(int, char, std::string);               private:         std::string foo;         char bar;         int baz;     };      But is that a good idea?   I started doing it because I knew what things a class/function needed;   I didn't always remember what order it took them in. * * * I've been assuming that the compiler optimizes this as if I called the same constructor.               //compiler will implement this with the same code?      //maybe not.. I could call a function to get a parameter,      //and that function could change the state of the program, before calling     //a function to get another parameter and the compiler would have to     //implement both     Foo foo1("hello",1,'a');     Foo foo2('z',0,"world");      What are your opinions on overloading a function so that the order doesn't matter? * * * Also, If I'm writing some utility functions,   Is it a good idea to provide different function names that do the same thing? eg.               void Do_Foo();     void DoFoo();     void do_foo();     //etc..      * * * I don't often see these two but similar conventions.   Should I break or embrace the habit?


title: What is the proper way to use an IDE to work on remote code?

text: One of the code bases I work on has a development environment that is running on a dev server and cannot be copied over to my PC to locally test and develop. I am wondering what is the proper way to work with this code base? It is object oriented and I have found it to be very tedious and time consuming to do my work using Vim when working on such a codebase. I have another project which I have running locally and I like to use Eclipse and sometimes Sublime text to make changes to the codebase. Is there a way to utilize such tools that I use locally with a remote project, and if so what is the proper way to set this up? Should I remotely mount my system? We do have git/hg setup with these environments however I like to test and debug things in very small changes and this would produce a lot of commits that are un-needed. As well it is also time consuming. Ideally it would be great to just be able to work like it is a local environment and when I save and refresh a page the change is there. Is my best solution mounting?


title: Are there any tools for remote coding interview?

text: Firstly, I'm not exactly sure if this question is a better fit over here, or on workplace.SE. So forgive me if it is in the wrong place. We are interviewing some candidates for a development position, and currently they are not in our city. We would like to give them simple coding tests to see how they will perform on the typical issues that we face in our daily work. Are there any specific tools geared towards this? Right now we are using Skype and I feel this tends to decrease the performance of a lot of developers since they tend to be shy, and often can't work when someone is directly staring at them. The problem with sending them the test questions by email are as follows:   1. It is not possible to know what their thought process is, sine we just see the end result. There is no discussion, or clarification of the question, which is an Important step.   2. There is no guarantee that the problems were solved by the candidates themselves. They could send it to a smarter friend, and we wouldn't be able to know. How are these problems usually solved?


title: Guid collisions

text: I have a product that lets game developers create games. Inside of their games they are required to give all the elements of their games GUIDs. I've told them that they need to generate their guids using a specific mechanism, but they seem to think that it won't cause any issues. What I'm concerned about is GUID collisions between games. Some developers just sequentially increment the last digit of their GUID, others zero out the last block and increment other parts, well others just pull together a random armada of numbers and letters for each one. My argument is that by doing this it dramatically increases the risk of colliding with other games that are both following the standard, and those that don't. Just as a heads up there are potentially hundreds of thousands of GUIDs involved here. Am I right in thinking this, or is it really improbable that this will really happen?


title: Just in time prize winning algorithm

text: I'm building a contest where you can win prizes by opening boxes. Whatever the box is open, i just send a request to the server to test if the user won something. Since this contest is not a "Register and we'll draw a winner after some time" type of contest, i'm a bit puzzled at what algorithm i should be taking to calculate chances to win. I've devised in an excel spreadsheet what i call a progressive winning algorithm in the form of:               ([Number of prizes left] / [Prizes i should have left at this time of contest]) / 4      Which gives me a rough percentage change of winning an item off the pool of remaining items around 25%. If there are many winners within a close timespan, the algorithm should automatically lower the chances of winning while going in the opposite direction if the scenario is different. What i'm afraid of is that not all my items will be drawn by the end of the contest because it's a linear calculation of expected gifts left or i'm afraid that, by chance, most of my prizes will be won after only half of the contest (and by chance i mean that lots of player get truly great random odds and keep winning) So my question is, how should i tackle this kind of scenario, what are already known methods for this and please keep it simple, i'm no mathematician nor statistician. * * * **Variables to take into account**   * 100 prizes to give out total   * Contest lasts five whole days   * Unknown number of participants   * Unknown participation rule but will probably be once per day based on a unique credential such as an e-mail address.   * It's an online contest where a user opens a virtual box, nothing physical


title: Practice programming guidance

text: I am a recent graduate so I understand a lot of the theory, object-oriented languages, and various data structures. I am competent in languages such as C++, Java, PHP, just to name the ones I'm strong at. Since graduation I bite the bullet and accepted a job outside of my field for now. So obviously I don't want to lose my edge and want to stay current. Most of my programming has been for academic reasons and a 3-month web programming (back-end) internship. I really want to program something to use my skills I've learned. I always hear program a game is great practice. However one problem with the Internet is it's robust volume of information and find myself reading one site then jumping to another & on & on. Where would you suggest is a good foothold to begin? It's always harder to start from scratch and that is where I am. I figure start with some 2D game and go from there, but then comes the question of which SDK to use, if any. I'm currently using Linux but I wouldn't mind developing in Windows either. I'm always thinking maybe I should try to develop a simple app for an Android phone as well. As you can tell I'm all over and just need a little direction. Any advice/website is greatly appreciated!


title: What are the difference between an edge case, a corner case, a base case and a boundary case?

text: I'm not a native English speaker. In my native language I'm aware of some terms used to refer to the condition checked to stop a recursion, and to the condition checked for extreme, unlikely or super-simple cases. In English, I've encountered the terms "edge case", "corner case", "boundary case" and "base case", but I can't quite figure out the differences and which is used to refer to what; I'd love to get some summary of the differences between them. In particular, I would be very happy if someone could provide annotations for the lines in the following code sample:                   int transmogrify(int n) {     1.      assert(n <= 1000000);     2.      if (n < 0) return -1;     3.      if (n == 1000000) return PRE_CALC;     4.      if (n == 0) return n+1;            // For stopping the recursion     5.      if (n == 1251) return 3077;             return transmogrify(n-1);         }      I _think_ it's:   1. Sanity check   2. Input check   3. Boundary case? Edge case? Corner case?   4. Base case? Boundary case?   5. Corner case? Edge case?


title: Using Scrum/agile with multiple customers

text: I am a big believer in agile development. I just changed jobs, and I am now working for a company that coordinates big development projects for (rather large) groups of customer organizations. My job is to find the right contractors for the projects, and make sure that the customer organizations are as happy as possible, and control the process. There is nothing in the world that would make me happier, than if I could introduce Scrum or a similar agile method into this situation, making my company's main role the product owner. It would make sense on so many levels. There are some issues though: Since Scrum is a rapid-response method, I wonder if Scrum is the right method for a place like this, where not one customer but a big group of customers have to be involved in prioritizing of the backlog from sprint to sprint. It takes place in a quite political environment. What pitfalls and possibilities do you see in a situation like this? Can this situation simply be handled by longer sprints? There is a general understanding and empathy for the agile agenda in the company, but the issue I describe here seems to be a major obstacle. I would really appreciate your input. I need good ammo for my agile preaching :o)


title: Making internal search engine return results that adhere to local permissions on an internal web application

text: I have an ElasticSearch search engine and an internal web application. Prior to applying the security model, search results were very fast. The security model restricts some users from accessing certain pages. We have 7 "types" of pages. Our process is currently this:   1. Search engine queries all records   2. For each type of result, I get all recordIds of that type from the database that the user is allowed to access. This ensures I only call the database a max of 7 times (once per type)   3. I do an intersect between the records the user can access and the records search is returning The above approach isn't fast enough. I have an autosuggest search and each query takes up to 2 seconds now. What is a typical way to make a search engine return results that adhere to security? Another developer has recommended I store the security permissions directly in ElasticSearch itself(essentially mirroring what our sql server has). Edit: Each record has a page. We can assume 200-500 users and 25000+ records.


title: Using two versions of a class in the same code

text: At my job, in our core project, we have a Validation class that has been evolving with the years. And ee have an old project with an User class that uses an old version of the Valdiation class. And we have to update some functionality that requires new validation methods. All those methods are implemented in our latest Validation class. But the new Validation class isn't backwards compatible, so we can't just put the new one in place. I thought that a good solution would be to upgrade all the code that references the Validation Class or making it backwards compatible but, obviously, both of them would take a lot of time. Finally, it was decided that adding the latest version and calling it Validation2 works just fine, some methods use Valdiation and others Validation2. I think that will bring a lot of problems later, because you don't know when to use one or another as the names stop being meaningful. What could be a better option to deal with this? Also, the Validation class was the best example, but we have the same problem with a lot of bigger and more complicated classes and now we have a lot of "duplicated" classes. The language is PHP, but could happen in other languages too.


title: Degree after BSc in Computer Science: Marketing, MBA, Techno-MBA, HCI?

text: Since a year I am a graduated Computer Engineer, and am now working in named field since 2 years. However, I'd like to get a Masters in a "softer" field and was thinking over the following choices:   * **MBA** : Master of Business Administration, to bridge the business world with the world of computer science. Would give me an interesting job, travel potential, high salary etc.   * **Techno-MBA** : Sort of an MBA, but aimed at people who already have a degree in Computer Science.   * **HCI** : Human Computer Interaction degree, something I have been **very** interested in, but feel like it doesn't have the growth potential of MBA/Techno-MBA   * **Marketing** : My most recent brainchild is a degree in Marketing, is this at all a good idea given my background? Growth potential? Main priority: Gaining a skill, and gaining a job allowing me to use my social skills. Which path has the best "career potential"? (Controversial I know) Any thoughts? Any feedback welcome. Edit: DOH. Realized that the first sentence makes no sense. Was running my own semi-successful business during last year of school.


title: When would you choose *not* to update a third-party library to a newer version?

text: Using third party libraries for productivity gains in software development is common. Unfortunately, along with the library's functionality we also import its bugs. Some of them get fixed in subsequent releases. So, to upgrade or not to upgrade, this is the question. I am interested in learning from experiences when upgrading to a newer version of the library was desirable, but after a cost/benefit analysis the conclusion was that upgrading was not a good solution "in the grand scheme of things". I am interested in finding out what _forces_ influence the decision towards _not_ upgrading.


title: Python vs. Java for embedded wireless module

text: We are developing a product at work which interfaces with basic I/O and sends data to a webserver over a GPRS connection. What i need to know before we commit to a product, is which language is more suited for this task: Java or Python? (or any language to be honest) As i said, it will run on a wireless module and open serial connections, read values, send data through GPRS connections to a webserver...


title: Should PHP view files be called something other than '.php'?

text: By default, any file that PHP touches is usually suffixed with `.php`. It's universally understood by Apache / Nginx as the default for PHP files and most setups expect PHP files to end in this extension. In short, `.php` is the standard for everything PHP. However, I'm wondering if perhaps view files should have a different extension to help differentiate them from other PHP files. First, when it comes to views I have found that almost all MVC frameworks using a matching view file named after the controller or method. In addition, you generally also have a matching model named the same thing. This causes a problem with most IDE's and editors. For example, you might have a "user" controller, a "user" view, and a "user" model. The results in having three files open called "user.php" which makes it a bother when you are moving around and clicking on the wrong tabs. Second, separating views as a fundamentally different kind of PHP file (the presentation type) is another argument for changing the extension of the view files to something other than `.php`. Something that immediately tells your brain what type of content belongs in it. Third, some applications expose parts (or all) of the PHP files in the webroot and it's directories. Rather than adding something like `<?php if(!defined(ABC)) die('not allowed');` it would be nice to have an easy way to forbid access to views while allowing other files like the customary `index.php`. **Are there any other good/bad reasons to think it's a good idea to change the file extension of view files?**


title: Lua-type Java integration with C++

text: So I'm curious: I've implemented Lua within C++ a few times before, and while it was relatively simple, it still didn't harness the power that I would have liked. I love how eclipse works, including javadoc locations, etc. and I was wondering if there was a way to integrate Java into a native application (that is cross-platform, of course) to do what Lua does, but with Java. This means I'd be able to build my own base classes and stuff, etc. Just an interesting thought! Any insight? EDIT: Also, what about MonoDevelop? Is it relatively easy to integrate? Is it compiled? Is it cross-platform-able?


title: Using function points as a metric for the velocity of a Scrum team?

text: I came across the idea of using function points as a metric for the velocity of a Scrum team. I saw it in a team and I found two articles mentioning a link between estimates and function points (http://www.ifpug.org/ISMA5-2010/Amol%20Keote-FunctionPointsAndAgile-Hand-in- Hand.pdf and http://www.cosmicon.com/portal/public/FromStoryPointsToCOSMIC.pdf). I am not sure how this can work, because if I understand it correctly, function points measure the _value_ of a feature (e.g. from the users perspective) whereas the velocity measures the _effort_ of finished features. And in my view there's no direct connection between these two. To put it another way: If you have (let's say) a stable Scrum Team which works 2 week Sprints, the number of functions points they deliver per Sprint should vary (possible wildly), which would render a velocity based on function points quite meaningless (e.g. for planning purposes)... Am I missing something here?


title: Have You Ever Had To Code "Badly" For Your Team?

text: I've been on the constant road of learning new concepts in OOP, Software Design, Architecture, etc. But there are times when you are in a team where those concepts are foreign to them and they don't have the time or the same eagerness to learn as you. The problem is if you design your code the "right" way, the people who code with 2kLOC classes won't understand it. Would you sacrifice good coding principles to support your team? What about a scenario where this will be a long term arrangement?


title: Does usage of advanced language features decrease maintainability?

text: On a code review, I've stumbled on an interesting idea, which I can't properly judge alone. Is it OK to improve readability of code by means of not widely known language syntax? When the original writer didn't use a special syntax designated for solving a specific coding problem, and solved it by simulating with workarounds — is it worth to refactor it for clarity and conciseness? What if even the code reviewer didn't know about the language feature? To be specific, I'll bring the exact issue I've met on the code review — but keep in mind that this is just an example. So the original code was a little web service in Python. At some point, there arised a requirement for several request handlers to be protected with an authentication mechanism. Somebody solved it with inheritance:               class AuthOnlyAccess:         def GET(self, *args):             if not hasattr(self, 'PROTECTED_GET'):                 raise web.Nomethod()                  if check_auth():                 return self.PROTECTED_GET(*args)             else:                 raise web.Unauthorised()              def POST(self, *args):             if not hasattr(self, 'PROTECTED_POST'):                 raise web.Nomethod()                  if check_auth():                 return self.PROTECTED_POST(*args)             else:                 raise web.Unauthorised()          ...          class FooHandler(AuthOnlyAccess):         def PROTECTED_GET(self, a, b, c):             handle_foo_get(a, b, c)              def PROTECTED_POST(self, x, y, z):             handle_spam_eggs()          ...     <more handlers deriving AuthOnlyAccess>      The refactorer found this code ugly and introduced a decorator:               from functools import wraps     ...          def requires_auth(wrapped_func):         """ (a little doc telling that this is a decorator and how to use it) """         @wraps(wrapped_func)         def decorator(*args):             if check_auth():                 return wrapped_func(*args)             else                  raise web.Unauthorized()              return decorator          ...          class FooHandler:         @requires_auth         def GET(self, a, b, c):             handle_foo_get(a, b, c)              @requires_auth         def POST(self, x, y, z):             handle_spam_eggs()          ...     <more refactored handlers>      The reviewer argues that this change actually **decreases** maintainability, because most of the team doesn't know decorator syntax. So the next person visiting the refactored code could be puzzled by the construct — but not with the previous version. There's also a convincing argument that **most of the codebase isn't in Python** , (the language is there only for that little web service), and hence team members aren't required to have even shallow knowledge of Python. However, to work with code, one's going to need to know its language, right? And if you have the temptation to say that python decorators aren't _that_ advanced syntax — please remember that this is only an example. Every language has its dark corners. (But to learn those corners means to become better.) So the question is... Can you read unknown syntax? Is the elegance worth the surprise? At least, what are the tradeoffs and/or guidelines you can name? I do really need some opinions from the community of programming professionals.


title: How do I initialize a Scala map with more than 4 initial elements in Java?

text: For 4 or fewer elements, something like this works (or at least compiles):               import scala.collection.immutable.Map;          Map<String,String> HAI_MAP = new Map4<>("Hello", "World",                                             "Happy", "Birthday",                                             "Merry", "XMas",                                             "Bye", "For Now");      For a 5th element I _could_ do this:               Map<String,String> b = HAI_MAP.$plus(new Tuple2<>("Later", "Aligator"));      But I want to know how to initialize an immutable map with 5 or more elements and I'm flailing in Type-hell. # Partial Solution I thought I'd figure this out quickly by compiling what I wanted in Scala, then decompiling the resultant class files. Here's the scala:               object JavaMapTest {       def main(args: Array[String]) = {         val HAI_MAP = Map(("Hello", "World"),                           ("Happy", "Birthday"),                           ("Merry", "XMas"),                           ("Bye", "For Now"),                           ("Later", "Aligator"))         println("My map is: " + HAI_MAP)       }     }      But the decompiler gave me something that has two periods in a row and thus won't compile (I don't think this is valid Java):               scala.collection.immutable.Map HAI_MAP =             (scala.collection.immutable.Map)              scala.Predef..MODULE$.Map().apply(scala.Predef..MODULE$.wrapRefArray(                     scala.Predef.wrapRefArray(                             (Object[])new Tuple2[] {                                     new Tuple2("Hello", "World"),                                     new Tuple2("Happy", "Birthday"),                                     new Tuple2("Merry", "XMas"),                                     new Tuple2("Bye", "For Now"),                                     new Tuple2("Later", "Aligator") }));      I'm really baffled by the two periods in this:               scala.Predef..MODULE$      I asked about it on `#java` on Freenode and they said the `..` looked like a decompiler bug. It doesn't seem to want to compile, so I think they are probably right. I'm running into it when I try to browse interfaces in IntelliJ and am just generally lost. Based on my experimentation, the following is valid:               Tuple2[] x = new Tuple2[] { new Tuple2<String,String>("Hello", "World"),                                 new Tuple2<String,String>("Happy", "Birthday"),                                 new Tuple2<String,String>("Merry", "XMas"),                                 new Tuple2<String,String>("Bye", "For Now"),                                 new Tuple2<String,String>("Later", "Aligator") };          scala.collection.mutable.WrappedArray<Tuple2> y = scala.Predef.wrapRefArray(x);      There is even a `WrappedArray.toMap()` method but the types of the signature are complicated and I'm running into the double-period problem there too when I try to research the interfaces from Java.


title: unit testing variable state explicit tests in dynamically typed languages

text: I have heard that a desirable quality of unit tests is that they test for each scenario independently. I realised whilst writing tests today that when you compare a variable with another value in a statement like:               assertEquals("foo", otherObject.stringFoo);      You are really testing three things:   1. The variable you are testing exists and is within scope.   2. The variable you are testing is the expected type.   3. The variable you are testing's value is what you expect it to be. Which to me raises the question of whether you should test for each of these implicitly so that a test fail would occur on the specific line that tests for that problem:               assertTrue(stringFoo);     assertTrue(stringFoo.typeOf() == "String");     assertEquals("foo", otherObject.stringFoo);      For example if the variable was an integer instead of a string the test case failure would be on line 2 which would give you more feedback on what went wrong. Should you test for this kind of thing explicitly or am i overthinking this?


title: A design pattern for data binding an object (with subclasses) to asp.net user control

text: I have an abstract class called Address and I am deriving three classes ; HomeAddress, Work Address, NextOfKin address. My idea is to bind this to a usercontrol and based on the type of Address it should bind properly to the ASP.NET user control. My idea is the user control doesn't know which address it is going to present and based on the type it will parse accordingly. How can I design such a setup, based on the fact that, the user control can take any type of address and bind accordingly. _I know of one method like :-_ Declare class objects for all the three types (Home,Work,NextOfKin). Declare an enum to hold these types and based on the type of this enum passed to user control, instantiate the appropriate object based on setter injection. As a part of my generic design, I just created a class structure like this :- ![Sample UML](http://i.stack.imgur.com/DyML8.png) I know I am missing a lot of pieces in design. Can anybody give me an idea of how to approach this in proper way.


title: Which operating system book do you recommend?

text: I want to read a good book about operating systems. More specifically, I want to read about how common problems - such as managing virtual memory, handling traps, doing context switches, managing processes and threads, etc. - are usually solved. To wit, I'm not looking for a book about how to program _towards_ an operating system; I'm looking for a book about how to _write_ an operating system. I hope this makes the question clear. Please only write **one book per answer** , for voting purposes.


title: What is a "powerful" language?

text: I have often seen people fighting over that their favorite language is more "powerful" than others. When it comes to describing a programming language, I can understand what an object oriented language is or what a dynamic language is, but I still can't figure out what exactly a "powerful" language is. What are your thoughts?


title: Is it a good idea for JS objects to draw themselves when the page loads?

text: So normally I would only use JS to modify the dom after the user interacts with something or some event goes off. This seems right for some reason. But I'm developing a widget based app where widgets need the capability to draw (print) themselves and it feels redundant to send the widget's html via the initial http request when I can just print them with the js method when the page loads. Should I be trying to avoid printing html elements with JS on the page load as a rule or is it just an optimization thing?


title: Graduated transition from Green - Yellow - Red

text: I have am having algorithm mental block in designing a way to transition from Green to Red, as smoothly as possible with a, potentially, unknown length of time to transition. For testing purposes, i will be using 300 as my model timespan but the methodology algorithm design needs to be flexible enough to account for larger or even smaller timespans. Figured using RGB would probably be the best to transition with, but open to other color creation types, assuming its native to .Net (VB/C#). Currently i have:               t = 300     x = t/2     z = 0     low = Green (0, 255, 0)     mid = Yellow (255, 255, 0)     high = Red (255, 0, 0)      Lastly, sort of an optional piece, is to account for the possibility of the `low`, `mid`, and `high` color's to be flexible as well. I assume that there would need to be a check to make sure that someone isnt putting in `low = (255,0,0)`, `mid=(254,0,0)`, and `high=(253,0,0)`. Outside of this anomaly, which i will handle myself based on the best approach to evaluate a color. ### Question:   * What would be the best approach to do the transition from `low` to `mid` and then from `mid` to `high`?   * What would be some potential pitfalls of implementing this type of design, if any?


title: What is an appropriate language for expressing initial stages of algorithm refinement?

text: First, this is not a homework assignment, but you can treat it as such ;). I found the following question in the published paper The Camel Has Two Humps. I was not a CS major going to college (I majored in MIS/Management), but I have a job where I find myself coding quite often. > For a non-trivial programming problem, which one of the following is an > appropriate language for expressing the initial stages of algorithm > refinement? > > (a) A high-level programming language. > > (b) English. > > (c) Byte code. > > (d) The native machine code for the processor on which the program will run. > > (e) Structured English (pseudocode). What I do know is that you _usually_ want to start your design implementation by writing down pseuducode and then moving/writing in the desired technology (because we all do that, right?) But I never thought about it in terms of **refinement**. I mean, if you were the original designer, then you might have access to the original pseudocode. But realisticly, when I have to maintain/refactor/ **refine** somebody elses code, I just keep trucking with the language it currently resides in. **Anybody have a definitive answer to this?** As a side note, I did a quick scan of the paper as I havn't read every single detail. It presents various score statistics, can't find where the answers are with the paper.


title: Should interfaces extend (and in doing so inherit methods of) other interfaces

text: Although this is a general question it is also specific to a problem I am currently experiencing. I currently have an interface specified in my solution called               public interface IContextProvider     {        IDataContext { get; set; }        IAreaContext { get; set; }     }      This interface is often used throughout the program and hence I have easy access to the objects I need. However at a fairly low level of a part of my program I need access to another class that will use _IAreaContext_ and perform some operations off it. So I have created another factory interface to do this creation called:               public interface IEventContextFactory      {        IEventContext CreateEventContext(int eventId);     }      I have a class that implements the _IContextProvider_ and is injected using NinJect. The problem I have is that the area where I need to use this _IEventContextFactory_ has access to the _IContextProvider_ only and itself uses another class which will need this new interface. I don't want to have to **instantiate** this implementation of _IEventContextFactory_ at the low level and would rather work with the _IEventContextFactory_ interface throughout. However I also don't want to have to inject another parameter through the constructors just to have it passed through to the class that needs it i.e.               // example of problem     public class MyClass     {         public MyClass(IContextProvider context, IEventContextFactory event)         {            _context = context;            _event = event;         }              public void DoSomething()          {            // the only place _event is used in the class is to pass it through            var myClass = new MyChildClass(_event);            myClass.PerformCalculation();               }     }      So my main question is, would this be acceptable or is it even common or good practice to do something like this (interface extend another an interface):               public interface IContextProvider : IEventContextFactory      or should I consider better alternatives to achieving what I need. If I have not provided enough information to give suggestions let me know and I can provide more.


title: Returning results of method on batch list?

text: The title is a bit vague so I'll try to elaborate. I have a function               makeFoo(int bar) -> returns Foo or throws Exception.      I also have a batch version of this               makeFoos(int[] bars) -> returns Foo[]      which basically loops through bars and runs makeFoo() on them. Issue is, if while running makeFoos(), makeFoo() throws an Exception, what do I do? I don't want to break out of makeFoos() because I want to continue processing the rest of the bars. But also, I want to retain the Exception that was thrown. My initial solution is, instead of returning Foo[], I return Result<Foo>[]. Where Result is a wrapper class:               class Result<T>:         T data;         Exception e;      Is there a better way that I can approach this? * * * Edit: Apologies if this is considered a duplicate post, but I posted a more general version of this question here: Result Object vs. Exceptions


title: How do .so files avoid problems associated with passing header-only templates like MS dll files have?

text: Based on the discussion around this question. I'd like to know how .so files/the ELF format/the gcc toolchain avoid problems passing classes defined purely in header files (like the std library). According to Jan in that answer, the dynamic linker/loader only picks one version of such a class to load if its defined in two .so files. So if two .so files have two definitions, perhaps with different compiler options/etc, the dynamic linker can pick one to use. Is this correct? How does this work with inlining? For example, MSVC inlines templates aggressively. This makes the solution I describe above untenable for dlls. Does Gcc never inline header-only templates like the std library as MSVC does? If so wouldn't that make the functionality of ELF described above ineffective in these cases?


title: Program Design clearness vs convenience

text: I've recently disputed with my colleague about the following situation: I've developed a framework that processes the resources (in java, although its not really important). It goes (simplified, pseudo-code) like this:               class Algorithm {         Processor processor = ...;         execute() {             forEach(Resource r : readResourceNamesFromFileSystem()) {                DomainObject do = convertResourceToDomainObject(r);                processor.process(do);             }                }           }          interface Processor {          process(DomainObject do);     }      Class **Algorithm** is an entry point to my framework. Resource is a representation of some content in the filesystem (it has methods for reading the data from file and the file name, which is important) Class **DomainObject** (declaration is omitted) is a java representation of the content of the file depicted by Resource. DomainObject only has data and doesn't have a filename inside. Class **Processor** represents the business logic layer, the DomainObject can be processed, stored in Database and so forth. The content data is supplied by others, we just know that these files contain the data that can be converted into DomainObject(s) which is a real object we work with in the framework. We store one DomainObject in one file. Now we argue about the file name. Colleague of mine wants the file name to be propagated into the Processor and potentially to all the layers because its easy to print the logging message/throw an exception that contains a file name if something goes wrong during the processing, or maybe to write the message like "domain object stored in file ( **here__comes__filename** ) has been processed successfully". I see the point of my colleague (convenience) but I'm sure it breaks the design and encapsulation because the processor module shouldn't really be aware of the "origin" of the DomainObject (today we store them in files one DomainObject per file, tomorrow we'll maybe use something else, something that doesn't necessarily has a filename). I claim that we better catch the exception in the Algorithm.execute method and rethrow the exception with a filename/ log the filename. The log file will be less readable but the encapsulation won't be broken. In my understanding its a design vs clearness. Could you please share your opinion, who is right, who is wrong? Should I sacrifice the design for the clearness of logs? BTW I've promised my colleague to ask this question so we'll read the possible answers together :) Thanks a lot in advance and have a nice day


title: Shared FIFO file descriptor

text: is ok to open fifo with one FD and share it with multiple threads? or is it better to have multiple fds opened for the same fifo and share these fds with the threads? BTW, I'll be doing write and read. The environment is linux, C, pthreads


title: Using Visual Studio as a Task-Focused IDE

text: Are there patterns or libraries or any official Microsoft SDK for using Visual Studio as a specifically Task-Focused UI? For example, both Revolution R (IDE for the R language) and SQL 2012 (and I think SQL 2008 and possibly 2005) use Visual Studio as the underlying IDE framework. Is there an officially supported SDK and/or examples/samples for doing this type of thing? I am building a language Parser for an existing language - whose only available IDE is INSANELY expensive - using Irony (and eventually will generate a Language Service as well). Any direct or indirect suggestions/answers are appreciated.


title: Relative encapsulation design

text: Let's say I am doing a 2D application with the following design: There is the Level object that manages the world, and there are world objects which are entities inside the Level object. A world object has a location and velocity, as well as size and a texture. However, a world object only exposes `get` properties. The `set` properties are private (or protected) and are only available to inherited classes. But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation). How to tackle this problem? Should I just make everything public? Currently what I'm doing is having a inner class inside game object that does the `set` work. So when Level needs to update an objects location it goes something like this:               void ChangeObject(GameObject targetObject, int newX, int newY){      // targetObject.SetX and targetObject.SetY cannot be set directly      var setter = new GameObject.Setter(targetObject);      setter.SetX(newX);       setter.SetY(newY);      }      This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.


title: What if any languages treat undisposed resources as an error?

text: I've seen lots of code like the following example. It's in Python, but the same mistake is made in all languages with managed resources:               f = open('foo.txt', 'rb')     for line in f: print line      That's it. The error is that `close(f)` wasn't called so the file handle is kept open until some indeterministic time in the future when the runtimes memory management decides to reclaim memory. Python has `with` and c# has `using` to help make resource cleanup easier, but let's disregard those features for a minute. Given that:   1. It's a programming error not to explicitly close open files.   2. The runtime can detect that an open file has not been closed. Why then doesn't the runtime throw an error instead of being "helpful" and closing the file for the programmer? That would be the fail fast and fail early strategy. Is there a technical reason why it can't? Is there any languages that does it? Has the idea been considered before (I've googled but not found anything)? Here is how you **almost** implement the feature in Python:               class mustclose:         def __init__(self, f):             self.f = f         def __del__(self):             if not self.f.closed:                 raise Exception("You forgot to close() me!")     k = mustclose(open('foo.txt', 'wb'))     #k.f.close()      Two problems: It requires wrappers, Python doesn't like to throw exceptions from destructors. (Read this http://stackoverflow.com/questions/2807241/what-does-the- expression-fail-early-mean-and-when-would-you-want-to-do-so SO question for background on why failing fast is often desirable)


title: How do I preview my mobile web application on a Windows 7 PC?

text: I am developing a mobile web application that may be browsed in an iPhone. I would like to test this application, but I lack a mobile web device. How can I test this mobile application on a Windows 7 PC?


title: What should I recommend a small company looking for C# developers

text: Here is the issue. I am a senior developer, and one of the start-ups I designed the system (management system/database/web) a long time ago, have grown and need software updates. I have left their system to another developer long time ago, but apparently he has left the job, and so they are asking me if I can suggest them where to find a new one. The problem is that the company has no clue that the IT is not cheap. They expect multiple features to be added for 40$, so that's an issue. Actually one of the reasons why I left the project when I did. Lots of expectations, little pay, also I know those people outside work, so I decided to avoided stressing the nonwork-relationships and left the project gracefully. Today they asked me for an advice, and I told them that the feature list they want is probably going to cost some if they'll get a senior developer for the job. So I guess their best bet is to find someone who loves coding and has just finished the school. Which would give someone a chance to code for money which is good for a student, and at the same time, allow the student to get some hands on experience. Then again, the system is not exactly 20 line console program, there is an MSSQL database, ASP.NET web page and content management system with all the AJAX stuff and some other things. So student straight out of school could have some problems with that. But, I thought about the issue some more, and I think that junior developer is a tricky deal, without mentoring, he can either screw up royally, or just do what's asked. Also, it seems no one is coming to interviews at all, which is weird, or maybe not. What should I suggest them?


title: Maintaining Method Signatures across languages?

text: I'm finishing up a port I did of a portion of a Java Library. The library calculates sunrise and sunset for a given latitude and longitude. The original Java library also calculated various times based on sunrise and sunset, which I plan to get to later. That said, I'm working with Objective-C and the Cocoa touch framework. The original methods, being Java, all began with `get` and took their arguments in parenthesis. However, Objective-C has a different method structure, so the methods end up looking different. For example, `public double getUTCSunset(AstronomicalCalendar astronomicalCalendar, double zenith, boolean adjustForElevation)` becomes this: `- (double) getUTCSunsetForDate:(NSDate*)date andZenith:(double)zenith adjustForElevation:(BOOL)adjustForElevation`. The problem here is twofold. First of all, according to the Apple Documentation on coding convention, method names (and "getters"), should not include `get` in them. However, a second issue arises if we drop the `get`. We end up with a method signature that begins with a capital letter, which is also not supposed to happen. How would you rewrite this method, while keeping the method signatures similar enough to be recognizable to each other?


title: Preparing For a New Programming Project

text: I consider myself to be a novice programmer -- a noob is you like. As such I'm still not sure how to get started on a project where I will be doing stuff that I've never done before. For instance, I would like to write a program that can download videos from YouTube and convert them to a format specified by the user. I've never done anything like this before and I really have no idea where to start. Rather, I have no idea what I should search for. If I search for "YouTube Downloader" then I get hit with a bunch of useless links to existing YouTube Downloader sites, most of which don't work. What I want to know is how to get started on a project that I know nothing about. How do I find out what is required for this project? How do I find out what languages are best suited for this? How can I find out if there are any APIs that would be particularly useful? Also, what other questions should I be asking myself when preparing to take on a new project?