Where to validate domain model rules that depend on database content?

I'm working on a system that allows Administrators to define Forms that contain Fields. The defined Forms are then used to enter data to the system. Sometimes the Forms are filled by a human via a GUI, sometimes the Form is filled based on values reported by another system. For each Field, the Administrator can define a Validation Rule that limits the allowed values for the Field. The Validation Rules can be anything from "the value entered in the Field must be True or False" to "the value entered in the Field must exist in column A of table B in the database". The Administrator may at any time change the Validation Rule for the Field. In this scenario, what in your opinion is the most suitable place for validating that each Field is filled correctly? I currently have two main approaches in mind: **Option #1: Validate in the Domain Model** Each Field object would contain the Validation Rule specified by the Administrator. The Field objects would also have a reference to an IValidator. When an attempt is made to set the value of the Field, the Field would pass the given value and the Validation Rule to the IValidator. If the given value is not valid, a ValidationException would be thrown and appropriately handled in the GUI/interface to the other system. _Pros:_   * Strong protection against Fields being accidentally assigned values that violate the Validation Rule _Cons:_   * The Data Access Layer needs to be able to bypass the validation and construct Fields that violate the current Validation Rule. Despite the Administrator changing the Validation Rule for a Field, we still need to be able to construct Field objects based on the old data e.g. when rendering a Form that was filled years ago. This could potentially be resolved by storing the current Validation Rule whenever we store the Field.   * In this design, the Field model has an indirect link to the Data Access Layer/Repository via the IValidator. The injection of Services/Repositories to Domain Models seems to be generally frowned upon. **Option #2: Validate in a Service** Try to ensure that all attempts to set the value of a Field pass through a Service that ensures the Validation Rule holds. If the Validation Rule is violated, throw a ValidationException. Of course, the Data Access Layer would **not** use the Service when creating Field objects that have previously been persisted in the DB. _Pros:_   * Does not violate the "don't inject Services/Repositories into your Domain Models"-thinking.   * No need to persist the current Validation Rule when persisting the Field. The Service can simply look up the current Validation Rule for the Field; when looking at history data, the value of the Field will not be changed. _Cons:_   * No guarantee that all logic that should use the Service to set the Field value actually does so. I see this as a major drawback; all it seems to take is someone writing "thisField.setValue(thatField.getValue())" and the Validation Rule of thisField might be violated without anyone being the wiser. This could potentially be mitigated by ensuring that the value of the Field matches with the Validation Rule when the Data Access Layer is about to persist the Field. I currently prefer Option #1 over Option #2, mainly because I see this as business logic and feel that Option #2 poses a greater risk of introducing bad data to the system. Which option do you prefer, or is there another design that fits this scenario better than the two options described? **Edit (Complexity of validations)** The validation cases that have come up for now are relatively simple; the Field value must be e.g. numeric, a date, a date with a time or be an existing value in a database column. However, I suspect complexity to gradually increase over time. For example, the validation solution needs to be built with internationalization in mind - things such as Dates may be input in a locale-specific syntax. I've decided to proceed with Option #1 for now, attempting to take care not to assign too many responsibilities to the Domain Model. Those facing a similar situation may also want to check out the related questions Validation and authorization in layered architecture and Data input validation - Where? How much?.


Why use a database instead of just saving your data to disk?

Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all. Why should one use a database instead of just saving the data to disk?


Client Server .NET application with queuing message

I am new, so forgive me if my question is mistaken or anything, just give me an alert and I'll be glad to fix it. Me and my team is about to develop a system where the database is located in a private server, and the applications is distributed between clients on distant location. It is actually a simple CRUD application, but our primary concern is how poor the internet connection on some remote clients. I thought to give a try to WCF queue message so that when the connection is down, I can save the message to later send it again when it is up, but I don't have a real clear solution in mind. Currently, my solution would be something like this : > **CLIENT** > > **MySolution.sln** > > \-- **MyDataAccess** > > \---- Entities (Contains my object class definitions and properties) > > \---- Repositories (Handles database communication) > > \---- Services (Handles message queue to server CRUD) > > \-- **MyClassLibraries** (Contains third party's DLLs) > > \-- **MyHelper** (Contains helper classes and functions) > > \-- **MyCore** (Main application project) > > \---- Model > > \---- View > > \---- ViewModel and for the server : > **SERVER** > > \-- **MyBackgroundService** (Responsible for fetching incoming message and > doing CRUD to database) Is there a better solution to this? I am not good enough yet to see it. Please let me know if I violate some rules here. Cheers !


How to store weekly-occuring time spans in Java objects

My school programming club is setting up a tutoring program. We have 12 tutors who specialize in a range of different languages, and each is available for a different set of hours each day of the week. I want to set up a web interface where students can select the language they need help in, and then be shown a list of the time spans each day that there is a tutor in that language available to help them. My main question at this point is how I should go about storing tutor availability data - should I use a database (and if so, how), or should I simply store availabilities as fields in POJO "Tutor" objects. If the latter would be best, what data-type should I use? Can I get by simply storing them as strings or should I use joda or java.util Date objects? The task that seems particularly tricky to me at this point is combining availabilities of multiple tutors into a single time-span for each day - i.e., if I have one tutor available from 10-2 and one available from 12-4, I want a single line saying "10-4" to be presented to the user. I'm just beginning to design my approach to this task, so I'm very open to general suggestions and/or having unforeseen problems pointed out to me. I would like to use a Java JApplet as my web interface.


Services in Model Layer

I understand services should have no state and no business logic.   * How can you implement a service like AuthentificationService considering these rules?   * All the methods in a service should be static?


Is it worth moving from Microsoft tech to Linux, NodeJS & other open source frameworks to save money for a start-up?

I am currently getting involved in a startup, I am the only developer involved at the moment, and the other guys are leaving all the tech decisions up to me at the moment. For my day job I work at a software house that uses Microsoft tech on a day to day basis, we utilise .NET, SqlServer, Windows Server etc. However, I realise that as a startup we need to keep costs down, and after having a brief look at the cost of hosting for Windows I was shocked to see some of the prices for a dedicated server. The cheapest I found was £100 a month. Also if the business needs to scale in the future and we end up needing multiple servers, we could end up shelling out £10's of £000's a year in SQL Server / Windows Server licenses etc. I then had a quick look at the price of Linux hosting for a dedicated server and saw the price was waaaaaay lower than windows hosting. One place was offering a machine with 2 cores for less than £20 a month. This got me thinking maybe the way to go is open source on Linux. As I write a lot of Javascript at work (I'm working on a single page backbone app at the moment), I thought maybe NodeJS and a web framework like Express would be cool to use. I then thought that instead of using SQL why not use an open source NoSQL database like MongoDB, which has great support on NodeJS? My only concern is that some of the work the application is going to do is going to be dynamically building images and various other image related stuff, i.e. stuff that is quite CPU heavy - so I'm thinking of maybe writing anything CPU heavy in C++ and consuming it as a module in Node. That's the background - but basically is Linux a good match for:   1. Hosting a NodeJS/Express site?   2. Compiling C++ node modules?   3. Using a NoSQL DB like MongoDB? And is it a good idea to move to these unfamiliar technologies to save money? * * * ## 3 MONTH UPDATE I've been working on this for the past few months now so thought I would give an update in case anyone is interested. In the end I decided against using a NodeJS & Linux stack for the simple reason of time. I am doing this startup on the side, so I am working 9 hour days, then going home and working until late on the startup. While working in this way I obviously need to be as efficient with my time as possible, or I will never end up shipping the product. After taking some of the advice on this thread I did apply for Microsoft BizSpark, and was accepted. This means I now have access to Visual Studio license, Windows Server license etc, all for free. Which is awesome. Hopefully by the time we are required to begin paying for everything we will be turning over enough that will make it a non-issue. Do not think I am only using Microsoft tech, however, as I have tried to use open source stuff where possible. The main place I have done this is my data layer, where I have decided to use PostgreSQL and MongoDB. I am also using BackboneJS on my front end. Below is a summary of the tech/frameworks I am currently using:   * Standard DB stuff: PostreSQL   * Logging & Data Store: MongoDB   * ORM: Entity Framework 5   * Core libraries: .NET (C#)   * Web Framework: ASP.NET MVC3   * UI: Razor view engine / BackboneJS


Inserting copyright notice

What is the easiest way to insert copyright notice in lots of PHP files.   It's not possible to do it manually.


Which skills would you look for in an offshore junior developer?

Suppose you have to interview a developer for a (not senior) developer position. The catch is that the developer is not from your country and your company would have to invest some money and time to bring him to your country. You have to make the interview. What skills would you look for in such a candidate? **For the sake of context** , suppose it is a position of a web developer or desktop developer. Thanks in advance **EDIT** : This question is related to the _developer_ point of view, so in this case, the answers should be oriented to help the developer in which to expect...


How should I go about learning PHP given a background in C#.NET?

I have developed a few websites and applications using C#, and lately I've been developing a website in ASP.NET MVC. To be honest, this has pissed me off somewhat as it has me feeling like I have zero knowledge. So many things work under the hood in .NET that I'm just not able to focus and understand what is left to the developer and how these things are done. Now, the question that prompted me to make this post is: **How should I proceed for learning PHP from a very basic standpoint?** Mind you, I have no idea about this language at all, just seen some code and heard people talking.


Refactor class (extract methods) in a main / helper classes

Simply spoken, one of my c# classes got too big and I'm currently splitting this class in several subclasses by clustering semantically related methods (actually actions, which do side effects). So, to give you an example:               class ViewModel     {       // a lot of properties bound to view (MVVM pattern)       public Property 1 //bound to view       public Property 2 //bound to view            // a lot of actions, containing the controller logic of the view       //Function 1 changes Property 1 -> shall be moved to class MyViewModelHelper       Function1() {}      That is, when I create a helper class for the viewModel, it needs to to receive the instance reference of the main view model in its constructor, so that it has access to the public properties. I do not want that the view has to have the knowledge about the helper classes, that is the main view model shall provide all the properties... but the functions shall delegate the work to the helper classes to keep the viewModel class maintainable. Is there any known add in /tool for visual studio, which can automatize this?


Is information hiding more than a convention?

In Java, C# and many other strongly-typed, statically checked languages, we are used to write code like this:               public void m1() { ... }     protected void m2() { ... }     private void m2() { ... }     void m2() { ... }      Some dynamically checked languages don't provide keywords to express the level of "privateness" of a given class member and rely on coding conventions instead. Python for example prefixes private members with an underscore:               _m(self): pass      It can be argued that providing such keywords in dynamically checked languages would add little use since it is only checked at runtime. However, I can't find a good reason to provide these keywords in statically checked languages, either. I find the requirement to fill my code with rather verbose keywords like `protected` both annoying and distracting. So far, I have not been in a situation where a compiler error caused by these keywords would have saved me from a bug. Quite in contrary, I have been in situations where a mistakenly placed `protected` prevented me from using a library. With this in mind, my question is: **Is information hiding more than a convention between programmers used to define what is part of the official interface of a class?** Can it be used to secure a class' secret state from being attacked? Can reflection override this mechanism? What would make it worthwhile for the compiler to **enforce** information hiding?


The Default State of Unused Memory

In an embedded device, during the initializing of memory locations, is there any convention that are being practiced. I mean, say setting every byte to zero or 0xFF or any other value.


What makes for a good architect/manager/lead developer?

I am the Lead Developer for a small software company. Over the past two years, my team has grown from one developer (me) to a group of about nine people. Most of us are very capable, senior engineers (20+ years of experience building software per person), so very little hand-holding is generally necessary. We use Scrum to manage our efforts, and we usually get a lot done quickly with minimal written requirements. As the team has grown, I've reached the point where it is difficult for me to retain technical oversight over the entire project while also writing significant amounts of new code myself, so it is time for me to adjust my role. How can I make myself most useful to the team when I'm no longer spending most of my time developing? **My goal is to allow my group to grow even further (i.e. increase Scrum velocity) by adding more developers** , so I don't want to simply become the "architecture police" who imposes my will on the team. In other words, I want to be the guy who helps things work better/smoother, rather than be the guy who slows things by down by adding an unnecessary layer of bureaucracy. Still, one of our main risks is that things will spin out of control if we add more people without having enough structure to keep us all on the same page. What is the best way to achieve my goal?


Are there any drawbacks to the Major.Minor.YMDD.Build version strategy?

I'm trying to come up with a good version strategy to fit our specific needs. We've proposed settling on this and I wanted to ask the question to see if anyone's experience would suggest avoiding this or altering it in any way. Here's our proposal: Versions are released in this format: MAJOR.MINOR.YMDD.BN. Here it is broken out:   * MAJOR & MINOR are typical; we'll increase MINOR when we feel code and new feature sets warrants it; once every few months most likely. MAJOR will increase ~yearly.   * YMDD: Y will be the last digit of the current year, so "1" for 2011, "2" for 2012, etc. A non-padded month will be used to keep the number smaller (9 instead of 09 for example). DD of course is the day, padded with a zero for days under 10.   * BN: BN is the build number and increases by one anytime we make a change to a branch of the code represented by the build, for example: If were to make a build today, our release would be version 5.0.1707.1. I release to QA today and 3 days from now QA finds that a change broke the save functionality on a page. Instead of me changing our current development code, I'd go back to the code that I used to create version 5.0.1707.1, make the fix there, then increase the BN portion of the version and would then re-release 5.0.1707.2 back to QA. In short, anytime a change is made to a branched version that isn't the active dev branch, we'd use the original version number and increase only the BN portion (even if the change happened 3 days, 3 weeks or 3 months from the initial release of that version). Anytime we make a new release from our Active dev branch, we'd come up with a new version based on the M/D of the release using the outlined strategy. We do this once every 2-3 weeks. Are there holes or pitfalls with this? If so, what are they? Thanks **EDIT** To clarify one point that I didn't get out very well - Oct/Nov/Dec will be two digits, it's only the year that won't be. So 9 for Sept, 10 for Oct, 11 for Nov, etc.


listing my programming experience on my resume

On my resume, I list myself as having "7 years of hands-on experience programming in C++". To clarify, I am a self-taught C++ programmer with some college courses thrown in the mix. I've worked on some small personal projects, and I consider myself to be more competent than a CS grad with no actual real-world experience, though by no means am I anywhere near being an expert. The issue is this... I keep getting calls and emails from recruiters that see my resume on job sites, inquiring about my interest in senior developer positions, contracts, etc., of which I feel that I am completely under- qualified for. My resume only has 3 years of work experience listed (which is all IT stuff), so when they ask about my prior experience in C++, I have to clarify that it was personal work, not professional work. I'd really like a job as a developer, but I don't want to get hired for something that I can't handle, nor do I want to misrepresent myself while trying to show off my strengths. I deliberately chose the phrasing "hands-on" to imply that it wasn't professional. How should I phrase my C++ experience on my resume to clarify it better?


Is XML, HTML/CSS, XSL analogous to Model, View, Controller?

For some time in personal projects I have been using XSL to convert my raw XML data into human-friendly HTML/CSS (in simple projects, I have no JavaScript, so let's leave that out of the equation for simplicity). Now I'm trying to understand the MVC architectural pattern (not my first experience with it, but it is taking some work to go from understanding it basically to understanding it well), and I'm wondering if there is an analogy between the two.   * **XML** : data model; lacks the complexity/logic of a full-blown model component, but intent seems similar   * **XSL** : converts raw data for viewing--seems like a controller   * **HTML/CSS** (rendered): the viewable output Is this analogy fitting? What in it matches well and what does not? (One dissimilarity, I suppose, is that in my example I am not getting any input back from the view--only producing output.)


Has JPA replaced CMP?

No question too stupid right :) Came across this on wikipedia > The Java Persistence API replaces the persistence solution of EJB 2.0 CMP > (Container Managed Persistence). My understanding was the CMP is still there i.e Pooling,Transactions etc can be done via CMP where as JPA is ORM for me. I did not think there are even same thing . I thought may be CMP VS JTA might make sense but obviously not.   I know how off track I am but thats why I am here may some can help me get things in perspective.


Does current evidence support the adoption of Contextual over Canonical Data Models?

The "canonical" idea is pervasive in software; patterns like Canonical Model, Canonical Schema, Canonical Data Model and so on, seem to come up again and again in development. Like many developers, I've often followed, uncritically, the conventional wisdom that you _need_ a canonical model, otherwise you'll face a combinatorial explosion of mappers and translators. Or at least, I _used to_ do that until a couple of years ago when I first read the somewhat-infamous EF Vote of No Confidence: > The hypotheses that once supported the pursuit of canonical data models > didn’t and couldn’t include factors that would be discovered once the idea > was put into practice. We have found, through years of trial and error, that > using separate models for each individual context in which a canonical data > model might be used is the least complex approach, is the least costly > approach, and the one that leads to greater maintainability and > extensibility of the applications and endpoints using contextual models, and > it’s an approach that doesn’t encourage the software entropy that canonical > models do. The essay presents no evidence of any kind to support its claims, but did make me question the CDM approach long enough to try the alternative, and the resulting software didn't explode, literally or figuratively. But that doesn't mean a whole lot in isolation; I could have just been lucky. So I'm wondering, has any serious research been done into the practical, long- term effects of having a canonical model vs. contextual models in a software system or architecture? Or, if it's too early to be asking that, then have any developers/architects written about personal experiences switching from a CDM to independent contextual models, or vice versa, and what the practical effects were on things like productivity, complexity, or reliability? What about the differences at different levels, i.e. using the same model across a single application vs. using it across a system of applications or an entire enterprise? (Facts only, please; war stories are welcome but no speculation.)


Python Metadata Files and Project Organization

I have a project in Python where I have a server. The server can have a variety of different services, but I don't know what those are until I start it up. I want it to do a search of available plugin files to know what services are available. Right now, I'm doing that by just having the metadata files as Python source code and loading it using imp.load_source. My question is where do I store these metadata files? The metadata files need to contain information pointing to files on the filesystem. For example, one of the programs the service needs to launch is a java program. I have the jar file and I compile it myself, but when I'm working on the project the compiled file goes into the build directory. When I'm going to want to install this on a machine, I'll need to store the files somewhere else. I want to keep the source directory and build directory separate (as it makes the clean command easier). What standard practice is done to handle the need for metadata files and where they are located? EDIT: I'm trying to target both Windows and Linux systems (and hopefully Mac systems too, but that's less important). For Linux, most important are the major distributions (such as Fedora and Debian) and hopefully others (although this is dependent on others trying to use it on whatever distribution, as I cannot test all of them and will only test on Fedora and Debian myself).


3d point cloud render from x,y,z 2d array with texture

Need some direction on 3d point cloud display using OpenGL in c++ (vs2008). I am brand new to OpenGL and trying to do a 3d point cloud display with a texture. I have 3 2D arrays (each same size 1024x512) representing x,y,z of each point. I think I am on the right track with               glBegin(GL_POLYGON);      for(int i=0; i<1024; i++)      {           for(int j=0; j<512; j++)           {                 glVertex3f(x[i][j], y[i][j], z[i][j]);           }      }      glEnd();      Now this loads all the vertices in the buffer (I think) but from here I am not sure how to proceed. Or I am completely wrong here. Then I have another 2D array (same size) that contains color data (values from 0-255) that I want to use as texture on the 3D point cloud and display. I understand that this maybe a very basic OpenGL implementation for some but for me this is a huge learning curve. So any pointers, nudge or kick in the right direction will be appreciated.


Is it the job of a developer to suggest IT requirements?

I am the only developer working on a web application which is nearing to its end. Now we are looking into making it Live in maybe a couple of months time. This is a web application for a non IT company. Though they have their own internal IT team, they have asked me on what will be the hardware requirements for the live servers eg. RAM, 32 bit or 64 bit. Shouldn't the internal IT team be doing this or since I am the only person working on the project is it my resposiblity to let them know of the any specific hardware requirements which may impact the performance of the project? The reason I am asking this question is that, I have not done this before. All the times I used to be given a server and asked to deploy apps on it. I never used to worry about the server configuration, etc.


Advice: How to convince my newly annointed team lead against writing the code base from scratch

I work in a pretty reknowned MNC, and the module that I work in has been assigned to a new "lead". The code base is pretty huge (~130K or more, with inter dependencies on other modules) , but stable - some parts have grown ugly over the years, but its provably in working state. (Our products are running for years on them, even new ones). The problem is, our lead wants to rewrite the code _from scratch_ , to encompass "finer granularity and a proactive design". I know in my guts thats not a very good idea, but how do I convince him/the rest of the team(who are pretty much more senior than me in terms of years of exp), without sounding too pedantic myself (Thou shalt not rewrite , as Joel et al have clear articles prohibiting it)? I have a good working relation with the person concerned, and don't want to ruin it, but neither do I want to be party to a decision which would surely plague us for _years_ to come !! Any suggestions for a milder,yet effective approach ? Even accounts of how you have tackled such a situation to your liking would help me a lot! EDIT: The code base I'm talking about is not a product/GUI, but at kernel level with all the critical functionalities for our product. I hope now you know why i sound so apprehensive !!


More job responsibilities, yet still entry level?

I currently work for a large-ish manufacturing company that has a variety of pay grade levels. I've put some serious time and effort into my work over the past 4 years and I've managed to make a significant enough impact that they moved me into a new branch of the company to start an in-house software development branch dedicated to serving our international interests. This has implied a ton of traveling and working at night due to time zone differences. While this is a great opportunity and sounds impressive to my friends/family, I'm still working at the lowest possible pay grade level. I assumed with all the additional job responsibilities that I'd also receive some kind of promotion. Is this common? Do I need to speak up in order to get a promotion? Do I even deserve one? Should I just wait it out? I'm lost...


I just talked to a friend. He said that in his company, QA persons get higher salary than developers, that on average it is 2 times higher. I'm quite surprised because I have thought that QA persons will get lower salary than developers (on average). (true confession: my company does not have QA department) So, how is your company's QA salary compared to developer's? Is it reasonable for QA department to get higher average salary than that of development department?


Starting a second undergraduate degree

## Some background I've started programming when I was about 10 years old and truly loved it ever since. This year I've graduated from a mediocre university with a CS degree in Eastern Europe and two months later got a job offer at Google in Mountain View as a software engineer. ## The problem The problem is with my education - when I went through any curriculum from the top 10 US universities (an a lot of my co-workers are from such universities), and watched some of the online-available video lectures from these universities and the assignments that their students had during their studies, I've noticed that my university does not even come close to their level. I just feel that I was wasting time at my university, when I see that others got incomparably better training in CS. I would say that the courses at my university covered at most 30% of what the top-10 universities did - despite having identical classes. They just have better teachers, better curriculum, harder projects, better resources and they go more in-depth. Now, I feel quite comfortable with solving algorithmic problems, with programming in general, but still - each time I look at any of the undergraduate courses in these universities I find a lot of nuances that weren't covered in my classes. Some of them are significant, other less. ## The question Now being in the US, being financially and legally able to afford paying for an undergraduate CS course - is it worth going to one of the top 10 US universities and complete a second CS bachelor degree to fill in the gaps left over my first degree?


Why isn't protection against SQL injection a high priority?

On Stack Overflow, I see a lot of PHP code in questions and answers that have MySQL queries that are highly vulnerable to SQL injection attacks, despite basic workarounds being widely available for more than a decade. Is there a reason why these types of code snippets are still in use today?


Javascript MVC in principle

Suppose I want to implement `MVC` in JavaScript. I am not asking about MVC frameworks. I am asking how to build it _in principle_. Let's consider a search page of an e-commerce site, which works s follows:   * User chooses a product and its attributes and press a "search" button.   * Application sends the search request to the server, receives a list of products.   * Application displays the list in the web page. I think the _Model_ holds a `Query` and list of `Product` objects and "publishes" such events as "query updated", "list of products updated", etc. The _Model_ is not aware of DOM and server, or course. _View_ holds the entire DOM tree and "subscribes" to the _Model_ events to update the DOM. Besides, it "publishes" such events as "user chose a product", "user pressed the search button" etc. _Controller_ does not hold any data. It "subscribes" to the _View_ events, calls the server and updates the _Model_. Does it make sense?


designing large scale applications in a low level language

I have been learning C for a while but still get confused about designing large programs within C (a large application such as the Linux kernel). Moving from Java where you have classes it's difficult to understand how to design a large application in C. What advice/links can people advise from moving from a high level language to designing applications in a low level language such as C?


Copyright question about building a similar app

A client wants me to build a Wordpress plugin similar to an app on Windows Phones. Although the app that I will build will be different in many ways (such as the UI, logos, graphics and a couple of more functions) but the basic functions will be similar to the app currently available on Windows Phone. I am doing this as a freelance project. I would like to know once I complete the development and send over the files to the client, and in case the original owner of the app on the Windows Platform comes out saying that the Wordpress plugin has a lot of features from their app. Who would be the one in trouble? Can he file a case against me or will it only be my client who will be held responsible as he will own all the rights after I send him the files and he makes a payment. Update : thank you for all your inputs and help. Much appreciated. To clarify on some of the questions raised :   1. Yes, this is a work for hire project.    2. The freelancing contract says that all rights and files including source code have to be transferred to the client after he makes the payment and thereafter he owns all the code and the app.    3. The app to be made is a utility app, but i am not sure how common such kind of an app is and whether i can really relate it to the accounting app example.   4. I am writing my own code, I have no access to the original app source


View is calling constructor method in the Model instead of passing model to the controller method

The problem is the UserTypes property (used to populate a drop down list in the AddUser view) is not being retained after POSTback of the form. **Here is my AddUserModel:** (which inherits from EditUserModel which doesn't have properties for UserTypes/UserTypesSelectList - probably part of the problem?)                public class AddUserModel : EditUserModel         {             public AddUserModel() : this(new Dictionary<string, string>())             {              }                  public AddUserModel(Dictionary<string,string> userTypes)             {                 UserTypes= userTypes;             }                  //properties etc                  public Dictionary<string, string> UserTypes{ get; private set; }                  public SelectList UserTypesList             {                 get { return new SelectList(UserTypes, "key", "value"); }             }     }      **The view has the following** but it calls the parameterless constructor in the above code first instead of the AddUser() method in the controller:                  using (Html.BeginForm<MyController>(c => c.AddUser(Model)      I can see when debugging that this is because the parameterless constructor method in the AddUserModel is being called first instead of the controller method being called (thereby instantiating an empty AddUserModel). I found this question on this site but I still do not understand. Debugging shows that after POSTback of the form the AddUserModel contains no data, but the EditUserModel does contain the data (except the UserTypes data because it doesn't have a property for that) Should both the Add and Edit Models have the same properties? i.e UserTypes and UserTypesSelectList? Is there something I'm missing in terms of how Models inherit from each other and relate to Views? **Edit** After abit of research and deciding to use a shared model I was able to fix the above. Please refer to my answer for more details.


Introducing Agile development after traditional project inception

About a year and a half ago, I entered a workplace that claimed to do Agile development. What I learned was that this place has adopted several agile practices (such as daily standups, sprint plannings and sprint reviews) but none of the principles (just in time / just good enough mentality, exposing failure early, rich communication). I've now been tasked with making the team more agile and I've been assured that I have complete buy-in from the devs and the business team. As a pilot program, they've given me a project that just completed 15 months of requirements gathering, has a 110 page Analysis & Design document (to be considered as "written in stone"), and where I have no access to the end users (only to the committee made up of the users' managers who won't actually be using the product). I started small, giving them a list of expected deliverables for the first 5 sprints (leaving the future sprints undefined), a list of goals for the first sprint, and I dissected the A&D doc to get enough user stories to meet the first sprint's goals. Since then, they've asked why we don't have all the requirements for all the sprints, why I haven't started working on stuff for the third sprint (which they consider more important but is based off of the deliverables of the first 2 sprints) and are pressing for even more documentation that my entire IT team considers busy-work or un-related to us (such as writing the user manual up- front, documenting all the data fields from all the sprints up front, and more "up-front" work). This has been pretty rough for me as a new project manager, but there are improvements I have effectively implemented such as scrumban for story management, pair programming, and having the business give us customer acceptance tests up front (as part of the requirements documentation). So my questions are:   1. What can I do to more effectively introduce change to a resistant business?   2. Are there other practices that I can introduce on the IT side to help show the business the benefits of agile?   3. The burden of documentation is strangling us - the business still sees it as a risk management strategy instead of as a risk. What can we do to alleviate their documentation concerns and demands (specifically the quantity of documentation and their need for all of it up front)?   4. We are in a separate building from our business, about 3 blocks away and they refuse to have their people on the project co-habitate b/c that person "won't be able to work on their other projects while they're at our building." They expect us to always go over there and to bundle our questions so that we can ask them all at once and not waste that person's time with "constant interruptions." What can we do to get richer communication from them? Any additional advice would also be appreciated. Thanks!


How can we inspire "hacker" culture?

I came across these essays the other day whilst dreaming of becoming a Lisp hacker: http://paulgraham.com/yahoo.html, http://paulgraham.com/gba.html and they crystallised for me that the reason for the unrelenting failure I'm seeing in so many software projects I find myself working on is that programming is seen as a low-end commodity resource that is an afterthought in comparison to the heavyweight layers of non-technical management that strategise above the code. Given our commodity nature, what practical steps can we take to inspire hacker culture in our fellow commodities?


Learning About Data Feeds

How and where can I learn more about financial data feeds? I'm specifically interested in learning how feeds are implemented, i.e. are feeds implemented as SOAP/RESTful Web Services? Or if they are implemented differently, how so and as what?


Moving a multi-activity android app into a navigation drawer activity

I'm making an Android app and have it structured as a simple multi-activity app. I want to add a navigation drawer to it, and it looks like I will need to completely restructure the app and load everything as fragments. (http://developer.android.com/training/implementing-navigation/nav- drawer.html) How should I begin performing this "movement" of code? Should I completely copy and paste my class variables and functions into a giant file? This definitely feels like it would be prone to bugs and errors. Perhaps there's a method of separating the class files but still having one navigation drawer?


want to switch from Enterprise software development to C programming

I'm a software engineer with 5years of IT experience in a reputed (tier 1 indian MNC) service based software company in peoplesoft and informatica. But unfortunately i'm interested to switch to a programming career, esp. C. Can anyone please let me know what is a way to switch to a C programming career? Also, what are the pros and cons for such a switch?


Mono patent safety

Could you please share you thoughts about Mono patent safety? Is it risky to use Mono in production for commercial projects? In case of WEB application, for example the following technology stack: "Linux + PostgreSQL + C# Mono + EntityFramework(Mono) + ASP.NET MVC(Mono)", can I be sure that if I will use implemented by Mono Project frameworks (ADO.NET, ASP.NET/MVC, EntityFramework, WCF) and run them on Linux I will not get a persecution from Microsoft caused by some patent violation? Thank you!


Which timeout should I set to an external service?

This service is a remote session pool. I need to ask for a session to work with other services. In most cases, this pool will have a session available, so in 15ms I will have a response. But sometimes, it will need to create a session on demand, requiring up to 800ms to create it. I have two options in mind to handle this situation:   1. To set a 15ms timeout, and to implement a retry policy up with an exponential back off until 800ms. This service will create the required session no matter whether I am connected to it.   2. To set a 800ms timeout, and to keep connected to the service until a session is available for me. In both cases, there's no guarantee that I will have a session after 800ms. **Which are the pro/cons for each option?**


What are some interesting problems to solve using GA's?

I want to start messing around with Genetic Algorithm's in my spare time. I've been thinking of some ways to incorporate them either into personal projects or work projects. I work in financial software - so a lot of risk analysis and things like that using derivative markets. Not sure how GA's would fit into that. Was curious to see if anyone had any cool ideas about how I could use GA's to cure some boredom and do some really cool stuff!


What is a good use case for native XML databases?

What would be a good use case to use a native XML database such as Apache Xindice and eXist-db? I have used XML features of SQL Server in the past and they were of great value, but there it is possible to use XML for 5% and traditonal storage for 95% of the application. Which application types would benefit from a 100% XML storage?


Good platform to teach Programming 101?

Years ago, I used to suggest Visual Basic 6 to rank beginners as a way to learn what programming is. Key point: This was NOT for career training, but just as a primer to the basic concepts of programming. I subscribe to the KISS principle (many programmers do not) Detest Microsoft as we may, the instant graphical nature of VB6 really helped kickstart things for the rank beginner (GUI control methods/events vs, cmdline programming) VB may have been a "toy", but it allowed real programming concepts to be applied. One could learn these UNIVERSAL topics in any language, including VB6:   * Datatypes, variables and constants   * Conditionals (If....Then....Else Blocks, Select Case)   * Random number generation / seeding   * Introduction to threads/timers   * Loops (while loop, for loop)   * Functions & procedures (and passing parameters)   * Using arrays    * GUI controls (properties, methods and events)   * GUI animation (manipulating top, left, visible properties)   * Creating and adding external modules    * Debugging (breakpoints, watches, debug window) What environment or platform would you suggest to use today? Is Java/Eclipse making things too complex? To some extent, I think Java is overkill for this type of goal (OOP, etc). Would the path of least resistance be Visual Basic Express Edition 2012? or something else entirely like some sort of smartphone IDE? Or is that just too distracting, too complex, or too easy? And what do you lose compared to VB (Think how trivial it is to learn basic animation with the Timer and .top and .left) The KEY is to keep it EASY while not watering it down. Again, suggesting some esoteric language just because it's more "elegant" misses the entire point. What would you tell your neighbor's 15 year old kid to use if he wanted to know what programming is? (He does not want to become a professional programmer, and is not a good independent learner) Thank you.


Why does the stack grow downward?

I'm assuming there's a history to it, but why does the stack grow downward? It seems to me like buffer overflows would be a _lot_ harder to exploit if the stack grew upward...


PDF help in the software manual

Just need a bit of advice here, if we embed Adobe Reader as an activex control, as well as have a fallback PDF viewer (in case the user doesn't have Adobe Reader installed) would it be wiser to put screenshots in the manual using whatever the latest version of Adobe Reader is, or using the fallback reader? I can see the drawbacks and benefits of both. For one thing, the look and feel of the fallback reader is constant, whereas Adobe Reader changes, so we don't have to redo the manual as often. But we expect that 90% of users will have Adobe Reader, so what they see in the manual won't even be what's in the program if we use the fallback reader for screenshots. So what's the solution. Adobe, Fallback Reader or Both? (For the record, the manual is a CHM, not a PDF)


Sharding / indexing strategy for multi-faceted search

I'm currently thinking about our database structure and how we modify it for scale. Specifically, we're thinking about using ElasticSearch to provide our search functionality. One common pattern with ElasticSearch seems to be the 'user-routing' pattern; that is, using routing to ensure that any one user's data resides on the same shard. This is great for client-specific search e.g. Gmail. Our application has a constraint such that any user will have a maximum of a few thousand documents, so this pattern seems like a good candidate. However, our search needs to work across _all_ users, as well as targeting a specific user (so I might search my content, Alice's content, or all content). Similarly, we need to provide full-text search across any timeframe; recent months to several years ago. I'm thinking of combining the 'user-routing' and 'index-per-time-interval' patterns:   * I create an index for each month   * By default, searches are aliased against the most recent X months   * If no results are found, we can search against previous X months   * As we grow, we can reduce the interval X   * Each document is routed by the user ID So, this _should_ let us do the following:   * search by user. This will search **all indeces** across **1 shard**   * search by time. This will search **~2 indeces** (by default) across **all shards** Is this a reasonable approach, considering we may scale to multi-million+ documents? Or should I be denormalizing the data somehow, so that user searches are performed on a totally seperate index from date searches? Thanks for any pros-cons of the above scenario.


What is the need of Odata when I have JSON ?

I am trying to understand the point of Odata and when it would make sense. Right now how I work is I use ASP.NET and MVC/WebApi controller to serialize/deserialize objects into JSON and have javascript do something with it. From what I can tell the benefit of OData is being able to query directly from the URL ... But since I am writing the client and server code there is no need for that. Would anyone ever parse the results of a ODaya query in javascript?? Maybe OData is more about providing a generic endpoint for ALL clients to get detailed information from a query that JSON does not provide ? So if I was a provider of data then I suppose that is what odata is for ? Help me understand the purpose and use of REST/JSON/ODATA.


Bringing your own computer to work

I recently joined a startup, and we've been growing quickly over the last year. However, I've noticed that out of all the new hires (mostly sales and support) they are bringing in their own laptops to work. Is that normal? Most of the developers have basic linux boxes provided for them. Meanwhile the company keeps telling us every month that they've set a new revenue record.


How do you keep track of the meaning of your SQL fields?

The more SQL fields I add to my tables and the more primary/foreign keys I add the more I lose the overview for specific fields for certain scenarios like Get/Add/Delete/Update data. I use SQL Management Studio (SQL Server) to design my database in the database diagram designer. Maybe there is a better tool or good approach how to keep track of the meaning of all those fields?


Side effect-free interface on top of a stateful library

In an interview with John Hughes where he talks about Erlang and Haskell, he has the following to say about using stateful libraries in Erlang: > If I want to use a stateful library, I usually build a side effect-free > interface on top of it so that I can then use it safely in the rest of my > code. What does he mean by this? I am trying to think of an example of how this would look, but my imagination and/or knowledge is failing me.


Best Practices for serializing/persisting String Object Dictionary entities

I'm noticing a trend towards using a dictionary of string to object (or sometimes string to string), instead of strongly typed objects. For example, the new Katana project makes heavy use of `IDictionary<string,object>`. This approach avoids the need to continually update your entity classes/DTOs and the database tables that persist them with new properties. It also avoids the need to create new derived entity types to support new types of entity, since the Dictionary is flexible enough to store any arbitrary properties. Here's a contrived example:               class StorageDevice {          public int Id { get; set; }          public string Name { get; set; }     }          class NetworkShare : StorageDevice {         public string Path { get; set; }         public string LoginName { get; set; }         public string Password { get; set; }     }          class CloudStorage : StorageDevice {         public string ServerUri { get; set }         public string ContainerName { get; set; }         public int PortNumber { get; set; }         public Guid ApiKey { get; set; }     }      versus:               class StorageDevice {                  public IDictionary<string, object> Properties { get; set; }     }       Basically I'm on the lookout for any talks, books or articles on this approach, so I can pick up on any best practices / difficulties to avoid. Here's my main questions:   * Does this approach have a name? (only thing I've heard used so far is "self-describing objects")   * What are the best practices for persisting these dictionaries into a relational database? Especially the challenges of deserializing them successfully with strongly typed languages like C#.    * Does it change anything if some of the objects in the dictionary are themselves lists of strongly typed entities?   * Should a second dictionary be used if you want to temporarily store objects that are not to be persisted/serialized across a network, or should you use some kind of namespacing on the keys to indicate this?


Good reasons for destroying mutexes with waiting threads

I'd like to see some valid examples of needing to let a thread enter a locked, non-re entrant mutex, then destroying the mutex (which supposedly terminates the thread). I can't think of any good reason to do this. I can't remember precisely what we were arguing about earlier today, but my colleague insists such techniques are needed for "point-of-no-return" problems (again, forgive me, but I forgot the example he gave me).


Are all dirty fixes created equal?

I have seen some dirty code in my time. I have heard varied feedback about "dirty fixes" too: a) a dirty "fix" is not a fix b) some fixes dirtier than others but dirty fixes are not acceptable c) some fixes dirtier than others and some dirty fixes are more acceptable than others d) dirty fixes show a pragmatic use of ones time but should be discouraged e) dirty fixes show a pragmatic use of ones time and should not be discouraged f) other Which of the above would you agree with and why? How do you stop attitudes like (e) from becoming standard practice?


What techniques should be used to ensure clear communication from the customer?

Some customers use terms from the domain language interchangably and incorrectly. This has, on several occassions, lead to an implementation of a feature in a way that was not desired by the customer. Are there any techniques that can be used to enforce the correct use of terms? Are there any techniques that can be used to prevent someone from handing "back of a cigarette packet" requirements to a developer?


do you use built in Stack/Queue/List or Vector in your program?

Yesterday i saw in a post a guy said that built in Stack/Queue are 5x slower than a normally coded Stack/queue !   Is it true ?   If true then why Microsoft (C#.NET,VB.NET) or Oracle (JAVA) is giving such ADT ?   Which one you prefer ? Writing your own or using the built in ? [I think most of the people prefer the built in as the code have been tested many times and is very very optimized]


Is there an idiom for a loop that executes some block of instructions between iterations? (In Ruby in particular)

I often need to do some operations in a loop and some other operations between the iterations. A simple example would be collecting words from an array into a string, spelled backwards and separated with commas. Is there an idiom or language support for this in any language? (For now i am mostly interested in Ruby.) I usually do something like               a = ['foo', 'bar', 'baz']     s = ''     n = a.size - 1     i = 0     loop do       s << a[i].reverse       break if i == n       s << ', '       i += 1     end      But i know no way to save this half iteration if using a ruby iterator:               s = ''     ['foo', 'bar', 'baz'].each do |w|       s << w.reverse       # ???     end


Is there any difference between interfaces and abstract classes that have abstract methods only?

Let's say we have an abstract class and let this class has only abstract methods. Is this abstract class different from an interface that has same methods only? What I am looking to know is if there are any differences both philosophically, objectively and in the underlying programming language implementation between an Abstract Class with only abstract members and an equivalent Interface?


Is this the right strategy to convert an in-level order binary tree to a doubly linked list?

So I recently came across this question - Make a function that converts a in- level-order binary tree into a doubly linked list. Apparently, it's a common interview question. This is the strategy I had - Simply do a pre-order traversal of the tree, and instead of returning a node, return a list of nodes, in the order in which you traverse them. i.e return a list, and append the current node to the list at each point. For the base case, return the node itself when you are at a leaf. so you would say               left = recursive_function(node.left)     right = recursive_function(node.right)     return(left.append(node.data)).append(right);`      Is this the right approach?


Is microoptimization worth it in mobile devices?

Usually microoptimization is considered not worth it with the following explanation: it might speed up the program by less that one percent, but noone cares of that minor boost - that's just too little of a change to be noticed. Furthermore, there might be some event handler that fires one thousand times per second and exits very fast - before it is fired again. Noone cares how fast it is - making it faster can't be noted, because it already "as fast as can be observed". However in mobile devices energy consumption is an important factor. The same event handler optimized to run ten percent faster will lead to less energy consumed and that's longer battery life and a longer operating device. How accurate is the latter judgement about mobile devices? Are there any real life examples that confirm or disprove it?


Difference between networking programming and socket programming

Are there any major differences when we talk about "socket programming" compared to "network programming"? Are there some topics that cover "network programming" but not "socket programming"?


Is this solution RESTful and secure?

Our product registers new players on our service, and we've chosen to host it on Azure (we're using .NET) and we wanted it to be stateless (for scalability) and relatively secure. Since this is the first REST WS I'm writing, I wanted to get some feedback on whether or not it's a solid solution. Some presumptions to know about our app:   1. Users are logged into the service anonymously, without requiring a password from a user   2. The WS must be completely stateless to allow horizontal scaling   3. We're connecting using HTTPS (SSL) to prevent 3rd party snooping **EDIT:**   1. We target for native iOS/Android devices   2. Our main concern is making sure only non-tampered clients are able to send requests And the abstract authentication process:   1. The client creates a simple hash (UDID:Timestamp) and encrypts it using the timestamp with some basic algorithm (for example, secret key is every 2nd character from the hash)   2. The client sends his UDID, Timestamp & hash to the server   3. The server rebuilds the hash and decrypts the encrypted hash sent from the user   4. If the two are equal - we know that it was actually sent from our client (and hopefully not from a malicious sender) Any input/suggestions would be great - obviously since it's the first time I'm handling this issue I might have designed it incorrectly. Thanks! **2nd update:** Reading the security specs for OAuth, it seems that there is no real answer to my question - since the client and server must know the secret keys and the client is locally stored on our users' mobile devices (as opposed to a web app). From the OAuth security guide (http://hueniverse.com/oauth/guide/security/): > When implementing OAuth, it is critical to understand the limitations of > shared secrets, symmetric or asymmetric. The client secret (or private key) > is used to verify the identity of the client by the server. In case of a > web-based client such as web server, it is relatively easy to keep the > client secret (or private key) confidential. > > However, when the client is a desktop application, a mobile application, or > any other client-side software such as browser applets (Flash, Java, > Silverlight) and scripts (JavaScript), the client credentials must be > included in each copy of the application. This means the client secret (or > private key) must be distributed with the application, which inheritably > compromises them. > > This does not prevent using OAuth within such application, but it does limit > the amount of trust the server can have in such public secrets. Since the > secrets cannot be trusted, the server must treat such application as unknown > entities and use the client identity only for activities that do not require > any level of trust, such as collecting statistics about applications. Some > servers may opt to ban such application or offer different protocols or > extensions. However, at this point there is no known solution to this > limitation.


Permuting a list of numbers by pushing and popping onto a stack

Suppose we have some long stack of numbers. There is another intermediate stack, and a destination stack to be returned in the end. The only two operations allowed is transferring the top of the old stack to the top element of the intermediate stack and transferring the top element of the intermediate stack onto the top of the new stack. List all the possible new stacks that can be produced, assuming the original stack is used up. I'm using Racket/Scheme. Purely functional solutions are more preferable ;) Any ideas on how to do it? By some handwaving it seems that the following function correctly predicts whether a certain output sequence is possible, given that the input sequence is sorted from small to big:               (define (possible? lst)       (match lst         [(cons a b)          (and (if (andmap (λ(x) (< x a)) b) (sorted? b) #t) (possible? b))]         [x #t]))      thus I can simply generate all permuations of the input list and filter out the impossible ones. It seems that there should be a more elegant solution though, which preferably uses recursion and functional programming instead of nested loops and mutation.


IPC linux huge transaction

I'm building and application that requires huge transactions/sec of data and I need to use IPC to for the mutithreaded mutliprocceses communication, I know that there are a lot of methods to be used but not sure which one to choose for this application. This is what the application is gonna have, 4 processes, each process has 4 threads, the data chunk that needs to be transferred between two or more threads is around 400KB. I found that fifo is good choice except that it's 64K which is not that big so i'll need to modify and recompile the kernel but not sure if this is the right thing to do? Anyway, I'm open to any suggestions and I'd like to squeeze your experience in this :) and I appreciate it in advance.


I'd like to write an "ultimate shuffle" algorithm to sort my mp3 collection

I'm looking for pseudocode suggestions for **sorting my mp3 files in a way that avoids title and artist repetition**. I listen to crooners - Frank Sinatra, Tony Bennett, Ella Fitzgerald etc. singing old standards. Each artist records many of the same songs - Fly Me To The Moon, The Way You Look Tonight, Stardust etc. My goal is to arrange the songs (or order the playlist) with the maximum space between artists and song titles. So if I have 2000 songs and 20 are by Ella I'd like to hear her only once in every 100 songs. If 10 artists sing Fly Me To The Moon I'd like to hear it once in every 200 songs. Of course I want to combine these two requirements to create my "ultimate shuffle". I know this is a fairly wide open question. I haven't started programming it yet so I'm just looking for suggestions of a good approach to take. I actually have some other requirements regarding evenly spacing other song attributes but I won't get into that here. * * * As a starting point I'm modifying code I found here to manipulate mp3 files and read ID3 tags. I wrote a small app that satisfies my need using parsifal's answer below. I also wrote a follow up question here. Thanks for all the great responses!


How does git/GitHub handle changed local and changed pushed repositories?

I'm working with a few other people on projects, and today I ran into a situation I'm sure I'll see often. One of my co-workers and myself had split up some tasks to do on the same project and began working. He finished his tasks, and pushed his changes to our shared repository. I was still working on my changes, but I was afraid to push them and overwrite the code he had worked on with my project, only containing half the needed changes. For this situation (just to be safe, I had a presentation on the code in a few minutes and didn't want any major setbacks), I made a copy of my local code, pulled his new code, copied the files I had edited into the project I had just pulled (we were working in two separate sections, but I'm curious as to how git/GitHub handles this issue when working in the same files), and then pushed our combined code. So how does git (or how should we) handle one project with two different changes to the same file?


Overcoming circular reference

I am working on an asp.net MVC web application which contains several projects. One is BusinessObjects, which contains business logic / processes. Another is EmailGeneration which is used to send marketing campaign / customer emails. The EmailGeneration project references the BusinessObjects project because it need to generate templated emails based on Business Objects. I need to be able to trigger emails from business objects so that I can, say, automatically send an invoice when an order is completed. However, I can't add the reference as it would create a circular reference. This suggests that my design is flawed. How can I change my design to reduce coupling between the components?


What's the dominant naming convention for variables in PHP: camelcase or underscores?

The consensus seems to be that one should follow the convention of the platform they're developing for. See: Underscore or camelcase? Naming conventions: camelCase versus underscore_case? However, PHP doesn't seem to strictly follow any convention internally (no surprises there), even for methods and functions (e.g. `mysqli::set_local_infile_default`, `PDOStatement::debugDumpParams`); however, underscores seem to be dominant in function names. However, what I couldn't find was this: **what's the dominant naming convention for variables in PHP?**


Where to use C++ today?

> **Possible Duplicate:**   >  Is there any reason to use C++ instead of C, Perl, Python, etc.?   >  When to use C over C++, and C++ over C? I am going to enter university next fall in computer sciences, but have been programming already for a few years. I am currently doing web application development. I use Python and Java mainly. I also know C++, but never really pacticed it because everytime I think of a project, there seems to be a language that is better suited for the job than C++. For example, Java seems to give the same result as C++, but in a more productive way (even performance-wise, Java is not far behind C++). Not to mention that the Java library is much greater than the C++ one. This makes me wonder where, in the world of web development, could I use C++ and get an advantage that other languages won't give me? I currently believe that it would be as an add-on to a language like Java or Python.


How to test issues in a local development environment that can only be introduced by clustering in production?

We recently clustered an application, and it came to light that because of how we're doing SSL offloading via the load balancer in production it didn't work right. I had to mimic this functionality on my local machine by SSL offloading Apache with a proxy, but it still isn't a 1-to-1 comparison. Similar issues can arise when dealing with stateful applications and sticky sessions. What would be the industry standard for testing this kind of production "black box" scenario in a local environment, especially as it relates to clustering?


Why do most languages provide a min-heap instead of a max-heap implementation?

I just noticed something and I wonder if there is any reason for that. Except for C++ (std::priority_queue is a max heap), I don't know any other language that offers a max heap. > Python's heapq module implements a binary min-heap on top of a list. > > Java's library contains a PriorityQueue class, which implements a min- > priority-queue. > > Go's library contains a container/heap module, which implements a min-heap > on top of any compatible data structure. > > Apple's Core Foundation framework contains a CFBinaryHeap structure, which > implements a min-heap. I find a max-heap more intuitive than a min-heap and I believe technically the implementation difference is only a question of changing a comparison operator. Is there any real reason? Most of the applications need a min instead of a max heap? Thanks in advance


How far should you be from your closest data backup?

Pretend for a moment that something catastrophic happened; you're hacked, and your production database becomes a mess. How far (time) should you be from your rolling out your latest backup and resuming operations as normal? Of course, "immediately" is "ideal", but I'd like to see some real answers. Perhaps some existing, real-life situations that you're currently in with regards to backups.


Completing a project successfully despite hostile management?

I work for a subsidiary of a large world wide company. This was not a subsidiary from the beginning, it was a company bought by the larger company. We seem to be heading toward a death march and I'm wondering if there is anything I (or my team) can do to either resolve the management problems or complete the project in spite of them. It's a typical Daily WTF situation:   * Unrealistic deadlines (management "estimated" 6 months, dev team needs 18 months _minimum_ );   * Long (up to 3h) daily meetings, further cutting our productivity;   * Management refuses to budge on the schedule because they want to look good to the new owners;   * Developers being bullied, accused of incompetence, put on a "wall of shame", etc.   * Team lead just resigned and morale is at an all-time low. I'd like to leave - most of the dev team is considering it - but I'm reluctant to quit. I really need the money, and I've also only been here for a short time (5 months) after a period of unemployment, so quitting now might raise red flags for prospective employers. Are there any strategies which might be effective in fostering more cooperation from the management, or at least minimizing the ongoing disruptions? **EDIT:** _I received great advice from answers to this question. I can't really accept an answer because I can't accept more than one and it would be unfair for the others._ _We've decided to do our best at work given the circumstances. We're pushing back on management to see if we can actually obtain help from them (as new people, new deadline etc). At the same time I'm looking for a new job (as my colleagues were already doing)._ _We'll see what happens and plan accordingly. But one thing is sure: Sacrificing ourselves on the corporate shrine is out of the question._ _Thank you all!_


Java but no JEE experience

I have quite extensive Java experience (many years of Swing, desktop apps, gigantic applets), but have done very little JEE - only one single gig for 9 months, but that was very narrow work where I was basically just implementing business logic (in a highly abstracted internal company IDE) and at most tweaking some JSP pages. Never really picked up the macro flow of the JEE framework in depth. In the meantime, I've done some very limited maintenance of an ASP.NET MVC app at my previous job ( _very_ limited) and am currently playing around with Ruby on Rails at home. I feel like I have the basic gist of web development down, but nothing that I can call solid "industrial strength experience" with any of these frameworks. I'm still a bit in the "cargo cult programming" stage with web development, can't really say that I could plug leaks in the abstractions if they broke, so to speak. So what I'm wondering is: with this background (extensive Java and a decent grasp of how web frameworks work), is JEE going to be be relatively logical and easy to pick up, or will it be a huge and steep learning curve? Basically, I'm planning to learn it, and want a preliminary idea about how big an effort it's going to be.


How long does it take for one to become really comfortable in a programming language and coding starts being fun?

I am just starting out in programming learning Aspect and I'm nearing the end of the introduction. I've learned about algorithms and functions and types of code and Python and briefly the basic ideas of programming. And I have to say it totally fits the description of a language it is like learning how to speak again. So what I would like to know is after this trivial and trying stages of learning just how to get into this gate of overstanding, does programming become easier and more fun? Also I would like to get an idea of how long or far into the learning process it is, before you can speak this language and do things like write an application or design on the web and all these electrifying things are graspable and doable?


Do I need to understand pointers to use C++?

Well, I love C++, I have been using it for a while: I like all the libraries (Allegro, SDL, QT, Ogre, etc.), but I have a problem: I don't understand pointers. Do I really need them ? I just program for fun: but I want to study it some day. Thanks.


Do you sign each of your source files with your name?

> **Possible Duplicate:**   >  How do you keep track of the authors of code? One of my colleagues is in the habit of putting his name and email address in the head of each source file he works on, as author metadata. I am not; I prefer to rely on source control to tell me who I should be speaking to about a given set of functionality. Should I also be signing files I work on for any other reasons? Do you? If so, why? To be clear, this is in addition to whatever metadata for copyright and licensing information is included, and applies to both open sourced and proprietary code.


Is it a good practice by commenting with owner name?

> **Possible Duplicate:**   >  How do you keep track of the authors of code? Here's several scenarios which may comment with owner name:   1. bug fixing, i.e. `// fixed bug 123 by xxx, solution is ... ...`   2. fixme/todo tags, i.e. `// TODO: .... by xxx.`   3. hacks, i.e. `// HACK! ... by xxx` For case #2, please refer to Comment Tags The obvious advantage is that we can ease tracking by names. The downside is the risk of abuse. Actually my previous company allowed this way of commenting style, but current employer completely disallows names appearing in code. In my opinion, I would vote for discreetly commenting with author names. I'm open to hear from you if this commenting style is good or bad. Thanks.


dbdeploy (phing) and development teams

Does anyone here use dbdeploy (phing) in a commands? If so - how do you manage the migrations? Let's suppose we have 2 different features developed in different branches of mercurial repository (phing build file and dbdeploy migrations are stored in mercurial). Which IDs to give to each feature changes?


How can I debug exceptions that are not easily reproducible and only occur in a production environment?

I am working on an issue where the exception only occurs in our production environment. I don't have access to these environments, nor do I know what this exception means. Looking at the error description, I'm unable to understand the cause.               javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure      Would someone please advise me on how to approach this kind of problem?


In which cases build artifacts will be different in different environments

We are working on automation of deployment using Jenkins. We have different environments - DEV, UAT, PROD. In SVN, we are tagging each release and placing same binaries in DEV, UAT, PROD. The artifacts already contains config files w.r.t each environment but I am not understanding why we are storing binaries in environment folder again. Are there any scenarios where deployment might be different for different environments.


Design Parts DB

I'm developing a tool that handles (electrical) parts. The parts can be created, viewed, modified, deleted, grouped and so on... In order to make this question useful for future visitors I like to keep this question universal since managing parts in a DB is very common no matter what parts are in the DB (CDs, cars, food, students, ...). I am thinking of 3 different DB designs:   1. Using a parts table and derived tables for specialized part attributes.              Parts      (id, part_type_id, name)     PartTypes  (id, name)     Wires      (id, part_id, lenght, diameter, material)     Contacts   (id, part_id, description, picture)        2. Using only specialized part tables.              Wires      (id, name, lenght, diameter, material)     Contacts   (id, name, description, picture)        3. Using a Parts-, PartTypes-, ValueTypes- and PartValues table that contain all values.              PartTypes  (id, name)     ValueTypes (id, part_type_id, name)     Parts      (id, part_type_id, name)     PartValues (part_id, value_type_id, value)      Which one to prefer and why? Or is there a better one?   I am concerned about the DB queries. I don't want the queries become overly slow or complicated. ## Update The number of types in the DB are pretty much given and static since they rest on a international standard and will be enhanced seldomly.


is it possible to monitor more than one stream simultanously?

E.g.   \- $stream1 is the STDOUT of a child process and $stream2 is the STDERR of the same child process   \- $stream1 is one child process and $stream2 is another child process Is there a possiblility in perl to monitor two or more streams at the same time? So we loop as long as anything pops-up in any of the streams and we take whatever comes first either in $stream1 or $stream2. Something like               while (my $line = <$stream1 or $stream2> ) {           #do something with the $line     }      ??


How can I do test automation using a python script to test a c program?

I was wondering if I can use a Python script to test a C program automatically. Suppose I have a very simple C program which reads data (numbers as test cases) from the console, calculates them, then outputs it to the console. Now I want to read data from a file then output whatever the program outputs into a file. Suppose in the original C program I use `while` loop and`scanf` to read two numbers into two variables `a` and `b` for several times and do different calculations according to the values of `a` and `b`, like this:               if(a>4 && a<10){...}     else if(a>=10){...}      Now can I use a Python script to test the program automatically? And do I need to modify my C program? How? EDIT: If any method is permitted, then what is the best way to test the C program automatically without using frameworks?


Prevent Casual Piracy for Simple Utility

I've written a small utility that I wish to sell for less than $10. My primary concern is "casual piracy". The scenario that plays out in my mind is this: > User buys the program, enjoys using it and tells their friends. The friends > copy the application to their USB drives and take it home - using the > application for free (maybe never realizing they should have purchased it. Since I've got absolutely no protection built in, it would just be a simple copy'n paste to pirate the app. The users who would be using the app are in close proximity to each other (work in the same environment), so casual piracy would likely occur frequently. **Any ideas?** Keeping in mind the app is cheap (partly to reduce casual piracy), and the level of effort to write the app hasn't been very demanding. Update: the app will run on any system that supports .NET 3.5.


suggest structure for classes that maps to json with dynamic data without using dynamic or object reference

this is a kind of data i have to de-serialize               {         "id": "M:11427",         "title": "DAX30",         "nextStartId": "S:727831",         "sections": [             {                 "type": "HIGHLIGHTS",                 "baseResults": [ values of type highlights ],                 "hasMore": true             },             {                 "type": "CHART",                 "hasMore": false,                 "chartTypes": [ string values ]             },             {                 "type": "TWEETS",                 "baseResults": [ values of type tweets ],                 "hasMore": true             }]     }      I have to serialize & deserialize them all. I want to create something that can hold the values corresponding to baseResults. there is a main class that represent the whole json               class Data      {     ...     ObservableCollection<Section> sections{get;set;}     ...     }      then there is a class that represents the data in **sections** array of main json               class Section     {     string type{get;set;}// thi elements decides what kind of data would be in baseResults     dynamic baseResults{get;set;} //it should hold ObservableCollection of either Highlights or Tweets etc.     }      base class for type of data coming in **baseResults** array is an abstract class `class CategoryData` and its children are `class Highlights` & `class Tweets` I am using `dynamic` since I can not assign an `ObservableCollection<CategoryData>` with `ObservableCollection<Highlights>`. But I don't want to use this dynamic or object type instead I want something relevant. please suggest me what could be a better approach for this problem.


Git-friendly spreadsheet format?

We're trying to move our project documentation process from Google Documents to a set of self-hosted Git repositories. Text documents are Git-friendly enough, since we usually do not need any fancy formatting, we'll just convert everything to, say, multimarkdown with an option to embed LaTeX for complex cases. But spreadsheets are quite different story... Is there a spreadsheed(-like) format that is friendly to version control systems (and, preferably, is as human-readable as Markdown)? _"Friendly format": Git works well with the format (itdoesn't with XML) and it generates human-readable diffs (extra configuration involving external tools is OK)._ Obviously, Markdown flavors allow one to build static tables, but I'd like to be able to use stuff like `SUM()` etc... (Note that CSV has the same problem.) No WYSIWYG is OK, but decent editor/tool support would be nice. _Update: Linux-friendly answers only, please. No MS Office stuff._


Root cause analysis in event correlation

I'm to write an event correlator module for the device we produce. When a fault occurs the resulting avalanche of logs about derivative conditions from various modules is readable only to a person skilled in the task - a layman will be utterly lost. The event correlator is supposed to solve this problem - find root cause and present a friendly message guiding the user to the origin of the problem. I can collect tokenized events from all the modules and observe the internal state of the main module. I can even write history a few seconds back. Now, the hard part and my actual question: writing the analysis algorithm. I tried the Wikipedia page, but it's awfully sketchy on the specific Root Cause Analysis part, and the RCA article linked is more about a business practice than about something that can be phrased as computer algorithm. The net is full of event correlators as software to be bought or used, but I have trouble finding anything about making one. So, summarizing:   * a history of events and states dumped at the moment of error (the "black box")   * a set of rules (preferably in human-editable form in some external file)   * a set of root causes, derived from the events according to the rules.   * a program interpreting these rules, then processing the black box through them and producing a set of root causes matching. How do I even approach writing something like that?   * What would be the format of the ruleset file and a parser for the rules - lexical parsing alone is easy enough but what would it produce?   * How to represent _a rule_ internally? As some kind of object probably, but how would that object look like? How to chain the rules together in a decision tree?   * processing black box data through these rules. Seems an awful lot like running data through a script, but the data contains a lot of of noise. How to assure obtaining _some_ results? Now, some caveats:   * I'd prefer to avoid bayesian or other statistical approach - I'd prefer a fully deterministic solution so that given set of conditions will produce the same result in laboratory analysis, and the precise set of rules is fully human-readable and human-editable.   * Not all components are directly monitored, and some faults can be derived only indirectly. The root cause will not always be one particular message in the black box. Sometimes it will be something that led to a certain set of logs.   * Not always the sequence of events is maintained, as messages sometimes are delayed on the message bus.   * If the main power goes out, we're not guaranteed to capture all the data. Examples: 1.   * Module 1 reports halt; blockade line is active.   * Module 2 reports halt; blockade line is active.   * Module 4 reports halt; blockade line is active.   * PSU module reports external power is okay, internal power has been disabled (per blockade line.) Root cause: Module 3 failed gracefully, serious hardware condition activated the blockade line correctly but it was unable to send its message out. 2.   * Module 1 reports halt; blockade line is active.   * Module 2 reports halt; blockade line is active.   * Module 4 reports halt; blockade line is active.   * PSU module reports external power is okay, internal power has been disabled (per blockade line.)   * Module 3 reports halt; No power in its output line. Activating the blockade line. Root cause: Burnt fuse of output line of Module 3 Now Module 3 was mean by sending out its message last, while pulling the blockade line first. 3.   * Module 3 reports halt; No power in its output line. Activating the blockade line.   * Module 1 reports halt; blockade line is active.   * PSU module reports external power is okay, internal power has been disabled (per blockade line.)   * Module 2 reports halt; No power in its output line. Activating the blockade line.   * Module 4 reports halt; No power in its output line. Activating the blockade line. Root cause: Main fuse of internal power disengaged. Likely reason: short circuit in the PSU or fuse disengaged manually. Note how Module 1 got late with detecting lack of power, say, its output was inactive and the capacitors kept it active long enough that it detected blockade line (engaged by other modules) first, before detecting power failure. Also, normally PSU would report a fault condition of internal power going out, but it's simply slower - less sensitive than the output modules, and they will pull the blockade line before it detects power is out, and by then it will assume this is correct behavior. The difference between cases 2. and 3. is only the number of simultaneous "no power" faults: it's extremely unlikely several fuses go out at the same time, while using the main fuse to disable power for service works is the "traditional" approach and it is expectable at least a few modules will detect "power out" if the main fuse is disengaged.


Will taking a job in web development prevent a low-level programming career?

I'm a computer science student in my last year, and I want to get a job, but have difficulties finding one in my city where I can use what I already know pretty well. There is a company which does PHP/web that insists to work for them, and it is tempting, because pay would be good (for someone who is still a student) and the working conditions are great; the problem is that in no way I want a career in web developement, because I love low-level programming (C++, C, a bit of C# and Python - for my thesis I'm working on a complete C compiler with optimizations - I will make it open source later this year). This job would be only until I graduate and find something I like. Now the question: could taking this job reduce my chances in being accepted on a job where low-level things are done? I think it might, because the interviewer could say something like "Well, if you pretend to know so much low-level stuff, why did you choose a job where you're doing the complete opposite?" Here PHP is considered by many a language used by novice programmers (I know it's not entirely true) and I fear it doesn't give a good impression to claim I have deep knowledge of low-level stuff while having a PHP job (and the only one) listed on my CV.


When or why should one use getters/setters for class properties instead of simply making them public properties?

I program primarily in ColdFusion but this is a general OOP question. Is there any benefit to using:               getProp() {         return prop;     }          setProp(val) {         prop = val;     }      As opposed to simply               obj = new Obj();     obj.prop = "1";


Getting your user agreement right

I'm planning to provide a little service with which you can control your computer from anywere. It exists out of a server (which I will be providing), and two clients (a controlled one and a controlling one). Now I want to provide that service for a little fee. However, the server is actually a small old Dell laptop with a broken screen at my home with Ubuntu as OS. It's not very reliable, but I want to use it, because it's cheep. Now, as I said already, the laptop maybe isn't the most reliable machine, along with my Internet connection, which also can go down if there are some unexpected problems. But I don't want to take risks, and let the user, before he pays, know that this can occur. But I also want me to be safe, so I won't need to give any money back. It is my first application that I will be giving away for a little fee, and I don't know about the legal responsibility I have to take. Basically I don't want to give any money back, even at a 100% downtime (which will be very unlikely), but I also don't want it to be my fault if someone loses data, by using my software, even if it is a bug, or someone intercepted his data. So, I have put this in the agreement, and this only. Is it enough and is it legally binding? What should I also know? >   * iControl actually implements a client-server-client protocol, where one > client let's the other client execute a shell command. Then the controlled > client will return the termination status, the standard output, and the > standard error of that command. >   * iControl uses no encryption to send data over the network. It is a > potential security risk to use this service, because all data is sent raw > over the network. You can compare it with the FTP protocol, the HTTP > protocol, which you're using right now, and the telnet protocol. >   * iControl's maker does not in any way stand in for the damage this > service can do. Not by misuse by the user, not by a bug in the software. No > illegal activities maybe done using this service. The provider of this > service may suspend you from his service at any time without an explanation, > without a money-back guaranty. The collector of the rent fees does not need, > in any circumstances, to return the payed money. >   * The iControl service is maintained by one man and one man only. Any > downtime of the used server may occur. In case of any length of downtime, > the service provider does not have to give any money back, however he'll do > his best to make you as happy as possible by trying to make the service be > up all of the time. > I'm planning to let the user check a box that they read this and agreed to it, when they register. Is this enough?


Freelance charging based on tasks completed

I've just started freelancing and have two projects where I am splitting my week with both companies, one I'm charging hourly and everything is fine, the other one however they have said they will pay me based on a points basis using Pivotal Tracker. For example, there's a fixed rate per point and they work on an estimate that I will complete two points per day, I was just wondering if this is something that is used regularly or if I should try and get them to switch to hourly? My concern is that points are only used for features and if a feature has a bug this isn't taken into consideration so any time spent fixing that bug won't be charged. Correct?


What's the most productive coding environment

I was speaking with an ex-colleague the other day about the most productive way to write code and he said he found it best "to CIMP, or Code In My Pants". When I asked him exactly what he meant, he explained he found it best to work at home, coding at his own pace, dressed comfortably (in his pants), and communicating with his team through emails, IM, or the telephone. Digesting his approach (which he describes to clients as the Complete Integrated Method of Programming), I realised my coding is also more productive when working in an isolated environment, which made me wonder if the software industry has got it all wrong and should development be really done by dispersed teams of individuals, or are there advantages to geographical herding that make up for the added interruptions it brings? So has business got it wrong? Should development occur predominantly across geographically isolated individuals to increase productivity, or are there real reasons why herding developers together makes sense?


How will I restrict the number of users logged in based on session?

I have a software (in cloud) with so many registered users. I want to restrict the number of users logged in at a time to certain number (configuration based, let's say 100). If the 101 user tries to login he should be placed in queue with priority 1, subsequently 102 user should be 2 in queue, I know at every time a logged in users request is hitting the server the `sess_file` access time will be updated. What should be the logic from here? Should I check the last accessed time of all the `sess_file` and log-out the uses that are idle? and how will I manage the waiting queue? Software is done with PHP-MySQL. When the user is logged in I mark the column as logged in in user table, and when the log-in page is loaded if the total logged in user count is 100, the 101 user who is trying to log-in is directed to a intermediate page which will check via ajax call fired at an interval of 5 mins that if any user is logged out. If a slot is available it redirects to the log-in page, automatically logs in and redirects to the user dashboard. But I want to know any better practice is there. Mostly I want to know the invalidation of logged in user by checking the access time of `sess_file` is the right way to do it?


Internal Libraries (Subversion Externals, 'library' branch, or just another folder)

Currently working on multiple projects that need to share internal libraries. The internal libraries are updated continually. Currently only 1 project needs to be stable but soon we will need to have both projects stable at any given time. What is the best way to SVN internal libraries? Currently we are using the 'just another folder' like so... > trunk\project1   >  trunk\project2   >  trunk\libs It causes a major headache when a shared library is updated for project1 and project2 is now dead until the parts that use the library are updated. So after doing some research on SVN externals I thought of this... > trunk\project1\libs (external to trunk\libs @ some revision)   >  trunk\project2\libs (external to trunk\libs @ different revision)   >  trunk\libs\ I'm a little worried about how externals work with commits and not making library commits so complicated that I am the only one capable of doing it (mostly worried about branches with externals as we use them extensively). On top of that we have multiple programming languages within each project some of which don't support per-project library directories (at least not easily) so we would need to check out on a per project basis instead of checking out the trunk. There is also the 'vendor' style branching of libraries but it has the same problem as above where the library would have to be a sub folder of each project and is maybe a little to complicated for how little projects we have. Any insight would be nice. I've spent quite a bit of time reading the Subversion book and feeling like I'm getting no where.


Should a DR & CR entry both be created or a single-entry accounting is fine

A new project has an amount. It is always related to a client. One client can have many projects. And he may pay in steps for a particular project. In order to keep track of client payments, I've created a table namely `client_ledger` which contains information about date, time, amount, mode of payment & related project. But then in one of the software screens, I have to reports pertaining to a client's debit & credit. So there are 2 things that can be done :   1. Either I can get the total amount of all projects of that client and his total payments & then can show how much balance is left to be paid.   2. Or if I'd created an entry in the `client_ledger` table for `DR`, then as soon as a project is created, an entry is made in the table for `DR` and subsequent payments received will be `CR`ed into the data-base. In this case, if a project's amount is modified/edited later, then either the original `DR` entry has to be modified, or a new `CR` entry followed by the new project amount's `DR` entry should be made. Which of these processes should be followed ?


Developers inheriting code. What to ask the old developer to better help the new developer?

I know nothing about code. We've had our old iOS developer drop out and we're looking for a new developer or a team to pick up where he has left off. I'm aware there can be issues with developers inheriting code etc. What are some questions that I can ask my old developer to better help the new developer understand what stage the code is at, what needs working on etc etc. Just general type questions? So that when I meet with potential new developers I can hand them a 'fact sheet' of where the code is at form the old developer.


Is there a need for a factory class for creating viewmodels?

A colleague of mine suggested using a factory class for creating viewmodel objects in our ASP.NET MVC solutions. The idea being that it can help with the design, and maintainability, of the way viewmodels are built in our apps. I wanted to find out if anyone else has experience of this. I've done some research and found very little on this practise. Currently we create viewmodel objects at the controller level eg               public ActionResult Index()     {         return this.View(this.BuildIndexViewModel());     }      So this.BuildIndexViewModel() is responsible for creating the viewmodel class (obviously :). But we're looking into the possability of:               public ActionResult Index()     {         return this.View(ViewModelFactory.CreateIndexViewModel());     }      This is an interesting idea, but I'm not 100% convinced. I was interested in other people's opinions on this.