IUserType like feature inEntity Framework

I'm working on a new project, we want to build a new, modern, application working with our legacy data sources, and especially, legacy databases. We want to use an ORM and we want advanced features so the obvious choice seems to be between NHibernate and EF 6. We can eventually make some minor changed to the databases but not totally modified the model since it's used by many other apps. Now, obviously since it's legacy stuff, it sucks. The database has many flaws and at the moment, I'm writing some basic code to test EF and NH and see if we can work around these flaws. My current problem is with Entity Framework. In my database, many fields are used in a "non-standard" way. For example, I have fields that are representing datetime with special format strings, or xml data in string. I'd like to let EF do the convert work without exposing these special fields to my API and without using another layer on top of EF. I could solve this problem with IUserType in NHibernate but I didn't find a way in EF. Here's an example, let's say I have a field representing a date in my DB, and it should be formatted like this : ddmmyy (090214 for today). I don't want to expose this string in my object but I want to be able to manipulate this date with classical datetime like : var comp = ctx.Companies.First(c => c.Id == 1); comp.Date = DateTime.Now; ctx.SaveChanges(); And it automatically saves the date with the special format in the DB. I can do this by mapping a DateString property for example and makes my Date field with a getter/setter that do the transform but I don't want to expose this DateString property and it's a bit painfull to do it with all my Date fields across all my tables. IUserType in Nhibernate was perfect to solve this kind of problems, is there something equivalent in EF? Thanks


I looked at it in my field of work, which is film and pretty much every software we use comes with python as a scripting language: http://en.wikipedia.org/wiki/List_of_Python_software That made me assume it's the most popular. How did Python become popular as a scripting language? Especially as an embedded language into standalone applications. What's the reason for this? There are others like Lua, Ruby, etc. but yet it looks like Python came on top. If it's because of a particular thing or just a matter of getting out there at the right time?


Memory management for fast message passing between threads in C++

Suppose there are two threads, which communicate by asynchronously sending data messages to each other. Each thread has some kind of message queue. My question is very low level: What can be expected to be the most efficient way to manage the memory? I can think of several solutions:   1. Sender creates the object via `new`. Receiver calls `delete`.   2. Memory pooling (to transfer the memory back to the sender)   3. Garbage collection (e.g., Boehm GC)   4. (if the objects are small enough) copy by value to avoid heap allocation completely 1) is the most obvious solution, so I'll use it for a prototype. Chances are that it is already good enough. But independent of my specific problem, I wonder which technique is most promising if you are optimizing for performance. I would expect pooling to be theoretically the best, especially because you can use extra knowledge about the flow of information between the threads. However, I fear that it is also the most difficult to get right. Lots of tuning... :-( Garbage collection should be quite easy to add afterwards (after solution 1), and I would expect it to perform very well. So, I guess that it is the most practical solution if 1) turns out to be too inefficient. If the objects are small and simple, copy by value might be the fastest. However, I fear that it forces unnecessary limitations on the implementation of the supported messages, so I want to avoid it.


What is Java's primary focus? Why does it take so long to get new features?

I have been exploring the new features in the JDK8, like the lambda expressions, the extension methods, and the new stream API. Evidently none of these features are new in the programming world and that made wonder why are getting all these things in Java until now. We had lambda expressions in Lisp (1958), SML (1973), Haskell (1990), Python (1991), JavaScript (1994), Ruby (1995), Scala (2003), C# (2007) and 55 years after Lisp and practically everyone else, in Java (2013). And I had read about streams in SIC (1996). I have been wondering why now? The evidence suggests that competing with other languages is not the motivation. It would seem that all the cool new features in this release of Java are just a by-product of implementing parallelism. We have lambdas because they make writing parallel algorithms simpler, and we have extension methods because we needed them to give support to the changes that lambda expressions required, etc., etc. So, my question is: can we safely affirm that the main topic in this upcoming release of Java is actually parallelism? Or can we justify other reasons for the appearance of the oldest tricks in the book until now in Java?


Brittle unit tests due to need for excessive mocking

I've been struggling with an increasingly annoying problem regarding our unit tests that we are implementing in my team. We are attempting to add unit tests into legacy code that wasn't well designed and while we haven't had any difficulty with the actual addition of the tests we are starting to struggle with how the tests are turning out. As an example of the problem let's say you have a method that calls 5 other methods as part of its execution. A test for this method might be to confirm that a behavior occurs as a result of one of these 5 other methods being called. So, because a unit test should fail for one reason and one reason only, you want to eliminate potential issues caused by calling these other 4 methods and mock them out. Great! The unit test executes, the mocked methods are ignored (and their behavior can be confirmed as part of other unit tests), and the verification works. But there's a new problem - the unit test has intimate knowledge of _how_ you confirmed that behavior and any signature changes to any of those other 4 methods in the future, or any new methods that need to be added to the 'parent method', will result in having to change the unit test to avoid possible failures. Naturally the problem could be mitigated somewhat by simply having more methods accomplish less behaviors but I was hoping there was perhaps a more elegant solution available. Here's an example unit test that captures the problem. **As a quick note 'MergeTests' is a unit testing class that inherits from the class we are testing and overrides behavior as needed. This is a 'pattern' we employ in our tests to allow us to override calls to external classes / dependencies.**               [TestMethod]     public void VerifyMergeStopsSpinner()     {         var mockViewModel = new Mock<MergeTests> { CallBase = true };         var mockMergeInfo = new MergeInfo(Mock.Of<IClaim>(), Mock.Of<IClaim>(), It.IsAny<bool>());              mockViewModel.Setup(m => m.ClaimView).Returns(Mock.Of<IClaimView>);         mockViewModel.Setup(             m =>             m.TryMergeClaims(It.IsAny<Func<bool>>(), It.IsAny<IClaim>(), It.IsAny<IClaim>(), It.IsAny<bool>(),                              It.IsAny<bool>()));         mockViewModel.Setup(m => m.GetSourceClaimAndTargetClaimByMergeState(It.IsAny<MergeState>())).Returns(mockMergeInfo);         mockViewModel.Setup(m => m.SwitchToOverviewTab());         mockViewModel.Setup(m => m.IncrementSaveRequiredNotification());         mockViewModel.Setup(m => m.OnValidateAndSaveAll(It.IsAny<object>()));         mockViewModel.Setup(m => m.ProcessPendingActions(It.IsAny<string>()));              mockViewModel.Object.OnMerge(It.IsAny<MergeState>());                  mockViewModel.Verify(mvm => mvm.StopSpinner(), Times.Once());     }      How have the rest of you dealt with this or is there no great 'simple' way of handling it? **Update - I appreciate everyone's feedback. Unfortunately, and it's no surprise really, there doesn't seem to be a great solution, pattern, or practice one can follow in unit testing if the code being tested is poor. I marked the answer that best captured this simple truth.**


I'm creating my own scalable, rapid prototyping web server. How should I design it?

I'm going to create my own web server that focuses on scalability, rapid prototyping and the use of JavaScript as the server's scripting language, much like node.js. It will use a Model-View-Controller design pattern so a web application can support more concurrent users just by adding hardware -- and not having to redesign the software. Basically, I'm aiming to produce a framework that allows for fast and easy development of cloud applications without the need to write lots of boiler plate code. I've got some questions about this...   1. How hard will it be to put MySQL in the cloud? How could I go about implementing this and make the resulting product free? Will I have to write my own engine or modify an existing one, if I do what should I watch out for?   2. To make this scalable I need to adjust from one server to hundreds of servers this creates the requirement for the servers to be load balancing, how should I do this? If I balance based on the work load per server I would need gateway to handle all the incoming requests. Is it the right idea to have all the servers check into the gateway and update there status.   3. By having the servers run through a gateway if the gateway dies all the incoming requests are ignored. I'm thinking that having all the servers maintain a list of each other, or at least a few I could rebuild the list of servers and establish a new gateway. Is it worth it? Or should I have a backup gateway that could switch out? Should I let the user choose?   4. How should I pick which server handles the database and which handles the page serving? Should I spread the database so that queries are preformed on multiple servers? Which would theoretically improve performance.   5. The servers would need to mirror the database at least once so that if a server goes down the database isn't corrupted. So this brings up writing another question, should I broadcast SQL queries so that all the servers can take a bit of the work load? If I do it that way wouldn't a query clog up the network so that other queries couldn't be preformed? What are my alternatives?   6. Finally, is there a free solution already out there that might need a little modification that suits my needs?


Which string search algorithm is actually the fastest?

I have been stuck for some time on which is the fastest string search algorithm, heard many opinions, but in the end I'm not sure. I have heard some people saying that the fastest algorithm is Boyer-Moore and some saying that Knuth-Morris-Pratt is actually faster. I have looked up for the complexity on both of them but they mostly look the same `O(n+m)`. I have found that in the worst case scenario Boyer-Moore has an `O(nm)` complexity compared to Knuth-Morris-Pratt which has O(m+2*n). Where n=length of text and m=length of pattern. As far as I know Boyer-Moore has a linear-worst case-time if I would use the Galil Rule. My question, Over all which is actually the fastest String search algorithm (This question includes all possible sting algorithms not just Boyer-Moore and Knuth-Morris-Pratt). **Edit:** Due to this answer What I'm exactly looking for is: Given a text `T` and a pattern `P` I have to find all the appearances of `P` in `T`. Also the length of P and T are from `[1,2 000 000]` and the program has to run under 0.15 sec. I know that KMP and Rabin-Karp are enough to get a 100% score on the problem but I for one wanted to try and implement Boyer-Moore. Which would be best for this type of pattern search?


Optimal storage space calculation for name, address, phone, fax and email data

Given the following assumptions:   * The amount of available data storage is highly limited   * All data is international    * As much storage as possible must be preserved since it will be used for something else Is there any widely accepted standard or best practice which defines how much storage should be allocated for those items? **Note** : I'm not looking for assumptions but for facts like "97.5% of all names fit into 70 bytes using UTF-8" and "An international address must at least contain field1, field2 and field3 of size1, size2 and size3". **Edit** : I'm looking for the fields/lengths to use in the user interface. Not a technique to store it efficiently.


How important are UML diagrams for a successful project?

I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex. I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?


Low Latency Unix/Linux

Most low latency/high frequency programming jobs (based on job specs) appear to be implemented on unix platforms. In a lot of the specs they make particular request for people with "low latency linux" type of experience. Assuming this does not mean a real-time linux OS, could people give me help with what this could be referring to? I know you can set CPU affinity to threads, but I am assuming they are asking for much more to it than that. Kernel tuning? (although I heard manufacturers like solarflare produce kernel bypass network cards anyway)? What about DMA or possibly shared memory between processes? If people could give me brief ideas I can go and do the research on google. (This question will probably require somebody familiar with High Frequency Trading)


Difference between lexical scoping and passing variables in JS

There are several ways to reach the same end point in JS, for example:               (function (foo, bar) {       return {run: function () {return foo(bar);}};     } (foo, bar));          (function (foo, bar) {       return (function(foo, bar) { return {run: function () { return foo(bar); }}} (foo, bar))     } (foo, bar))          (function (foo, bar) {       var Fizz = function (foo, bar)  { this.run = function () { return foo(bar); }; };       return new Fizz(foo, bar)      } (foo, bar))      Now for these, I know that one difference is that the prototype in the third case for the returned object would be different, but other than that, all three paths lead to an object which provides the same api. And since Javascript is a duct typed language, what a thing is is usually defined by its behavior. Are there any other implications of choosing any one approach of the three that I am ignoring ?


Bug fixing in Scrum, at the end of the project

We have a project that is reaching a deadline for the final production release. It's a fixed price project and up till now we've managed to work in 2 week iterations, doing regular releases to our "inner test environment" where BAs and people acting as POs from the client's side had a chance to have a look, give feedback etc. We're now at the point where we have only 4 weeks to end this project and as we go to deploy the separate modules of this application to the client's environment, we've been struggling with a lot of bugs appearing. We have some functionality to be done still but my question is - what is the best way to handle those bugs as they appear? Since there's really a lot of them (due to project specifics, we didn't have the ability to test it on client's environment earlier) and it's impossible to estimate them up front + we have only 4 weeks till the end, does it make sense to keep Scrum or switch to Tech Lead dispatching work daily to the devs directly?


Will the portions of Boost that are incorporated into the new C++ standard continue to be developed?

What will happen to the portions of the Boost library that are incorporated into the new C++ standard? Will they continue to evolve and any changes be reincorporated into the standard which follows C++0x?


Is collective code ownership mandatory in Scrum?

Is is an absolute must when following the Scrum methodology to practice collective code ownership, instead of for example weak code ownership?


How does a fresher with a clean slate turn into a good programmer?

As a graduate fresh out of college with a clean slate, how can one go about being a good programmer who writes good maintainable code? How does one learn good coding practices and apply them? Can one get these skills by reading any specific books on Software development or is it something that comes purely from experience? (I don't like to believe that it's purely experience based since I see people here complaining about bright co-workers with years of experience writing bad code). What are some suggestions on getting good at writing clean code? Passion and ability are assumed.


Do Web Applications and The Cloud provide better Career Opportunities than Systems Programming?

As the years progress , I can't help but see how web apps and the cloud is replacing normal computer software. Developers of systems programming languages like C/C++ are going down the hill and PHP / ASP.NET(C#) is rising to the skies (cloud?). Since I am a serious C++ fan and like to develop mostly in C++, I was wondering whether it is prudent to say on this path. Will there be employment for C++ programmers after , say , 10 years? I have seen a lot of unemployed C++ programmers while there are no .NET programmers or Web Developers going downhill. So should I move to the web and/or cloud now, when there is still time, or should I continue going down the C++ path? Will there be enough employment for C++ and other Systems (offline?) Programming Language developers?


When is a loop "non-trivial"?

Is it correct to call a loop that you do not know the limit at compile time `"non-trivial"`? If you know that you will be using a value from a class that will be in a range e.g. between 0-1000, is that still non-trivial? e.g. Where ISomeInterface.MAX_LIMIT is always between 1-1000:               public bool someMethod(Type someType, int someId, int someVariable)     {         bool returnFlag = false;         int maxLimit = (Activator.CreateInstance(someType) as ISomeInterface).MAX_LIMIT;              for (int i = 0; i < maxLimit; i++) //is this a non-trivial loop?         {             if (_someSerivce.SomeOtherMethod(someType, someId, someVariable, i))             {                 returnFlag= true;             }         }         return returnFlag;     }      * * * **Edit:** Was uncertain as to whether this was a meaningful piece of terminology. I originally read it in one of Jon Skeet's pieces from yoda.arachsys: http://www.yoda.arachsys.com/csharp/stringbuilder.html (see the section headed _Rules Of Thumb_ ). Do you use this as technical terminology at all?


Who extends interfaces? And why?

AFAIK, my class `extends` parent classes and `implements` interfaces. But I run across a situation, where I can't use `implements SomeInterface`. It is the declaration of a generic types. For example:               public interface CallsForGrow {...}          public class GrowingArrayList <T implements CallsForGrow>  // BAD, won't work!                                   extends ArrayList<T>       Here using `implements` is syntactically forbidden. I thought first, that using interface inside <> is forbidden at all, but no. It is possible, I only have to use `extends` instead of `implements`. As a result, I am "extending" an interface. This another example works:               public interface CallsForGrow {...}          public class GrowingArrayList <T extends CallsForGrow>  // this works!                                   extends ArrayList<T>       To me it seems as a syntactical inconsistancy. But maybe I don't understand some finesses of Java 6? Are there other places where I should extend interfaces? Should the interface, that I mean to extend, have some special features?


Is inline SQL still classed as bad practice now that we have Micro ORMs?

This is a bit of an open ended question but I wanted some opinions, as I grew up in a world where inline SQL scripts were the norm, then we were all made very aware of SQL injection based issues, and how fragile the sql was when doing string manipulations all over the place. Then came the dawn of the ORM where you were explaining the query to the ORM and letting it generate its own SQL, which in a lot of cases was not _optimal_ but was safe and easy. Another good thing about ORMs or database abstraction layers were that the SQL was generated with its database engine in mind, so I could use Hibernate/Nhibernate with MSSQL, MYSQL and my code never changed it was just a configuration detail. Now fast forward to current day, where Micro ORMs seem to be winning over more developers I was wondering why we have seemingly taken a U-Turn on the whole in-line sql subject. I must admit I do like the idea of no ORM config files and being able to write my query in a more optimal manner but it feels like I am opening myself back up to the old vulnerabilities such as SQL injection and I am also tying myself to one database engine so if I want my software to support multiple database engines I would need to do some more string hackery which seems to then start to make code unreadable and more fragile. (Just before someone mentions it I know you can use parameter based arguments with most micro orms which offers protection in most cases from sql injection) So what are peoples opinions on this sort of thing? I am using Dapper as my Micro ORM in this instance and NHibernate as my regular ORM in this scenario, however most in each field are quite similar. What I term as _inline sql_ is SQL strings within source code. There used to be design debates over SQL strings in source code detracting from the fundamental intent of the logic, which is why statically typed linq style queries became so popular its still just 1 language, but with lets say C# and Sql in one page you have 2 languages intermingled in your raw source code now. Just to clarify, the SQL injection is just one of the known issues with using sql strings, I already mention you can stop this from happening with parameter based queries, however I highlight other issues with having SQL queries ingrained in your source code, such as the lack of DB Vendor abstraction as well as losing any level of compile time error capturing on string based queries, these are all issues which we managed to side step with the dawn of ORMs with their higher level querying functionality, such as HQL or LINQ etc (not all of the issues but most of them). So I am less focused on the individual highlighted issues and more the bigger picture of is it now becoming more acceptable to have SQL strings directly in your source code again, as most Micro ORMs use this mechanism. Here is a similar question which has a few different view points, although is more about the inline sql without the micro orm context: http://stackoverflow.com/questions/5303746/is-inline-sql-hard-coding


How can I justify my disclaimer of warranties license to a customer?

I'm selling a software that lets users manipulate critical information. In my licence contract (redacted by a lawyer specialized in this field), I've got a standard clause reading : > THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED > WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF > MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO > EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, > SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, > PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; > OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, > WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR > OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF > ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. I've seen equivalents in almost every single software I've been using so far. So far, all of our clients accepted that without difficulty, but now one potential client is contesting it. Actually he's telling me something along the lines of : > You mean that if I use your software to buy something at $10 to a third > party company, and there's a bug in your software (as you don't guarantee > there aren't any), and you transmit a $20 order, I shall pay the $10 > difference, not you? I'm a bit stuck between what seems like common sense on his part, and the fact that my insurance companies would probably not insure me for those kind of risks, and if you consider we're talking millions, not plain $, it doesn't feel comfortable being responsible for that kind of potential losses. So far, the best answer I've come up with is that everybody does it in the industry (Microsoft doesn't guarantee that the mail you've sent using Outlook won't be altered, eg by turning all the $10's in $20's ...) Any advice on how to handle this ? (apart from doing our best to ship bug-free software, of course :p)


Should programmers help testers in designing tests?

How much should programmers help testers in designing tests? I don't think they should help at all. My worry is that if they help testers in designing tests for their own code, they'll 'infect' the testers with their own prejudices and blind spots about that code. I feel that the requirements should be sufficient for giving the information needed for testers to create their tests. If there is some part of the implementation that the programmers find worrisome, then I think it's their duty to implement unit tests to test that part or even run their own informal system tests to test that part. Not everyone I know agrees with this though (and I understand some of their points to a certain extent). What do others think about this? Is this discussed in the literature anywhere?


Should we be using functional and/or logic programming languages more?

I've programmed a bit of Haskell and Prolog as part of a couple of uni courses, but that's about it. And I've never seen it been used in industry (not that I've had much of working experience to begin with but I've never seen an ad where you are required to know them). So should we be using functional and/or logic programming languages more often? Are there any advantages or disadvantages for using or not using them?


Store the result of a complex but frequent database query, in another temp persisting table

I have a slightly complex SELECT query which uses a number of JOINs and variables inside it and the query is run frequently throughout the application. The result varies when one column is updated. Eg: When the product quantity is updated only, the result set changes. So my question is, is it a good idea to run a trigger and update a temporary table in the database, with my SELECT queries results, whenever the product quantity is updated? Or to run the complex SELECT query every time? Right now I tested with ~10 rows of data and the query execution time is 0.001 seconds. I want to use the best possible method which won't hinder the performance as the DB grows. Thank you!


What are the rules for permissible names on google app engine?

When I create a new application, and I am choosing a name, most common dictionary words appear to be unavailable, along with even some of the more esoteric ones including 'aaaaaa' (I've tried variable length, and different letters). However, most of these applications don't actually seem to exist. So either all of these names have been taken, but none of these people have bothered to build even a hello world app on it, or there are additional naming rules that app engine enforces beyond > Application Identifier must be between 6 and 30 characters. Lowercase > letters, digits, and hyphens are acceptable characters. Leading and trailing > hyphens are prohibited. I'd like to rule out the later -- are there any additional naming rules that GAE imposes?


What is the one bit of computer science theory I should know?

Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the **one bit** of computer science I should know to make me a better **real world** programmer? (By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).


How do you avoid disrupting the flow of work when the Product Owner asks for a release?

My team has been using Scrum for years with a goal to deliver a potentially releasable build each sprint. We recently started using a Kanban board moving away from time-boxed delivery to feature-boxed delivery. So far, this seems to better fit the teams natural way of working. With feature-boxed delivery, stories are pulled from the backlog when an individual feels they are comfortably ready to begin working on it. The teams average story lead time is three weeks. So, theoretically, at the moment the product owner asks for a release, the team should be able to deliver it three weeks later. When the PO sets the "stop development" trigger, individuals who have time are supposed to start helping with stories already underway to begin clearing out the board. The people freed up first are typically the "front-end" folks... Those more skilled at analysis and development. They are typically asked to help with back-end work, like system testing. The teams work flow, or cadence changes each time the stop trigger is set. What do you do to minimize this change and keep the team working as efficiently as possible? How do you avoid the disruption caused by the Product Owner asking for a release?


Correct pattern for Worker Processes involving Queues & Tables

Edit: OK, so, people said it is unclear what I am asking. I am asking for feedback on this design. Here is an example user story: As a group admin on the website I want to be notified when a user in my group uploads a file to the group. Easiest solution would be that in the code handling the upload, we just directly create an email message in there and send it. However, this seems like it isn't really the appropriate level of separation of concerns, so instead we are thinking to have a separate worker process which does nothing but send notifications. So, the website in the upload code handles receiving the file, extracting some metadata from it (like filename) and writing this to the database. As soon as it is done handling the file upload it then does two things: Writes the details of the notification to be sent (such as subject, filename, etc...) to a dedicated "notification" table and also creates a message in a queue which the notification sending worker process monitors. The entire sequence is shown in the diagram below. My questions are: Do you see any drawbacks in this design? Is there a better design? The team wants to use Azure Worker Roles, Queues and Table storage. Is it the right call to use these components or is this design unnecessarily complex? Quality attribute requirements are that it is easy to code, easy to maintain, easy to debug at runtime, auditable (history is available of when notifications were sent, etc...), monitor-able. Any other quality attributes you think we should be designing for? Original: We are creating a cloud application (in Azure) in which there are at least 2 components. The first is the "source" component (for example a UI / website) in which some action happens or some condition is met that triggers a second component or "worker" to perform some job. These jobs have details or metadata associated with them which we plan to store in Azure Table Storage. Here is the pattern we are considering: ![enter image description here](http://i.stack.imgur.com/fLIs4.png) Steps:   1. Condition for job met.   2. Source writes job details to table.   3. Source puts job in queue. Asynchronously:   1. Worker accepts job from queue.   2. Worker Records DateTimeStarted in table.   3. Queue marks job marked as "in progress".   4. Worker performs job.   5. Worker updates table with details (including DateTimeCompleted).   6. Worker reports completion to queue.   7. Job deleted from queue. Please comment and let me know if I have this right, or if there is some better pattern. For example sake, consider the work to be "sending a notification" such as an email whose template fields are filled from the "details" mentioned in the pattern.


How do I overcome paralysis by analysis when coding?

When I start a new project, I often times immediately start thinking about the details of implementation. "Where am I gonna put the DataBaseHandler? How should I use it? Should classes that want to use it extend from some Abstract superclass..? Should I use an interface? What level of abstraction am I going to use in my class that contains methods for sending requests and parsing data?" I end up stalling for a long time because I want to code for extensibility and reusability. But I feel it almost impossible to get past thinking about how to implement perfectly. And then, if I try to just say "screw it, just get it done!", I hit a brick wall pretty quickly because my code isn't organized, I mixed levels of abstractions, etc. What are some techniques/methods you have for launching into a new project while also setting up a logical/modular structure that will scale well? - _-_ EDIT - _-_ Well, this is already the type of question that is difficult to accept an answer to, but wanted to get some more feedback, see if there's some consensus. TDD sounds really cool and, frankly, I've been meaning to get more up to speed on using JUnit, etc. At the same time, what do the fans of TDD think about the fact that one legitimate point with relation to TDD solving my particular issues, is that TDD doesn't really seem to address the question of design. Sure, I agree TDD will help me define what I want to do and then I can gradually work through the how, but there are many different overall design patterns/structures that could all pass through unit testing. That's just it: it tests single UNITS. I guess I'm a bit confused... I dunno. Maybe I'm just trying to procrastinate even more by trying to figure out some magical formula, but I would like to hear how some of the veterans approach this area... Thanks!


Creating an Interface To a Language's Standard Library?

In the process of learning test-driven development, I've been introduced to dependency injection and the use of interfaces, and have started using these concepts in my own PHP code in order to make it more testable. There have been times when I've needed to test code that was doing things like calling the PHP `time()` function. In order to make these tests predictable, it seemed logical to create an interface to the standard PHP functions I use so that I can mock them out in my tests. Is this good software design? What are the pros and cons of doing this? I've found myself groaning at how quickly my PHP interface can stick its fingers into everything I do. Is there a better way to make code that relies on PHP- accessed state and functions more testable?


Does FitNesse improve product quality and collaboration?

I heard about a tool named FitNesse, which is supposed to promote better collaboration between development, testing, and product groups. What are your experiences with it? Does it really improve program quality? Are there any drawbacks to using it?


Generating tests from specification

I am reading "The Pragmatic Programmer" . The book has the following paragraph > Dave once worked on an international telex switch. Quite understandably, the > client demanded an exhaustive test specification and required that the > software pass all tests on each delivery. To ensure that the tests > accurately reflected the specification, the team generated them > programmatically from the document itself. When the client amended their > specification, the test suite changed automatically. Once the team convinced > the client that the procedure was sound, generating acceptance tests > typically took only a few seconds. I am curious to know how he created tests from specification . What format was the specification in ? How to write a program that will automatically read the specification and write test cases. Have I misunderstood the above paragraph ?


How do you overcome your own coding biases when handed legacy code?

As programmers, we often take incredible pride in our skills and hold very strong opinions about what is 'good' code and 'bad' code. At any given point in our careers, we've probably had some legacy system dropped in our laps, and thought 'My god, this code sucks!' because it didn't fit into our notion of what good code should be, despite the fact that it may have well been perfectly functional, maintainable code. How do you prepare yourself mentally when trying to get your head around another programmer's work?


What would be the most efficient way to reduce the complexity of a set of rotations to a cube?

Despite the long title, my question is fairly simple. Let's say you have a cube in 3D-space and you want to rotate it along the three axes based on the set of instructions provided by a user or elsewhere in the program. How would you simplify, if you will, that set of rotations? For simplicity's sake, we'll use the notation involved in rotating a Rubik's cube. (And also because that's what I'm programming.. But that's unimportant.) So, X would be a clockwise rotation along the X axis, X' would be a counterclockwise rotation along the X axis, and X2 would be two clockwise rotations rotations along the X axis. Now, let's say I have a set of instructions `X Y X'`. That set of instructions did the same thing that the single instruction of `Z` would have done. Or, in a simpler case, if I had `X X'` or `X2 X2`, those rotations cancel out. My question is, what is the best way - from a programming perspective - to simplify these sets of instructions?


Web Services exposed by url

Lets take some random internet site which i am not aware of any API it exposes for it's web services if there are any , is there a way to query that URL for exposed web services ?


Is it advisable to create an ad-hoc open source software license?

IANAL I have several private projects that I _might_ be needed to show to my prospective employers. I haven't uploaded them to any online version control system because not only do I not have the patience to filter the many many licenses available and choose the most appropriate one (as I am not yet sure how I would want my open source code to be used), I also feel the projects aren't fit enough for upload in public domain as they are not tested rigorously enough for me. I could create a private repository somewhere and allow access to the prospective employers, or I could simply take a USB stick with me, but the question still remains about licensing. So, I thought of creating an ad-hoc license to the effect of saying "this code is made available to you and no part of it shall be reproduced from memory...", which is almost like signing a NDA. I know it might sound silly, or inane, but I want to protect my IP in someway (you never know what your code could become!). What is the best way of going about this? If indeed license creation is an option, how would the creation work? Would merely writing a prologue at the beginning of every source file suffice, or is there some long winding legality involved?


State Pattern Code for embedded device - Dependency Injection of Device Objects in Context and State Classes

I'm wrestling with some code and I think I've finally gotten some state pattern code working with my events. I've got a _simplified_ system that will work like this: ![State Diagram](http://i.stack.imgur.com/LzxdG.jpg) This is my first go with State Pattern code and the examples I found were too simple or just not related to my type of device. **Q:** Is the context class supposed to do all of the controlling of peripherals of the device or should the active state directly control them? For instance, Drive the display, read the sensors, etc. To me, either way would work, but don't have enough experience here to choose what's correct. I mention DI because I'm having to pass all of my peripherals into the context then into each state to provide control. OR do I just pass them into context and make the calls to the context from the active state(mentioned above)? The way I see it, the active state and the context are constantly communicating with each other via DI to control the device. I hope this is clear. Context Class Code:               //context     //the context will capture the interrupt events and delegate the response     class ModeContext     {         private int rotationCount;         private string direction;         private State state;         public RotaryEncoder rotaryEncoderInstance;         public Tlc5940 Display;              //public event NativeEventHandler rotationEventHandler;// = null;              public ModeContext(RotaryEncoder re, Tlc5940 display)         {             this.State = new Mode1(this);             rotaryEncoderInstance = re;             rotaryEncoderInstance.RotationEventHandler += OnRotationEvent;//attach to Context's Handler             rotaryEncoderInstance.MomentaryButtonEventHandler += OnButtonEvent;             Display = display;             rotationCount = 0;         }              public void RunStateTask()         {             state.MainTask(this);         }              public State State         {             get { return state; }             set { state = value; }//debug state change         }              //Event Handler                 public void OnButtonEvent(uint clickCount, uint zero, DateTime time)         {             switch (clickCount)             {                case 0:                                                     state.OnButtonHold(this);                             break;                case 1:                             state.OnButtonSingleClick(this);                             break;                //default:                //             throw new Exception("Something went wrong!");                //             break;                  }                   }              public void OnRotationEvent(uint data1, uint data2, DateTime time)         {             rotationCount++;             if (data1 == 1)              {                  direction = "Clockwise";                 state.OnCWRotationEvent(this);             }             else             {                  direction = "Counter-Clockwise";                 state.OnCCWRotationEvent(this);             }             //Debug.Print(rotationCount.ToString() + ": " + direction + " Context Mode Rotation Event Fired!");         }          }      Example State Class:               class Mode1 : State//, IDisposable     {              public Mode1(ModeContext mode): base(mode)         {             Display = mode.Display;            }              public override void MainTask(ModeContext mode)         {             Debug.Print("Mode1 Main Task Running...");             //read Sensor             //display the value to Display             //let the context determine how to display it??             //or call a method in the context that encapsulated all of it's functions?             //Thread.Sleep(500);         }              #region event handlers         public override void OnCCWRotationEvent(ModeContext mode)         {             //change state             mode.State = new Mode2(mode);             Debug.Print("Changing State");         }         public override void OnCWRotationEvent(ModeContext mode)         {             //change state             Debug.Print("Changing State");             mode.State = new Mode0(mode);         }         public override void OnButtonSingleClick(ModeContext mode)         {             Debug.Print("Mode1: Single Click!");         }         public override void OnButtonHold(ModeContext mode)         {             Debug.Print("Mode1: Press and Hold Detected!");         }              #endregion               }


Multiple remote views of a C# application

I have a C# application (Desktop based application for Windows OS), which I wanted to use from Web browser. The application is a kind of analyzing tool, which takes some input values and performs set of calculations over it then displays an animation of the results. Since the application can't be coded again in a new language, Can anyone suggest me, how I can view and interact with this C# application from browser (like the way we interact with Java Applets)? Also the application can be used by more than one user at a time, so there must be multiple views for this web application.


Small companies and software licensing

Small companies with small budgets may not have have the money to invest in expensive software licenses that they may need for a given development project. This is even more so if the project was a loss-leader to drum up more business and the price of the development product cannot be renegotiated without potentially harming relationships, when it is discovered later that some proprietary expensive software license is needed for a very small yet crucial part of the application. I have dealt with this in the past by cleverly using trial versions of software in potentially unethical ways just trying to delay or prevent purchasing the license. What creative ways do smart software engineers work around this problem when the money to invest would be hard to acquire without breaking laws or stealing? **UPDATE:** To give some context of a situation where free or open source isn't available, you have a signature pad peripheral device that comes with an integration plugin to Adobe Acrobat Professional. To use this device properly a PDF needs to be created with Acrobat and its accompanying plugin. The trial works fine for creating the PDF but what happens if the customer wants to modify the PDF a year from now? You basically just punted that problem down the road.


Can I use aac in an commercial app for free?

I was wondering if I can use the aac codec in my commercial app for free (through lgpl ffmpeg). It says on the wiki: > No licenses or payments are required to be able to stream or distribute > content in AAC format.[36] This reason alone makes AAC a much more > attractive format to distribute content than MP3, particularly for streaming > content (such as Internet radio). However, a patent license is required for > all manufacturers or developers of AAC codecs.> For this reason free and > open source software implementations such as FFmpeg and FAAC may be > distributed in source form only, in order to avoid patent infringement. (See > below under Products that support AAC, Software.) But the xSplit program had to cancel the AAC for free members because they have to pay royalties per person. Is this true (that you have to pay per each person that uses aac)? If you do have to pay, which company do you pay to and how does one apply?


Question regarding approach to programming and testing

I have read somewhere that the cost of resolving bugs increases if it is not resolved at the initial stage. My question is: Which approach should I take while creating programs:   1. Divide program development in modules. Complete coding one module. Fix ALL bugs of that module before starting coding other modules.   2. Divide program development in modules. Complete coding all modules. Then start fixing bugs in the whole program. Please let me know your experiences in which approach you found better.


More productive alone than in a team?

If I work alone, I used to be superproductive, if I want to be. Running prototypes within a day, something that you can deploy and use within a few days. Not perfect, but good enough. I also had this experience a few times when working directly with someone else. Everybody could do the whole thing, but it was more fun not to do it alone and also quicker. The right two people can take an admittedly not _too_ large project onto new levels. Now at work we have a seven person team and I do not feel nearly as productive. Not even nearly. Certain stuff needs to be checked against something else, which then needs to also take care of some new requirement, which just came in three days ago. All sorts of stuff, mostly important, but often just a technical debt from long ago or misconception or different vocabulary for the same thing or sometimes just a not too technically thought out great idea from someone who wants to have their say, and so on. Digging down the rabbit hole, I think to myself, I could do larger portions of this work faster alone (and somewhat better, too), but it's not my responsibility (someone else gets paid for that), so by design I should not care. But I do, because certain things go hand in hand (as you may experience it, when you done sideprojects on your own). I know this is something Fred Brooks has written about, but still, what's your strategy for staying as productive as you know you could be in the cubicle? Or did you quit for some related reason; and if so where did you go?


Why should I use a web framework's template language over python's templating options?

I'm coming from a python CGI background and was wanting to move into something more contemporary and think I have decided upon `web.py` as the framework I would like to use. In regards to templating, previously I used formatted strings and the `string.Template` module to effect most of my templating needs. After reading through a few of the templating options I have heard mentioned, I began wondering what the main benefits of using something like the `Django` or `jinja` templating options over "native" Python templating options were? Am I just going to be replacing `$tmpl_var` with `{{ tmpl_var }}` and `s.substitute(tmpl_var=value)` with `t.render(s)`, i.e., alternate syntax? or will I gain additional advantages from using these templating systems?


Anyone know of any parallelizing compilers following the approach of the Dragon Book?

In _Compilers: Principles, Techniques, & Tools_, Aho _et al_ describe an approach for optimizing for parallelism (chapter 11 in the second edition). Is anyone aware of any existing compilers which follow that approach?


Is rapid prototyping incompatible with software requirements specification?

From what I've learned last term on SWE courses, a big part of it is writing documents, so it seems that a software requirements specification (SRS) should earn points for my end-of-course project. However, I will be more comfortable if I use prototyping, i.e., I make a small thing that works for the most trivial of situations and gradually add up features and improvements. LVS 68:1996 doesn't seem to recommend mixing these two things together. Is it possible to still maintain my preferred approach to development, and have some usable requirement specification document?


Git, rebase and stay synced with remote branch

I have something of an annoyance in my Git workflow. I do the usual thing where I branch off master, into a branch called feature. I work on this feature branch for a while, meanwhile possibly master has commits of its own, which I might merge into feature. As I do this, I have a remote branch for feature (origin/feature) that I use so I can build and run my code on multiple machines. Now, when I finish with the feature branch, I need to push the code to our code review system. This means rebasing feature off master, and squashing all the commits into one. I do this, resolve conflicts if necessary, great. Here's the problem: feature and origin/feature now have different histories, and I'm not able to push. I tried push with -f to force it even, and this did not work either. Is there some convenient way to rebase feature off master, and keep feature and origin/feature synced? What I'm considering is doing another branch for the code review. In other words, before the rebase and squash, branch into featurecodereview. Then rebase featurecodereview off master, and if I like I can push this upstream to a new remote branch. I was wondering if there was something cleaner than opening another branch.


How to Detect Sprites in a SpriteSheet?

I'm currently writing a Sprite Sheet Unpacker such as Alferds Spritesheet Unpacker. Now, before this is sent to gamedev, this isn't necessarily about games. I would like to know how to detect a sprite within a spriitesheet, or more abstactly, a shape inside of an image. Given this sprite sheet: ![](http://www.gotoandplay.it/_articles/2006/06/beatemup/pixel_splatter.gif) I want to detect and extract all individual sprites. I've followed the algorithm detailed in Alferd's Blog Post which goes like:   1. Determine predominant color and dub it the BackgroundColor   2. Iterate over each pixel and check ColorAtXY == BackgroundColor   3. If false, we've found a sprite. Keep going right until we find a BackgroundColor again, backtrack one, go down and repeat until a BackgroundColor is reached. Create a box from location to ending location.   4. Repeat this until all sprites are boxed up.   5. Combined overlapping boxes (or within a very short distance)   6. The resulting non-overlapping boxes should contain the sprite. This implementation is fine, especially for small sprite sheets. However, I find the performance too poor for larger sprite sheets and I would like to know what algorithms or techniques can be leveraged to increase the finding of sprites. A second implementation I considered, but have not tested yet, is to find the first pixel, then use a backtracking algorithm to find every connected pixel. This should find a contiguous sprite (breaks down if the sprite is something like an explosion where particles are no longer part of the main sprite). The cool thing is that I can immediately remove a detected sprite from the sprite sheet. Any other suggestions?


Microsoft Public License vs MIT?

I'm working with a new plugin (flexbox), and I ran into the MS-PL license, which I had not run into before. In the past, I've used mainly MIT and Apache licensed projects, so I have no idea what the main differences are with this one. Here's a link to it: http://opensource.org/licenses/MS-PL Can anyone help explain the differences to me? I'm usually wary of Microsoft, so the fact that this product comes with this makes me nervous.


Using a "dead man's switch" to manage time-sensitive code

In our software environment, we often run a/b tests, as is probably good practice. However, our environment is set up such that, in very short order, the code starts to become very crufty with dead tests. The testing registry is little more than a collection of internal wiki pages. I thought of a "dead man's switch" style of defunct code management. If you're not familiar with the term, it refers to a switch that must be reset periodically in order to keep something from triggering -- in essence, if you don't responde, the switch triggers, and whatever you wanted the switch to trigger is performed. For example, I would write some code, register it with this system in some way, and when a date of my predetermined choosing rolled around, I would get a notification that this code would be removed (automatically cleaned up) unless I intervened (manually clean up, or snooze). What are the pros, cons and viability of incorporating such a system? Is it possible or wise? What might be some alternative ways to manage code against rotting?


Java or c++ for math intensive graphics application?

Lets say my friend needs to write an incredibly math heavy application. He has thought about using C++, but he wants to write it in Java. Just how slow is Java compared to C++? His application will need to solve something like a 10000 by 10000 matix per frame, so performance is important. What should I tell him? Make it in Java or C++? And why? (He really really wants to use Java, but if the application is going to run at snail speed, he's going to be extremely disappointed.)


SUN Java and GPL V2 licence issue for linked applications

I have recently noticed that the Sun Java code has been released as GPL V2 code (see Google code repo). Does that mean that all applications written in Java and linked to Sun APIs (beans, and so on) are also in GPL ? If we strictly follow the GPL then this should be the case (Libs should be in LGPL, not GPL if we want to build proprietary software on top of it). Is there another commercial licence which can avoid such an issue ? I cannot believe this is the case. There must be an explanation on this. Regards, Apple92


Is creating a full application in Silverlight advisable?

Is creating a huge public site fully in Silverlight really advisable? for eg. an ecommerce site. I don't want to start any debate but actually I feel Silverlight shouldn't be used for full website because the biggest loss you incur is of SEO. No search engines till today can parse the xap file and index it based on it's content. You can get around it by doing ifs and thens like if Silverlight is not supported then make an Asp.Net equivalent page for it but that only doubles our effort of making application, more than anything else. Why write double code in 2 applications meant for the same purpose. If that is the only option why not create Asp.Net application only. What are your views? Thanks in advance :)


ASP.NET web-application example for newbies

I want to learn ASP.NET web-application development by example. I want to learn it from an already developed web-application that is good as a tutorial for newbies. A fully functional web application that is small but powerful enough to teach newbies the development effort required for web-application development. I am looking for some application that is made using software engineering principles and not just a code written haphazardly.


Are "Compile to JavaScript" Frameworks Hostile to Continuous Integration?

Lately we've been looking at ways to improve automated testing and related tooling of our enterprise-level GWT web app. I've realized that in some ways, GWT is a bit hostile to automated testing, mainly because of the nature of the long GWT compile times from Java to JS. This makes unit testing somewhat challenging, but it also puts some roadblocks up for testing in a CI environment. I've also found out that some of our build and deployment processes are somewhat complicated due to the nature of GWT's compile process. Is this a general problem for "compile to JS" frameworks for webapps? I don't have much experience with them, but I can see some potential problems for automated testing and continuous integration and deployment. Some issues I see:   * Long build and compile times preventing quick deployments   * Language the app is developed in != JS, preventing good unit testing   * Obfuscated JS in the actual app makes it more like a executable than a web app Are these issues present in other similar frameworks, or is this more a GWT issue?


High-level description of how experimental C++ features are developed?

Herb Sutter in a video answers a question about the concepts proposal considered for C++11 and from his remarks it sounds like multiple groups offered prototype implementations but all of them left concerns about slow compile times. The comment surprised me because it suggests that, at least in some cases, the prototypes being developed are not just proofs of concept -- they're even expected to perform. All the work that must take has me curious. For mature languages, especially C++, how are experimental language features developed? Is it much different from developing a compiler that implements a standard? Does a developer have a sense of if it will work and perform or even if it ever could? What are the most time consuming parts and are any parts surprisingly easier than one might expect? The question is not what does the C++ standards committee do, but rather the part that comes before. When an experimental implementation for a proposal is being put together and there aren't any completely solidified rules, how is the sausage made? I'm not a professional compiler developer nor do I expect answers with step by step accounts. I'd like a high-level idea of how this would be done or if there are any general patterns at all. I don't know what to expect from the answers but even if there are no rules to the process and the small number of people who do this just cowboy it and then, for stuff that worked out, write up the "official version" as a proposal, that answer would still be informative.


Is ATL a deprecated language?

I currently developing some M2M-transformations with the Atlas Transformation Language (ATL). During studying the language constructs and properties I have often read, that ATL is a prototype for QVT, but was not used for QVT. This leads me to the question, if ATL is a deprecated language. Personally, I claim that ATL is not deprecated because there are some indications for this:   1. If I look at the website of ATL the last Update was August, 26th 2011. The first specification of QVT was 2008. So I think the development of ATL seems to proceed.   2. There are also some papers since 2011 on google scholar: http://scholar.google.de/scholar?q=atl+m2m&btnG=&hl=de&as_sdt=0&as_ylo=2011   3. It is still part of the M2M-frameworks of Eclipse What would you say? Would it be better to user another M2M language or is ATL future proof? If not, do you know possibilities to transform ATL into other M2M-languages?


Load Balancer impact on web development

This question has it's roots in a SharePoint site that I am help with. ### Background on the issue I dealt with: The dev box and integration server are not setup behind a load balancer. The links were being built using the HttpRequest.Url value from the current context. Note that the links weren't relative links but full URIs. Once we deployed to testing (which has a LB, amongst other things) we received errors on the links being built since the server had an address of "http://some.site.org:999" while the address at the LB as "https://site.org" (SSL was off-loaded at the LB). The fix was easy enough by using relative URIs. ### The Question: Since this is the first site I've worked with that's behind a Load Balancer on I'm wondering if there are other gotcha's that I need to consider when developing a site behind one?


Caching large amount of ajax returned objects

I'm building an application which fetches large amount of items with ajax requests via other application API. It returns me 6k - 30k js objects which are used multiple times across various application views (sorting, filtering etc.). I would like to avoid querying API every time for such big list so I decided to cache this data somehow. I was thinking about various solutions:   * saving it to localstorage,   * using some caching library (e.g. locachejs),   * storing in js var. I'm not an expert so I would like to hear Your suggestions about each (or one of these) solution, about its pros and cons. Every help will be very appreciated.


event source calls methods in a interface

I am using Java. How does an event source like a (button in a GUI) knows which method to call in an interface? For example, I am listening to Mouse Events and have implemented a Mouse Listener interface in my class then how would the event source know whether it should call `mousePressed()`, `mouseReleased()` or some other abstract method in the in the interface? I am aware that using `addMouseListener(this)`, provides a way for the event source to call the method of an interface.


Learning Python is good?

> **Possible Duplicate:**   >  Is Python worth learning? Is it a useful tool? Recently I have seen some videos from MIT on computer programming topics. I found it's really worth watching. Especially the concepts of algorithms and fundamental stuffs. The programs were written and explained in Python. I never had looked into this language before as I learned and doing stuffs with C/C++ programming. But the cleanliness and better readability of syntax attracted me. Of course as a C++ programmer for long time it's the most readable language for me. Also I heard Python library contains solid algorithms and data-structures implementations. Can you share your experience in this language?


Why do so many libraries have no/poor documentation?

In a similar vein as the Why do many open source projects have no documentation about their design or architecture? question, I'm curious: Why are so many libraries so lacking in end user documentation? My view is this:   1. Most everyone agrees that reading source code is more difficult than writing source code.   2. Without documentation, one must read the library's source code in order to use that library.   3. Therefore, using the undocumented library is more work than just recreating the library from scratch.   4. As a result, if you want to have people use your library, you'd damn well better make sure it's documented. I know lots of developers don't like writing docs, and I'll agree it can be tedious work. But it's essential work. I'd even say it's more important that a library have good documentation than have the best programmer's interface in the world. (People use shitty libraries all the time; few use undocumented libraries) Oh, note that when I say documentation, I mean real documentation. Not Sandcastle/Javadoc/Doxygen boilerplate.


Consequences of not using an open source license?

Lets say you don't use a license for your open source project. And you don't put anything about a license anywhere in the code..is this okay to do?


Enforcement of returning non-null

We are implementing some web services, and need to ensure that some of our methods **always** return non-null values. We've investigated two ways of doing this:   * Using code contracts, and returning the default value using `Ensures` constraints on the return value.   * Using an aspect-oriented programming approach using PostSharp. Both approaches work, but I'm wondering whether there are any other approaches that we should consider. How would you enforce non-null return values? * * * Looks like there was a similar question on SO, and Jon Skeet recommends the Code Contract approach.


Should you bring up commercial projects in an interview?

I am not sure if it's a good idea or not to mention commercial software projects. Right now, I have one desktop software site selling (not enough to support myself yet) and I am not sure what is a good way to use it as a way to convey my skills and experience? Speaking of experience, I've never had a developer job. I've worked by myself developing applications with intention to sell, and one one hand I feel like if I mention this, I might come across as someone who is not serious about getting a developer job, which is not true, my mind is set on getting a developer job. Should I say I gave up the project to look for a job? Or does this appear weak? I just don't know how to tie up my involvement in self started software projects in an interview situation in a relevant manner.


Implementing a machine learning algorithm to detect the region of an address

I have 10,000 addresses from a city, which all have a region field in the database. When a new address is entered, then I want my software to automatically detect the region of the address . I think it should be implemented with some sort of machine learning algorithm. How can I do this? And with every newly inserted address, the machine should learn to detect the region of the new address. Is there any library for machine-Learning algorithms (like aforge.net for neural networks)?


Will there be any official LINQ like lambda based library for C++?

Given C++('11) has lambdas now, will there be any LINQ like higher order function library officially supported later? Is there any such library now being used in any production level code? Obviously I'm not expecting the SQL-like expression tree based LINQ query syntax in C++. I am talking about the lambda based one. So, no new language feature in needed in C++'11, just a library will do.


Is it OK for me to suggest ready-made scripts to a programmer? If so, how can I do it without offending him/her?

Is it ok to suggest pre-built scripts from a place like codecanyon to a programmer who is building a startup web app? Or is it more likely to offend? I don't expect that a whole web app could be built from bits and bobs purchased from a site but I'm unsure of whether its the right thing to ask someone to do. Also, I am not a programmer.


How to get JMS to front end

I currently have a web application and I would like to add a messaging feature to it. In order to do that, I use JMS(actually OpenMQ, the implementation provided with Glassfish 3). The problem is that I do not know how to get the message notification from the background(from the listener) to the foreground. I am using JSF as a framework, if it does have an importance. Could you please tell me how should I notify the user about a received message(like a chat). Any suggestions are welcomed.


Rendezvous in Ada

In a test I was asked: > What elements present in the general form of a rendezvous are not present in > Ada language? I was a bit stumbled as I thought Ada fully supported rendezvous. Now it seems it doesn't. Can anyone tell me what are those elements?


What are the reasons for great performance differences running the same program?

I'm no computer scientist so please bear with me. Lately I wrote a python program that has to perform some expensive spatial searches while holding lot's of data in memory. I tried to improve the performance, that is tried different approaches (see my question here for example). First, and maybe not so surprisingly, I found great performance differences when running the same code on two different machines (up to 6 x faster on one machine). Then however and very much to my own surprise, running the exactly same code on the same machine on two different days showed great performance differences. To give you a rough idea what I mean by great. Machine 1, day 1: 11 minutes Machine 1, day 2: 2 minutes There was no reboot in the meantime by the way. So my question really is: what could be possible reasons for this difference? How can I can I make sure my system is ready for high performance when I start running my program?


Keeping third-party source code up to date

What is the best way to keep third-party source code up to date? For instance in my app, I'm using third-party source code from an open GitHub repository. What I've done is that I have downloaded the zip of the source code, unpacked it and imported it in my iOS app and then started modifying this source code to my hearts content. So this third-party source code has been working great for me, but now some months later the developer of the third-party source code released an update to his code from `1.0 -> 2.0`. Now of course I want to have this update as well in my iOS app. What would be the easiest way to migrate my `1.0` third- party source code (together with all my additions to the code) to `2.0`?


Product agnostic book on Message Queues?

Are there any recommendations for book(s) that are largely agnostic (with examples of MQ implementations is fine) on vendor but go to great details on the architecture, management, nomenclature, atomicity, durability, patterns, and logical deployments on Message Queue systems? Surely there are enough shared concepts between MQ Series, MSMQ, SysV IPC (OK, that might be stretching it), RabbitMQ, &c &c?


Algorithms for making image mosaics - is there a quicker way than this?

I've been playing with making image mosaics. My script takes a large number of images, scales them down to thumbnail size and then uses them as tiles to approximate a target image. The approach is actually quite pleasing: ![](http://i.stack.imgur.com/RZKkTm.jpg) I compute the mean square error for every thumb in every tile position. At first I just used a greedy placement: put the thumb with the least error on the tile it best fits, and then the next and so on. The problem with greedy is that it leaves you eventually placing the most different thumbs on the least popular tiles, whether they match closely or not. I show examples here: http://williamedwardscoder.tumblr.com/post/84505278488/making-image-mosaics So I then do random swaps until the script is interrupted. The results are quite OK. A random swap of two tiles is not always an improvement, but sometimes a rotation of three or more tiles results in a global improvement i.e. `A <-> B` may not improve, but `A -> B -> C -> A``1` may.. For this reason, after picking two random tiles and discovering they do not improve, I pick a bunch of tiles to evaluate if they can be the third tile in such a rotation. I do not explore if any set of four tiles can be profitably rotated, and so on; that'd be super-expensive real soon. But this takes time.. A lot of time! Is there a better and faster approach? * * * **_Bounty Update_** I tested out various Python implementations and bindings of the Hungarian Method. By far the fastest was the pure-Python https://github.com/xtof- durr/makeSimple/blob/master/Munkres/kuhnMunkres.py My hunch is that this approximates the optimal answer; when run on a test image, all other libraries agreed on the result but this kuhnMunkres.py, whilst being orders of magnitude faster, only got very very very close to the score the other implementations agreed on. Speed is very data-dependent; Mona Lisa rushed through kuhnMunkres.py in 13 minutes, but the Scarlet Chested Parakeet took 16 minutes. Results were much the same as random swaps and rotations for the Parakeet: ![enter image description here](http://i.stack.imgur.com/ZW8uh.jpg)![enter image description here](http://i.stack.imgur.com/RZKkTm.jpg) (kuhnMunkres.py on the left, random swaps on the right; original image for comparision) However, for the Mona Lisa image I tested with, the results were noticeably improved and she actually had her defined 'smile' shining through: ![enter image description here](http://i.stack.imgur.com/u4muy.jpg)![enter image description here](http://i.stack.imgur.com/2fI3G.jpg) (kuhnMunkres.py on the left, random swaps on the right)


Are there elements common to nearly every SRS?

An SRS is a staple of any serious contract work, and it can be _incredibly_ dull for those who've never had the misfortune of needing to read one through in one go. I'm writing a series of document classes with LaTeX (markup language for profession-quality documents; see these questions and this answer on TeX.SE) and, in so doing, I need to define the core tenets and common logical structures evident through any reasonable SRS. I have unfortunately never had the opportunity to participate in the creation of an SRS from scratch save a simplified, somewhat contrived example during college, so I don't think I know the breadth of what goes into a Software Requirements Specification (SRS). I do know it consists of at least the changelog and the requirements themselves, but beyond that... ? What are the indispensable parts of the document that every SRS should have? * * * I'm still pretty new here, but I'm open to making this CW if Programmers.SE is _all about_ this kind of stuff.


License Requirements for Including Dual-Licensed Open-Source Software

How do you opt into one software license and not the other when the distributor gives the consumer more than one choice? For example I would like to use the DataTables JavaScript library in my web application. According to their web site, "DataTables is dual licensed under the GPL v2 license or a BSD (3-point) license." Furthermore, the source code of the JavaScript library has this text **that calls out both licenses:**               /**      * @summary     DataTables      * @description Paginate, search and sort HTML tables      * @version     1.9.4      * @file        jquery.dataTables.js      * @author      Allan Jardine (www.sprymedia.co.uk)      * @contact     www.sprymedia.co.uk/contact      *      * @copyright Copyright 2008-2012 Allan Jardine, all rights reserved.      *      * This source file is free software, under either the GPL v2 license or a      * BSD style license, available at:      *   http://datatables.net/license_gpl2      *   http://datatables.net/license_bsd      *       * This source file is distributed in the hope that it will be useful, but       * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY       * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.      *       * For details please refer to: http://www.datatables.net      */      Finally, the web pages with the licensing text (e.g. the DataTables BSD license page) has this statement: "DataTables is made available under both the GPL v2 license and a BSD (3-point) style license. **You can select which one you wish to use** the DataTables code under." My specific question is "how do you select which one you want to use." In my case, I want to only use the BSD license and I want to make it explicitly clear that I do not opt into the GPL v2 license in any way. How do you do that **and have it hold up to legal challenge?**


Design pattern for complex view creation in sheet music

I've got a bunch of `Note`-Models with properties like `pitch`and `duration`. In music notation, these notes must now be placed into a certain bar on a certain line on a certain page, and so on. Many more factors influence the positioning of these notes like the notes that are placed in the same bar before them. Also, style-properties influence many different view-elements. The positioning of notes is affected by the "line-height" of the music lines, whether the bar is justified to the width of the page or not, and so on. **I'm looking for a design pattern that can help me cleanly position all these views relative to each other.** Can anybody help me out? I'm using SVG with JavaScript for my current project, if this is important. Thank you so much for helping out! :)


Executables and Python

I've started learning my first language recently, Python, and I became interested in how it differed from the myriad of other programming languages. I've been able to find most of it out with some searching: There is interpreted, compiled and assembly language. Then there is numerical machine code (which as I understand is just binary?) that is read by hardware directly. So Python is an interpreted language because it isn't explicitly compiled to machine code (although from what I understand this is a false distinction since most code is both compiled and interpreted, if only behind the scenes). I still have one question I couldn't figure out how to search an answer for. I assume Python code requires the Python platform to be read because it contains the interpreter. But how do you get those "standalone" .exe programs which you can run on most computers? Are those files just using a platform which every computer has by default, or are these files that are already compiled completely to machine code? (Like with C++?) The main reason I'm wondering this is that I was wanting to send someone my simple Python programs without having them install the platform. I've searched online and found some 'compilers?' that will do this, but they don't seem to work very well and are very difficult to work with.


Must all new features go through betatest?

Obviously, small usability fixes and bugfixes go directly into the stable product. What about small new features? Can you afford to just release them after internal testing, or do they have to be betatested by customers first? Situation: This is a young commercial project, produced by a one-person company. It has an existing userbase and is at it's second major version. Previous betatests have produced some results, however most feedback came from the stable product and not from beta versions.


Which license can I use for my open source AWS project

I'm creating a project on codeplex that uses Amazon Web Services and the AWS SDK for .NET Which licenses can I use? The SDK is released under Apache 2.0 license, so I assume my project can or should use the same. If I add another open source library released under a different license, do I need to find a license that is 'compatible' with both ie. one that has the same requirements for derivative works? * * * My requirement is for a license that allows me to publish a derivative work from the AWS .NET SDK. I can use any of the licenses that codeplex supports, which includes:   * Apache 2.0    * GNU GPLv2    * MIT    * Mozilla Public License 2.0    * Microsoft Public License


Creating an entity relationship in REST: May I create the parent by posting to a child id?

We are currently designing a REST API to access classical customer data. One of the elements in the API are the assets of an user. The assets are added under a given service. The backend API will only add an asset to an user under a given service. So, there's no User--Asset relation, but a User--[Service]--Asset relationship. Our URI's will look like this:               /users/{id}/assets/{id}/services/{id}      Uses of the API will know the asset id and the service id to create a new entry. What we are struggling with is the creation of this relation. One straightforward way would be to post the whole relation to `/users/{id}/assets/`               POST /users/{id}/assets         {asset:${id}, service:{id}, attribute1:"{var}", attribute2:"{var}"}      but then we are not actually creating an asset as the URI might indicate, but an asset-service relation. As an alternative, we are considering POST'ing to the URI addressing the relation, like this:               POST /users/{id}/assets/{id}/service/{id}     {attribute1:"{var}", attribute2:"{var}"}      But in this case, the resource path `/users/{id}/assets/{id}` will not exist before the POST and will be created as a side-effect. Is POST'ing to a resource path that does not exist yet allowed at all? Thanks for your thoughts, Gerard.


Sproc chaining verse discrete calls from OO code

I'm currently working on a change at work to generalize a function that was sloppily coded up to work for a particular use case. The function calls a particular sproc that checks if an entity exists and if it does not inserts it, this is the core problem. In discussion about the change with a co-worker we both agreed this should be more modular (you need to be able to get without inserting), however I stated a preference to have two individual sprocs which are discretely invoked in our C# code. He claimed it's superior to have one sproc call the other but wasn't actually able to provide me a convincing argument for why that practice would be better (other than making a the generalized claim that it performs better, to which I said there is much lower hanging fruit for performance optimizations). Which practice do you believe to be better? Why?


Do you unit-test your PODs?

do you create unit-tests for PODs (Plain Old Data Structure)? And why? I'm interested in your opinions. Regards Tobias


What is the Most Expedient Way to Make Legacy Code Conform to 'The Principle of Proximity'?

On page 242 of Code Complete 2, Steve McConnell touts **The Principle of Proximity**.   Put simply, Mr. McConnell advises programmers to **keep related actions together**. In my case, the applicable emphasis is:   * It's important to initialize and set variables (and objects) close to where they are being used. It's usually easy to abide by 'The Principle of Proximity' when you're working within a single code block or method body; but what if you're working with legacy code and an object at the top of the stack is set or mutated deep within the stack? To make things more complicated, what if that object is set, mutated, or referenced _multiple times_ within the stack? So here's my question: > What is the Most Expedient Way to Make Legacy Code Conform to 'The Principle > of Proximity'? Incidentally, I'm working with Visual Studio 2010 and Resharper 5.   Are there any IDE tricks that could help me out?


Javascript project for analysis and learning

I started learning and using Javascript now for about six months. First i started by following different tutorial on the internet. Testing them, playing with them and trying different variation. Afterwards i picked up up a couple of intermediate Javascript book and learned valuable thing from them. And now i am interested in the following:   * If someone can recommend a Javascript project from where i can learn the structure of a serious Javascript application and a project that will give me an a idea how Javascript application should be written.   * Example:realworld uses of prototyping, anonymous(lambda) functions, general program structure, how to write OO applications, what is the appropriate task to use a closure   * etc.. Further explanation: I'm working on my college final paper, on the subject of graph visualization. So im looking at project that will help me realize good patterns, so i can apply them in my project and also to see viable examples of Javascript design patterns Regards, FJ


Why is Javascript used in MongoDB and CouchDB instead of other languages such as Java, C++?

I asked this question on SO but was suggested to try here. So here it goes: My understanding of Javascript so far has been that it is a client-side language that capture events and makes a web-page dynamic. But on reading the comparison between MongoDB and CouchDB I noticed that both are using Javascript. This makes me wonder the reason behind the choice of JavaScript over other conventional languages. I guess I am trying to understand the role of JavaScript and its advantages over other languages. Update: I am not asking about the languages / drivers supported by the two databases. The comparison says: > Both CouchDB and MongoDB make use of Javascript. CouchDB uses Javascript > extensively including in the building of views. > > MongoDB also supports running arbitrary javascript functions server-side and > uses javascript for map/reduce operations. My lack of understanding pertains to why is Javascript being used at all for the backend work. Why is it preferred for building views in CouchDB, or for using map/reduce operations? Why C/C++ or Java were not used? What are the advantages in using Javascript for such back-end work?


Why are a seemingly disproportionate amount of programmers just, well, not nice?

Maybe it's just my personal experience, but I associate with varying different groups and types of people and it seems to me that an oddly large percentage of programmers I have encountered are "not nice" or for an attempt at a better definition:   * Condescending    * Snarky   * Negative in the way they talk about people If you have noticed the same thing, any theories as to why? Any suggestions on how to politely or not so politely let one of these programmers know how they are acting and suggest they correct it if they want to be perceived as professional one would want to work with? Or perhaps I've just come across a bad sample and there are bad seeds in every group of people one can name.


Learning a new language using broken unit tests

I was listening to a dot net rocks the other day where they mentioned, almost in passing, a really intriguing tool for learning new languages -- I think they were specifically talking about F#. It's a solution you open up and there are a bunch of broken unit tests. Fixing them walks you through the steps of learning the language. I want to check it out, but I was driving in my car and I have no idea what the name of the project is or which dot net rocks episode it was. Google hasn't helped much. Any idea?


How does a dependently typed programming language cope with mutability?

I have been investigating on the viability of a "normal" programming language with dependent types. Think for example in Java and add dependent types to it. One difficulty which I have found is that the type of a variable may change when mutated, like in the following piece of pseudo-code:               let xs = [1, 2, 3]; // The type of xs is List<int, 3>     let ys = [4, 5];    // The type of ys is List<int, 2>     xs.concat(ys);      // We concatenate the lists, so the type of xs is now List<int, 5>      This becomes a problem when we mutate a variable inside an `if` statement:               let xs = [1, 2, 3]; // The type of xs is List<int, 3>     if random_bool {         xs.push(4);     // The type of xs is List<int, 4>     }     // The type of xs is unknown, because random_bool is set at runtime      Is there any research on this topic? Is it possible to address this issue without renouncing to mutability?


Intersection of geometric entities

I was trying to design a small C++ geometric API for learning purposes, but came across a problem when dealing with intersections of geometric entities. For example, the intersection of a line and a sphere can have three different types: a couple of points, a point or nothing at all. I found several ways to deal with this problem, but I don't know which of them seems to be the best: ## CGAL `Object` return type I first tried to see what was done in other geometric libraries. The most complete I can found was CGAL. In CGAL, intersection functions return an `Object` which is a generic type that can hold anything (like `boost::any`). Then, you try to assign the `Object` to a value of another type, here is an example:               void foo(CGAL::Segment_2<Kernel> seg, CGAL::Line_2<Kernel> line)     {         CGAL::Object result;         CGAL::Point_2<Kernel> ipoint;         CGAL::Segment_2<Kernel> iseg;              result = CGAL::intersection(seg, line);         if (CGAL::assign(ipoint, result)) {                  // handle the point intersection case.              } else if (CGAL::assign(iseg, result)) {                  // handle the segment intersection case.              } else {                 // handle the no intersection case.         }     }      By the way, the `assign` function uses `dynamic_cast` to check whether the two variables are assignable (everybody loves RTTI). ## Union return type A union can also be used as a return type, but it means using an `id` for every geometric type and having some kind of variant type to cover all the problems.               struct Variant     {         int id;         union         {             Point point;             std::pair<Point, Point> pair;         };     };          int main()     {         Point point;         std::pair<Point, Point> pair;              Variant v = intersection(Line{}, Sphere{});         if (v.id == ID_POINT)         {             point = v.point;             // Do something with point         }         else if (v.id == ID_VARIANT)         {             pair = v.pair;             // Do something with pair         }         else         {             // No intersection         }     }      ## Avoiding the "no intersection" problem In order to split the "no intersection" case from the main problem, some libraries used to require the user to check whether there was an intersection before trying to find what was the intersection return type. It looked like this:               Line line;     Sphere sphere;          if (intersects(line, sphere))     {         auto ret = intersection(line, sphere);         // Do something with ret     }      Another way to split the "no intersection" case from the rest of the problem would be to use an `optional` type:               std::optional<...> ret = intersection(Line{}, Sphere{});     if (ret)     {         // Do something with ret     }      ## Using exceptions to control the "return" type _I can already see some of you crying._ Yet another way to handle that problem of having different return types would be to `throw` the results instead of returning them. The "no intersection" return could still use one of the techniques from the previous paragraph:               try     {         intersection(Line{}, Sphere{});     }     catch (const Point& point)     {         // Do something with point     }     catch (const std::pair<Point, Point>& pair)     {         // Do something with pair     }     // Can still catch errors (or "no intersection" special type?)      ## Having a "main" return type, throwing the other ones Another way would be to have a "main" return type for the intersection, let's say `std::pair<Point, Point>` and considering the other return types as "exceptional"; it gives more meaning to the use of exceptions while this is still not quite an error gestion. On the other hand, it could seem strange to handle a "main" type differently than the others...               try     {         auto pair = intersection(Line{}, Sphere{});         // Do something with pair     }     catch (const Point& point)     {         // The chances for a sphere and a line to meet at         // a single point are so small that the case can         // already be considered exceptional.         // ...     }      I purposedly left the errors gestion and the "no intersection" case out of this last example since many techniques already described could be used to handle it and I don't want the number of examples to be exponential. Here is one though:               try     {         // res is optional<pair<Point, Point>>         if (auto res = intersection(Line{}, Sphere{}))         {             std::cout << "intersection: two points" << '\n'                       << std::get<0>(*res).x() << " "                       << std::get<0>(*res).y() << '\n'                       << std::get<1>(*res).x() << " "                       << std::get<1>(*res).y() << '\n';         }         else         {             std::cout << "no intersection" << '\n';         }     }     catch (const Point& point)     {         // Exceptional case         std::cout << "intersection: one point" << '\n'                   << point.x() << " "                   << point.y() << '\n';     }      Since the cases where the result is thrown are exceptional, it should not add any runtime overhead to the program if the underlying system uses zero cost exceptions instead of the old SJLJ exceptions system. ## The actual question Well, that was a pretty long introduction, so here is the question: is there an idiomatic solution to the problem in these examples? And if not, are there at least some of the examples which could be banned without a second thought (well, you could give a second thought to the exception examples though...)? **Note:** something seemed evident to me but apparently is not: the entity returned by intersection between two geometric entities is not limited to a nothing, a point or a set of point. An intersection can pretty much return any geometric entity. Therefore, using a container to hold the values does not sound like a good idea.


Which database schema should I pick?

I am planning a database scheme and I hesitate between two designs, which one should I choose? For the purpose of the question, assume we want to prepare a database scheme for an application managing student information in a university. There is several modules in the application:   * **Registry,** dealing with general informations, like date of birth, health insurance number, and the like.   * **Library,** dealing with the properties useful to the library management, like the number of books withdrawn, quitus or penalties.   * **Exams,** dealing with the exams taken and the grades. The modules Library and Exams see the modules Registry, but apart from that, are independant. In the application scenario, there is a very large number of students, data is written once, seldom updated and often read. Furthermore, the university expands its system each year, so that modules are added: Sport, Campus, whatever. Modules remain quite independant. I hesitate between two database layouts. ### First layout In the first layout, a table `MODULE` is associated to each Module and a `UID` is used as primary key. Since each module needs the properties under control of Registry, we also prepare views of the join of `REGISTRY` and `MODULE` on `UID`, so that the database knows we will use this join extensively. When the system expands, we add a new table and a new view to reflect this expansion. ### Second layout In the second layout, we create a table with a large number of columns holding the properties of the various modules. When the system expands, we add columns to the tables. ### Comparison How does these two approaches compare? If, say, some software upgrade comes with a major bug, requiring to downgrade the software and perform later a second upgrade, the first layout seems to be more robust. Regarding perfomance, the second layout saves a lot of join operations, but in the first layout, we defined views for the join operations, thus advertising which complex operations are likely to happen so that the database system can plan this. I am far from a database expert, but am I right if I think that if I put all relevant information into the hands of the database system, it will be able to properly carry operation? If I did not see it used in industrial applications, I would never had given 2 pences on the second layout. But since I did, I would like to get other advises.


Why do generics in Scala have erased types, and are not reifiable? Is it due to lack of support from the JVM or for compatibility with Java libraries? What are the advantages in general of having generics as reifiable?


Generics and Type-erasure

Generics in Java are implemented using type erasure. The JLS says that the inspiration was backward compatibility. Where as on the other hand C# generics are reifiable. Theoretically what are the advantages and disadvantages by having Generics as "erasure" or "reifiable"? Is Java missing onto something?


Is it good practice declare a function inline?

I'm writing a method and depending on a config field I need to change where I get my data from. What this results in me having to write code that looks like this:               List<string> result = new List<string>();     if (configField)     {         result.Add(fieldA);     }     else     {         result.Add(...BusinessLogic...);     }      I'll have to write that if statement many many times so of course I want to turn it into a method instead so I can just write `result.Add(newMethod(configField, fieldA, dataForBusinessLogicToParse))`. This method would be useless to anyone not writing the specific method I'm writing so does it make sense to declare this method as a separate `private` method or can I just declare it inline as a `delegate` like this:               Func<Enum, int, int> newMethod = (configField, fieldA, dataForBusinessLogicToParse) => ...businessLogic...      I'm worried declaring it inline might make the code more difficult to understand but I think it makes the class cleaner.