How to deal with runtime changes to tenant-location in a clustered, multitenant web application with app-managed datasources?

I have a Java web application that supports multi-tenancy to keep customer data separate. Connection pools to each customer database are created at runtime. The details of each customer shard (jdbc url, credentials, etc) are stored in a shard "control" database. When the application needs to access a customer shard, it tries to obtain a JDBC connection from that shard's connection pool. If that connection pool has not be established yet, the application looks up the necessary details from the control schema and creates the pool. This is a fine setup but it has one major issue that I'm not sure how best to solve. This application is eventually going to be clustered with each app instance managing its own customer shard connection pools. The problem is what to do when the location of a customer shard changes. This doesn't happen very often but it does happen. The application has an admin interface for managing the shard details and I could put a function in there that says "rebuild this shard's connection pool" but you would only be interacting with whichever application instance the load balancer sent you to on that request and all of the other instances would not be aware that you wanted the pool rebuilt. So here are the ways I can think of to deal with this along with the pros and cons as I see them. ### 1) Since this scenario is not a frequent occurrence, just forcibly restart all of the application cluster instances when this situation arises and call it a day. PROS: Requires no further work. CONS: This is more workaround than solution. That said, restarting all app instances in a cluster might not be an easy as pushing a button and then going for a coffee break. Additionally, an application user with permission to manage customer shards might not be someone who is allowed to initiate a cluster restart. ### 2) Before releasing a connection from the connection pool, check the control database to see if the pool's definition has been changed and if so, reconfigure the pool before releasing the connection to whomever requested it. PROS: Most straight-forward approach. Application instances are guaranteed to get a connection to the right shard using the freshest information. CONS: Major performance overhead. You need to hit the control schema and read all of the shard definitions and then compare them to what you've currently got loaded for every single connection request in the application. ### 3) Have a background thread on a timer that looks for shard definition changes and rebuilds the pools when necessary. PROS: You avoid the performance hit involved with doing the check upon every request for a connection. CONS: Once a shard definition is changed, there is going to be a period of time in which each application instance has the wrong information. This can have lots of consequences including application exceptions until the shard definition change is picked up. The longer the check interval, the worse this problem is going to be so you'd like it to be as short as possible, but the shorter it is, the bigger the performance hit because you need to load the shard definitions from the control database. ### 4) Wait for an exception to be thrown while trying to obtain a connection from a shard's connection pool and then take that opportunity to hit the control schema and see if the shard definition has changed. PROS: None of the performance problems of options 2 and 3 CONS: Assumes that you're changing the shard definition because the old location is no longer functioning which may not be true. That alone I think is reason enough to kill this option but I'm listing it here because it came to mind. ### 5) Create a "shard definition change" topic in messaging infrastructure that all application instances would be subscribed to and reload connection pools in response to those. PROS: None of the performance issues of options 2 and 3. None of the stale data issues of option 3. CONS: I don't have any messaging infrastructure available to me today. It's coming but nothing I can put a date on yet. I'd appreciate any thoughts/experience/advice you can share with this problem.


Codebase Analysis of Trends over Time

I've looked around for a solution (preferably not hosted, something I can run locally) to do static analysis of a codebase over time for things like SLOC, Complexity, authors, commits, etc. It has to work with subversion, and I have to have some way of getting that "raw data" out in csv. Ultimately I want to write a small R app against the results to view some interesting graphs and do things with the resulting data (like overlaying commits or SLOC against deadlines or tags/releases). Does anyone know if any open source solutions exist that do this? I think really all we want is a way of extracting subversion information for the commits, and statically analyzing the code for that given commit, and being able to aggregate all that and export as .csv (for import into R). I **think** sonar does some of this, but I don't think it will do this sort of analysis or data capture across a codebase's history (ie- looking at subversion from day 1 and capturing commits per day, SLOC, complexity over time, etc). The static analysis I'll need to be done is over Java and JavaScript.


PHP: A config file in .ini or .php format?

I'm working on a huge CMS system, and I asked myself what configuration format I should use. There are two common formats for configuration files. The first one is an INI file, containg all the configuration properties. Then you can simply parse this INI file using build in PHP functions. A second option is to use a PHP file containing a regular PHP array with these configuration properties. Now, it's easier to edit an INI file, but a PHP file give's you more options, for example it allows you to add a function which retrieves one of the configuration options while reading the configuration file. Note: The PHP configuration file would only contain an array of configuration, no initialization functions or anything. (This is possible of course, but it's not implemented by default) Now, what is recommend for me to use as configuration file? What is the most common format for a configuration file? Should I go for simplicity with the INI files, or with a more dynamic one using PHP. One thing to note, this is not for personal usage. I'm planning to release the CMS system soon, and a lot of websites are scheduled already to change to my CMS system.


Java generalization

I have a question regarding generalization. I know when it is needed to be done, but is it worth having an extra class for 1 field? e.g.: `StatisticsCustomer` has fields: `Customer customer` and `int projectCount` `StatisticsCountry` has fields: `Country country` and `int projectCount` What is best in this situation? Creating an extra class just for projectCount or keeping it twice in the two classes?


Why do people fork repositories on GitHub?

I noticed that a lot of GitHub accounts only have repositories which are forked from other accounts. In addition the people who do this usually don't make any contributions to the forked repositories. I've heard of people collecting stamps and seashells, but why would anybody want to collect repositories? Personally I would only fork a repository if I wanted to make some changes to it.


What should be done with class names that conflict (common) framework names

What should be done exactly when the most obvious class name for a component is taken by a framework? In my case, I need to make a class that describes an HTTP request. Of course, the most common name is "taken" as System.Web.HttpRequest. What should I do? This project will be used in a web context, so I'd really rather not force people to not import the System.Web namespace, or type out all of my class names manually. What is the usual way of dealing with this? I can come up with this:   * Prefix class name with a project shortname   * Try to come up with a different name that means the same thing(I've tried and can't come up with anything)   * Force users to choose between namespaces


Should we stick to a framework?

I currently work with Zend Framework, but I also know about CodeIgniter and Kohana. I've just wonder that should I stick to a framework or depend on my purposes? Because I think I cannot master everything.


Multitier architecture using API

I have been reading a number of posts and I am leaning towards building an SOA. My main dependencies are:   * Need to support multiple clients   * Need individual client environments to not effect other client environments For example, if I want to add a text field to Client A's application, but I don't want Client B to be effected in any way. The solution I have is to send an API address along with the client auth token. For example, the client will send something like this:               api: http://myWebsite/api/clients/ClientA/someServiceCall      Similarly, from a token, the (MVC) controller will know which view to render for a given user. My question is, is this a good solution to my problem? I understand that I am having to call an HTTP REST service for my data access; but, I feel this solves a lot of problems. For instance, I could see which services sending 404 errors and fix them (presumably) before they even get reported. I have read a number of articles that seem to enforce my idea. Have I misunderstood this concept? Is there a better architectural approach? Here's what I've been reading:   * Dogfooding: how to build a great API   * Should a website use its own public API?   * Stevey's Google Platforms Rant Again, the goal is to keep individual client environments as separate as possible; such that if we push a change to the service layer, there is no downtime and no one gets logged out because of an app pool refresh. My over all plan is to incorporate these API calls wherever they are needed; i.e. in an MVC controller or a javascript AJAX call. For example:               public class HomeController : Controller     {         public ActionResult Index()         {             WebClient client = new WebClient();             string api = /* api from auth token */             User result = JsonConvert.DeserializeObject<User>(client.DownloadString(api));             return View(result);         }     }


How can the following algorithm be optimized?

I am currently working on a tic tac toe auto-mover game. I have come upon a decent algorithm that allows the computer to easily build towards, and claim victory spots. The problem however is that when the opponent is dangerously close to victory, the computer continues to build towards it's own victory instead of blocking the opponents, is there any way the following algorithm can be optimized to counter that? The algorithm works as follows:   1. Initialize a 3x3 integer array   2. Loop over all possible combinations on the board (0|0, 1|1, 0|2... e.tc).     1. If combination is a immediate victory, stop and return this position.     2. Else initiate a loop (That loops either 1000, 10000 or 100000 times, depending on difficulty)       1. Continually move from both sides randomly till victory is achieved. If victory is by the computer, increment the score counter.   3. Select the board position with the highest score This algorithm works fine and can build towards victory (example:               ·|x|o    ·|x|o    ·|x|o     ·|·|·    x|·|o    x|x|o     ·|·|·    ·|·|·    ·|·|o      However when confronted with a board like this               ·|x|o     o|x|·     ·|·|·      The optimal move should be to break x's chain, but the computer builds towards raising it's own chain i.e moving at 1|2 (The board is 3x3, indexes start from zero. So that'd be the second row's third coloumn). Is there any way to optimize this algorithm such that this weakness goes away?


Is it a bad practice to use empty node with value attribute in XML?

I created XML parsing logic that forces XML to be formatted like this:               <fooList>         <fooObject value="SomeValue1" />         <fooObject value="SomeValue2" />     </fooList>      And then I started to think that a more elegant way would be               <fooList>         <fooObject>SomeValue1</fooObject>         <fooObject>SomeValue2</fooObject>     </fooList>      Are there any recommendations or good practices regarding this? I already know about Element vs. Attribute question, please note that mine is different.


What are Web CMS and how they work?

I have heard about many CMS such as Drupal, Wordpress, Joomla, etc. Many sites are build using these CMS's, but what is a CMS and How they work(i.e basics)? Is CMS a normal Blog like site which is given many extended functionality, or we can do more from it?


Making a virtual supercomputer with distributed P2P computing

I was just having this idea once and wondering if there's any possibility to harness the power of p2p distributed computing to make a virtual supercomputer with the following features:   * Works like a normal machine but uses networked RAM   * Normal applications should be able to work on distributed environment dividing load among peers This maybe unrealistic, just curious and want to know your views.. EDIT: Some interesting links I found while researching...   * http://mashable.com/2005/11/29/my-latest-harebrained-scheme-distributed-computing-as-a-web-service/   * http://mashable.com/2005/11/04/amazon-mechanical-turk-human-processing-for-web-20/


Why do variables need a type?

So we write:               Customer c = new Customer();      Why is the design not such that we write:               c = new Customer();     c.CreditLimit = 1000;      The compiler can work out c points to a Customer and allow Customer's members to be invoked on c? I know we may want to write:               IPerson c = new Customer();     IPerson e = new Employee();      so as to be able to write:               public string GetName(IPerson object)     {         return object.Name     }          string name = GetName(c); // or GetName(e);      But if we wrote:               c = new Customer();     e = new Employee();      we could still write:               public string GetName(object)     {         return object.Name     }              string name = GetName(c); // or GetName(e);      The compiler could complain about the code immediately above if the type of object c references does not support a Name property (as it can check which members are used on the argument/parameter within the method), or the runtime could complain. Even with C#'s dynamic keyword, we are still using a variable 'type' (determined at runtime). But why does a variable need a type at all? I am sure there must be a good reason, but I can't think of it!


usage of double pointers and n pointers?

I am familiar with basic C pointers. Just wanted to ask what is the actual use of double pointers or for that matter n pointer?               #include<stdio.h>     int main()     {     int n = 10 , *ptr , **ptr_ptr ;     ptr     = &n;     ptr_ptr = &ptr;     printf("%d",**ptr_ptr);     return(0);     }      **ptr_ptr is printing 10 but how?


Parent class loses coupling after I refactored identical code blocks from child classes to parent

I have a class called `Parent`, and classes called `Child1`, `Child2`, etc, I have noticed that child classes have a series of function calls that had same (duplicated) lines of code that could be refactored into a function call. So I created a method `getData()`, which I put into the parent class and put those duplicated code lines in the method, and removed original lines from child classes. Two things happened:   * Dynamic nature of PHP allows child classes to call the method from the parent class, so things still work despite children not having (but calling) that specific function. **That's good**   * my IDE can no longer jump from function instantiation inside the parent class to function body in the child class(es). Because it doesn't know which one to pick, nor one exists in the parent class.   **That's kind of bad** \- at least I think that it is. I am losing the ability of IDE/PHP to tell me if there are errors. i.e. it looks like I can invent any function I want in parent class, and PHP will just think "oh maybe it's in the child class", when it in fact may not be - a fact that will only be discovered during run time, or using special static source code tools on PHP. Is there a more proper way to refactor my code? Namely, to have IDE/PHP be able to validate things a bit better than what I have now.


Knowing the range of variable types needed

So, if I (as the programmer) know that my value will never exceed a small number (say 100) because it is really just a counter-controlled loop or whatever, may I use `short` or `char` instead of `int` for the minute memory savings?


"TDD is about design, not verification"; concretely, what does that mean?

I've been wondering about this. What do we exactly mean by design and verification. Should I just apply TDD to make sure my code is SOLID and not check if it's external behaviour is correct? Should I use BDD for verifying the behaviour is correct? Where I get confused also is regarding TDD code Katas, to me they looked like more about verification than design; shouldn't they be called BDD Katas instead of TDD Katas? I reckon that for example the Uncle Bob bowling Kata leads in the end to a simple and nice internal design but I felt that most of the process was centred more around verification than design. Design seemed to be a side effect of testing the external behaviour incrementally. I didn't feel so much that we were focusing most of our efforts on design but more on verification. While normally we are told the contrary, that in TDD, verification is a side effect, design is the main purpose. So my question is what should I focus on exactly, when I do TDD: SOLID, external API usability, or something else? And how can I do that without being focused on verification? What do you guys focus your energy on when you are practising TDD?


What personal process can I employ at a non-software based company?

What is the best way for a developer to track his/her hours at work, if no framework exists at that firm which would avoid any complications with internal classified information being stored on a server I own at home? In particular, I would like to hear of any methodologies or software that could be used in this situation with limited issue. I just graduated from college, and am moving into my first full-time job with an embedded systems firm, which doesn't seem to have any particular process set up for its employees to use. Since last summer, I've been working on improving my development process, trying to record my time usage, bugs found, and other simple metrics for my process. Until now, I have been using Microsoft Team Foundation Server (TFS) to do this from one of my personal servers, and have enjoyed working with it. The firm I am going to, however, doesn't seem to have anything similar, so I am stuck with needing to find a way to continue tracking these metrics. I feel I should not use my TFS server (or a similar tactic, such as Traq), since there would be the chance of exposing company secrets to the outside world through my server.


At what point does "constructive" criticism of your code become unhelpful?

I recently started as a junior developer. As well as being one of the least experienced people on the team, I'm also a woman, which comes with all sorts of its own challenges working in a male-dominated environment. I've been having problems lately because I feel like I am getting too much unwarranted pedantic criticism on my work. Let me give you an example of what happened recently. Team lead was too busy to push in some branches I made, so he didn't get to them until the weekend. I checked my mail, not really meaning to do any work, and found that my two branches had been rejected on the basis of variable names, making error messages more descriptive, and moving some values to the config file. I don't feel that rejecting my branch on this basis is useful. Lots of people were working over the weekend, and I had never said that I would be working. Effectively, some people were probably blocked because I didn't have time to make the changes and resubmit. We are working on a project that is very time- sensitive, and it seems to me that it's not helpful to outright reject code based on things that are transparent to the client. I may be wrong, but it seems like these kinds of things should be handled in patch type commits when I have time. Now, I can see that in some environments, this would be the norm. However, the criticism doesn't seem equally distributed, which is what leads to my next problem. The basis of most of these problems was due to the fact that I was in a codebase that someone else had written and was trying to be minimally invasive. I was mimicking the variable names used elsewhere in the file. When I stated this, I was bluntly told, "Don't mimic others, just do what's right." This is perhaps the least useful thing I could have been told. If the code that is already checked in is unacceptable, how am I supposed to tell what is right and what is wrong? If the basis of the confusion was coming from the underlying code, I don't think it's my responsibility to spend hours refactoring a whole file that someone else wrote (and works perfectly well), potentially introducing new bugs etc. I'm feeling really singled out and frustrated in this situation. I've gotten a lot better about following the standards that are expected, and I feel frustrated that, for example, when I refactor a piece of code to ADD error checking that was previously missing, I'm only told that I didn't make the errors verbose enough (and the branch was rejected on this basis). What if I had never added it to begin with? How did it get into the code to begin with if it was so wrong? This is why I feel so singled out: I constantly run into this existing problematic code, that I either mimic or refactor. When I mimic it, it's "wrong", and if I refactor it, I'm chided for not doing enough (and if I go all the way, introducing bugs, etc). Again, if this is such a problem, I don't understand how any code gets into the codebase, and why it becomes my responsibility when it was written by someone else, who apparently didn't have their code reviewed. Anyway, how do I deal with this? Please remember that I said at the top that I'm a woman, and I'm sure these guys don't usually have to worry about decorum when they're reviewing other guys' code, but honestly that doesn't work for me, and it's causing me to be less productive. I'm worried that if I talk to my manager about it, he'll think I can't handled the environment, etc.


Which certification is the best for PHP?

What are the best PHP certifications according to the market requirements? Actually, I want to get the PHP certification which has the greatest demand. Also, I want to know more about the future of PHP:   * When will PHP 6 be released?   * Could you tell me something about the PHP 6 exam availability please?


Hire for the job/project or hire for the future?

I'm at a pivotal point in my small software company where I have reached the critical mass of too much work and need to hire someone. Simple question: Do I hire someone who is simply qualified and can do the work and possibly grow with the company, or do I hire someone overqualified for the immediate work I have to offer but who can significantly deepen the knowledge and experience pool of my company?


Why is Prolog good for AI programming?

I am researching programming languages used for AI programming. I know that LISP is taught as an AI programming language in my university, but Prolog rarely is. I am kind of fond of Prolog, but I'm not an AI programmer so I don't think I'm qualified to judge for myself why Prolog is better than LISP/Scheme. I was wondering if Programmers had any input on this topic. How could you argue that Prolog would be more useful for AI programming? I have been researching it a bit, and the basic argument I've seen over and over is that since thoughts are presented in logic, and Prolog is a logical programming language, Prolog can build decision machines easily, or something to that effect. Is there anything else that can be said for Prolog in AI?


Which server side framework/language should I use

I am an iOS developer. I love objective-c and the cocoa/cocoa-touch framework. I was wondering what's a programming language/ framework for server side programming that best mimics or closely resembles objective-c and the cocoa framework? I have never programmed server side apps before so that's why I am asking. Here's a list of languages/frameworks that I have heard about that might be close to cocoa.               Ruby - Ruby on Rails     PHP - not sure which fw     Python - Djano      Thanks


simple let binding vs constant function

I understand the reasons why I would prefer `let a = f(x)` over `let a() = f(x)`, especially when f takes is a long running function. I also think it is correct to say, that, considering lambda calculus origins of functional programming `let a()` is truly functional, while `let a` is not. Please correct me if I'm wrong on this. However I have no clue which expression will actually be better:               let a = 4      or               let a() = 4      Is there any reason I would prefer one over the other?


What are the differences between functional, operational and technical requirements?

I have done tasks based on Java, but my seniors assigned me to collect requirements for creating a globalized bug tracking tool. I have read many types of requirements from Wikipedia and the mindtools website, but it was very confusing. What are the exact differences between functional requirements, operational requirements and technical requirements?


REST API design for associations/aggregation

I am building RESTful API that manages persons and lists. There can be many `List` and many `Person` each with its own set of properties. `Person` can be in zero or more lists, `List` can contain zero or more Persons. I have implemented these operations for Persons and Lists:   * `GET api/Persons/` to get all persons   * `POST api/Persons/ {..}` to create new person   * `PUT api/Persons/123 {..}` to update person by id   * `DELETE api/Persons/123` to delete person by id To retrieve Lists person is in I would use `GET /api/Persons/123/Lists`, to retrieve all persons in List I would use `GET /api/Lists/234/Persons`. How do I design API to add Person to Lists, remove them from Lists? I thought about flattening `Person` to include `Lists` but then there will be other associations from `Person` and it seems unnecessary to transfer that mush information. I am using asp.net Web API 2 but I am asking in general what are the design principles in this case.


Separate methods or single method with if statement?

I'm working on a .NET application and I'm wondering if I should use separate methods to handle the click events of two different buttons. They essentially do the same thing, just on different objects on the form, in this case two separate maps. Same method:               Private Sub SingleButtonHandler(sender As Object, e As EventArgs) Handles btnToggleSatNew.Click, btnToggleSatOld.Click         If sender Is btnToggleSatNew Then             Me.NewMap.ToggleSateliteView()         Else             Me.OldMap.ToggleSateliteView()         End If     End Sub      Separate Methods:               Private Sub btnToggleSatOld_Click(sender As Object, e As EventArgs) Handles btnToggleSatOld.Click         Me.OldMap.ToggleSateliteView()     End Sub          Private Sub btnToggleSatNew_Click(sender As Object, e As EventArgs) Handles btnToggleSatNew.Click         Me.NewMap.ToggleSateliteView()     End Sub      What's the overhead of checking if the two objects are the same? Is one version easier to read than the other? Or should I be doing something completely different?


Getting some experience with asp.net

Hi I recently learned asp.net webforms and looking to get some experience under my belt using it.I found a website that provided some exercises here: asp.net exercises There weren't that many and I managed to finish them all.Are there any other website or books with similar exercises or tasks that could help me get some experience in using asp.net?


Python GUI and MVC - get variable from other module

I am trying to split my code into different layers: GUI, reading the GUI, creating input, calculating the model, interpreting data, creating view, sending the view to the GUI. Somebody told me about MVC and I would like to try to build my program that way. But I'm a little confused about how to exchange information between those modules. I'm running into problems with undefined global names and so forth. My model is written in matlab and consists of a simulation. The GUI is supposed to present the data in plots. My actual problem is: how to connect the different modules/classes/files to each other if they are supposed to be as independent as possible? For example: I'm creating a GUI in one file, like this:               # userinterface.py          class Userinterface(object):         def __init__(self, controller):             self.controller = controller             self.buildGUI()             return              def buildGUI():             # build lots of widgets and stuff             widget = tk.Thewidget(options=values, command=self.controller.onclick)      And call it my interface. In order to keep this file nice and clean, I would like to define all functions to handle button clicks and read fields in another file and I guess this is what you would call the controller part:               # main.py         import userinterface as gui              class Controls(object):             def onclick(self):                 # read values from widgets and do stuff                 var1 = GUI.widget_entry.get()                 # Call some other function with var1 etc.          if __name__ == '__main__':         GUI_controls = Controls()         GUI = gui.UserInterface(GUI_controls)      But how do I do to connect these two? In my example above, I'm handing over an instance of my Controls object. But then I read about Events too or Inheritance or subclasses. I'm rather new to programming and started all this 2 months ago, so I'm struggling sorting all these theories. If somebody could point out to me what the way of communication between my modules/files should be and what such a meeting-point looks like. Or just give me a link that I can study (like Javier did, although I'll have to read this thing more than once)


What is the middleware pattern?

Here's a Ruby poject that implements the middleware pattern. From the description, I have no idea what the pattern is, what it's useful for, and why other solutions wouldn't work as well. What is the middleware pattern, and what are its advantages and drawbacks?


Hide or Show singleton?

Singleton is a common pattern implemented in both native libraries of .NET and Java. You will see it as such: C#: `MyClass.Instance` Java: `MyClass.getInstance()` The question is: **when writing APIs, is it better to expose the singleton through a property or getter, or should I hide it as much as possible?** Here are the alternatives for illustrative purposes: Exposed(C#):               private static MyClass instance;     public static MyClass Instance     {         get {             if (instance == null)                 instance = new MyClass();             return instance;         }     }          public void PerformOperation() { ... }      Hidden (C#):               private static MyClass instance;          public static void PerformOperation()     {         if (instance == null)         {             instance = new MyClass();         }         ...     }      **EDIT:** There seems to be a number of detractors of the Singleton design. Great! Please tell me why and what is the better alternative. Here is my scenario: My whole application utilises one logger (log4net/log4j). Whenever, the program has something to log, it utilises the `Logger` class (e.g. `Logger.Instance.Warn(...)` or `Logger.Instance.Error(...)` etc. Should I use `Logger.Warn(...)` or `Logger.Warn(...)` instead? If you have an alternative to singletons that addresses my concern, then please write an answer for it. Thank you :)


How often should one update an app with a new version?

I've created my own iPhone app which is presently in the App Store. What is the maximum period that should pass without a new version update? What is the average time span between version releases? I'm asking this because I want to make sure that I'm giving the impression that my app is not being neglected. I'm currently working on an update, but as it is a one man show this could take a bit.


Algorithm for searching images within images

I can't google this question, because I can't come up with a good query, so let me describe what I want and maybe someone will be able to suggest a way forward for me. I need to solve the following problem: there is an list of jpg images. There is also one "source" jpg image. I need to find if this image is a cropped image from the list. I do not know what software was used to crop and have no control over what jpeg quality setting is used in the source image. I do realize that if the setting is to low the result can't be unrecognisable, but I still would like somehow be able to check the source image against each of the images in the list and get a "yes" if a match found. Ideally I'd like a .net library for this, but I also could implement it myself if only I knew a proper algorithm (and it's description is not 100 pages long). Since jpeg is lossy format I can't do bit by bit comparison, and even if I could it's not immediately obvious how to find the correct part of image to compare so this does not take too long, since the crop can be of arbitrary size in arbitrary spot of the image. In my case the crop is never resized or rotated, so it kind of makes it simpler, but I'm still not sure where to start.


Is it a good practice to wrap all primitives and Strings?

According to Jeff Bay's Essay on Object Callisthenics, One of the practices is set to be _"Wrap all primitives and Strings"_ Can anyone elaborate on this ? In languages where we already have wrappers for primitives like C# and Java. and In languages where Collections can have generics where you are sure of what type goes into the collection, do we need to wrap string's inside their own classes ? Does it have any other advantage ?


Is there any reason why most programming languages don't have '!>' (not greater than) and '!<' (not less than) operators?

I wonder if there is any reason - or if it is just an accident of history - that there are no `!>` and `!<` operators in _most_ programming languages? `a >= b` _(a greater OR equals b)_ could be written as `!(a < b)` _(a NOT lesser b)_ , that equals `a !< b`. This question struck me when I was in the middle of coding my own expression tree builder. Most programming languages have `a != b` operator for `!(a=b)`, so why no `!>` and `!<` ? _UPDATE:_   * `!<` (not lesser) is **easier to pronounce** than `>=` (greater or equals)   * `!<` (not lesser) is **shorter to type** than `>=` (greater or equals)   * `!<` (not lesser) is **easier to understand*** than `>=` (greater or equals) *because `OR` is binary operator you brain need to operate two operands (grater, equals), while `NOT` is unary operator and you brain need to operate only with one operand (lesser).


should singleton be life-time available or should it be destroyable?

Should the singleton be designed so that it can be created and destroyed at any time in program or should it be created so that it is available in life- time of program. Which one is best practice? What are the advantages and disadvantages of both?   EDIT :- As per the link shared by Mat, the singleton should be static. But then what are the disadvantages of making it destroyable? One advantage is it memory can be saved when it is not useful.


How do I set up MVP for a Winforms solution?

Question moved from Stackoverflow - http://stackoverflow.com/questions/4971048/how-do-i-set-up-mvp-for-a-winforms- solution I have used MVP and MVC in the past, and I prefer MVP as it controls the flow of execution so much better in my opinion. I have created my infrastructure (datastore/repository classes) and use them without issue when hard coding sample data, so now I am moving onto the GUI and preparing my MVP. **Section A**   1. I have seen MVP using the view as the entry point, that is in the views constructor method it creates the presenter, which in turn creates the model, wiring up events as needed.   2. I have also seen the presenter as the entry point, where a view, model and presenter are created, this presenter is then given a view and model object in its constructor to wire up the events.   3. As in 2, but the model is not passed to the presenter. Instead the model is a static class where methods are called and responses returned directly. **Section B** In terms of keeping the view and model in sync I have seen.   1. Whenever a value in the view in changed, i.e. `TextChanged` event in .Net/C#. This fires a `DataChangedEvent` which is passed through into the model, to keep it in sync at all times. And where the model changes, i.e. a background event it listens to, then the view is updated via the same idea of raising a `DataChangedEvent`. When a user wants to commit changes a `SaveEvent` it fires, passing through into the model to make the save. In this case the model mimics the view's data and processes actions.   2. Similar to #b1, however the view does not sync with the model all the time. Instead when the user wants to commit changes, `SaveEvent` is fired and the presenter grabs the latest details and passes them into the model. in this case the model does not know about the views data until it is required to act upon it, in which case it is passed all the needed details. **Section C** Displaying of business objects in the view, i.e. a object (MyClass) not primitive data (int, double)   1. The view has property fields for all its data that it will display as domain/business objects. Such as `view.Animals` exposes a `IEnumerable<IAnimal>` property, even though the view processes these into Nodes in a TreeView. Then for the selected animal it would expose `SelectedAnimal` as `IAnimal` property.   2. The view has no knowledge of domain objects, it exposes property for primitive/framework (.Net/Java) included objects types only. In this instance the presenter will pass an adapter object the domain object, the adapter will then translate a given business object into the controls visible on the view. In this instance the adapter must have access to the actual controls on the view, not just any view so becomes more tightly coupled. **Section D** Multiple views used to create a single control. i.e. You have a complex view with a simple model like saving objects of different types. You could have a menu system at the side with each click on an item the appropriate controls are shown.   1. You create one huge view, that contains all of the individual controls which are exposed via the views interface.   2. You have several views. You have one view for the menu and a blank panel. This view creates the other views required but does not display them (visible = false), this view also implements the interface for each view it contains (i.e. child views) so it can expose to one presenter. The blank panel is filled with other views (`Controls.Add(myview)`) and (`(myview.visible = true`). The events raised in these "child"-views are handled by the parent view which in turn pass the event to the presenter, and visa versa for supplying events back down to child elements.    3. Each view, be it the main parent or smaller child views are each wired into there own presenter and model. You can literately just drop a view control into an existing form and it will have the functionality ready, just needs wiring into a presenter behind the scenes.  **Section E** Should everything have an interface, now based on how the MVP is done in the above examples will affect this answer as they might not be cross-compatible.   1. Everything has an interface, the View, Presenter and Model. Each of these then obviously has a concrete implementation. Even if you only have one concrete view, model and presenter.   2. The View and Model have an interface. This allows the views and models to differ. The presenter creates/is given view and model objects and it just serves to pass messages between them.   3. Only the View has an interface. The Model has static methods and is not created, thus no need for an interface. If you want a different model, the presenter calls a different set of static class methods. Being static the Model has no link to the presenter. ### Personal thoughts From all the different variations I have presented (most I have probably used in some form) of which I am sure there are more. I prefer A3 as keeping business logic reusable outside just MVP, B2 for less data duplication and less events being fired. C1 for not adding in another class, sure it puts a small amount of non unit testable logic into a view (how a domain object is visualised) but this could be code reviewed, or simply viewed in the application. If the logic was complex I would agree to an adapter class but not in all cases. For section D, i feel D1 creates a view that is too big atleast for a menu example. I have used D2 and D3 before. Problem with D2 is you end up having to write lots of code to route events to and from the presenter to the correct child view, and its not drag/drop compatible, each new control needs more wiring in to support the single presenter. D3 is my prefered choice but adds in yet more classes as presenters and models to deal with the view, even if the view happens to be very simple or has no need to be reused. i think a mixture of D2 and D3 is best based on circumstances. As to section E, I think everything having an interface could be overkill I already do it for domain/business objects and often see no advantage in the "design" by doing so, but it does help in mocking objects in tests. Personally I would see E2 as a classic solution, although have seen E3 used in 2 projects I have worked on previously. ### Question Am I implementing MVP correctly? Is there a right way of going about it? I've read Martin Fowler's work that has variations, and I remember when I first started doing MVC, I understood the concept, but could not originally work out where is the entry point, everything has its own function but what controls and creates the original set of MVC objects.


Getting into Guava

So I recently started using Netty for my applications client/server communication and I discovered I loved the idea of listenable `Future`s. I wondered why I didn't know about Java being able to do this, and, sure enough, it cannot. After some searching I realized that this is a feature provided by Guava's concurrency tools, which got me skimming through it's user guide. It seems awesome, but I have some concerns:   1. I already have a decent amount of code that uses JDK concurrency. How hard will it be to migrate over?   2. What is the risk of starting to become a "Guava programmer" so to speak? How difficult will it be to bounce back and forth between doing things the Guava way and the core Java way?      * What potential harm could there be if, in an existing project, I write new classes with Guava classes without migrating the rest of the code over?    3. Is there a good guide for slowly beginning to use Guava features without having to stop doing my actual job to train myself for a few days/weeks?   4. Is there anything else I should know in advance that I haven't already thought of?


What is a development stack?

I am just now in the process of looking for jobs as I am about to graduate from college. An interviewer asked me what my current 'development stack' is? I know this is probably a really basic question. but could someone explain to me what a 'development stack' is? It isn't a term that gets used in school.


Should I re-download my server data after each change?

I have a simple DB editor that sits on the client. When I make changes via the editor, should I re-get all my data, as some of it is changed, or can I just do a check to make sure the procedure ran without error and assume my data is the same as the server?


Does a PHP programmer need ZCE certification?

I want to know if PHP programmers are validated with their Zend Certified Engineer certification. Around me some of them are saying it is very useful, some of them say no. Please clear my mind. Thanks in advance.


Determining the aggregates in this domain

I'm working on an ordering system where we receive tab delimited files that look like this (I removed most of the columns for clarity):                     OrderId   OrderLineId    BuyerName   BuyerAdress   RecipientName     RecipientAdress                   1            1         John        123, Street      Doe              25, street              1            2         John        123, Street      Doe              25, street              1            3         John        123, Street     Michael           11, France              2            1         Sam         66,Somewhere     Lily             25, Poland              2            2         Sam         66,Somewhere     Dave             25, Russia              ...      Applying **DDD** I primarily extracted few entities as shown in the image below: ![enter image description here](http://i.stack.imgur.com/YdOci.png) Some facts about the data received in the files:   1. An **Order** must have a **Buyer** and a **Buyer** must have an **Order** .   2. An **Order** contains at least 1 **OrderLine** and each **OrderLine** must belong to an **Order**.   3. Each **OrderLine** must have a **Recipient** and each **Recipient** must have an associated **OrderLine**.   4. The status history for the **OrderLine** must be tracked by the system (hence the **Line History** entity) **Questions:**   1. Which entity is the **aggregate root**? Most of the articles I read about DDD would put the **Customer** entity as its own aggregate root and the Order with its OrderLines as the other root. However, since the Buyer and Recipient can **NOT** exist by themselves how can they be treated as their own aggregate root?   2. Should OrderLines be a value object or an entity? I have seen some answers on numerous blogs suggesting the OrderLines should be a VO, but I don't see why it shouldn't be treated as an entity since its identity will be needed in its relation with the History entity.   3. Similarly the Line History should be modeled as entity or value object


Why HTTP Servers send information about themselves in HTTP Headers?

Most of the HTTP Servers I know send their application name and version in response http headers as default behaviour. (Nginx, IIS, Apache etc.) Of course we can change the default behaviour but I wonder why they send these information? Does it matter which HTTP Servers we use to the requesters? The only reason I can think of is to allow analytics services to keep track of which HTTP Servers are widely used by websites but otherwise these information are unnecessary for most of the requests and when an attacker figures out a specific version of a HTTP Server has a bug, he can easily find websites which uses that version and use that information against these websites.


What is the name of the part of the application, which manages people in general?

In each application there are concepts like users, customers, etc. and some part of the application tries to manage them. For example:               1. keeping the information of people, organizations, firms, etc.     2. managing users (people who work with the system)     3. managing customers (people who purchase goods/services)     4. distinguishing customers, from users, from ordinary people, etc.     5. ...      Do we have a universal term for that area of each application (that subsystem, that module, that whatever)? Or if I want to ask more precisely, can we package customers, users, people, organizations, etc. all in one module, and name it like X? Is this a correct taxonomy of subsystems? Update: Is **Entities** a good name?


Return multiple columns with SQL where GroupBy is on one column

I have noticed that all the columns in a SQL Select Query should be in a aggregate function, because otherwise the output value for group would be arbitrary. This makes sense. But when the other columns are same in value, it doesn't matter which is returned. Is there a way to specify this or just use MAX() or MIN() on varchar columns?


What is a good lightweight IDE that performs well in an Xterm window?

Our group is currently has a solaris server with eclipse installed on it. However, we need to run this from out desks using an xterm window. There is a delay with every action due to the weight of eclipse. Are there any other decent unix IDE's out there that are more forgiving on Xterm? The IDE is mostly used with our php projects (Though we do perl,ksh,python as well).


Company PC refresh, laptop or desktop?

My company is getting PC refreshes with a choice of to have a desktop or laptop. Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time? I'm not asking what would be better for coding, but more for convenience and productivity. I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.


Decoupling Components - Design

I have created a a number of non-trivial scripts in Python that do some long running reporting. At first these reports started off as scripts with a config file. Then I added in the a database component to persist data. Now I'm building a GUI to sit on top of all of them. My question relates to design. Each time I add an additional requirement, I find myself wishing I had decoupled the components of these scripts more than I did. When I consider how to recfactor my code to be more modular, I find that I need to pass quite a few references around the code, to the point that class initializers and function signatures have a ton of parameters. Also I find myself having parameters that are simply "pass-through", in that one object needs them only to pass to another object, doing nothing with them. What is the best way to approach modularity in Python while minimizing the need to pass references all over the place? I understand this is very conceptual and will vary by design, but I'm looking for guiding principles.


How can I build this payment receipt/booking application?

I'm planning to build a payment receipt/booking application for a media company with several branches in different locations. The application should be able to move data across the network/internet to a central database where the administrator/accountant in a different location will be able to see the result of the entire job for the day from each branch. Application will run on windows environment. Will be able to send result of the booking to a Point Of Sales printer for print output. Now, I'm confused about choosing the right programming language to accomplish this task. I'm between beginner/intermediate level in PHP, I know HTML/CSS and JavaScript. I have tried to do this in PHP but, I'm face with several challenges and I fear for the POS part since PHP application run on the web browser. I don't know if python will be best suited for this and how long will it take someone with my experience level to pick up python. Any suggestion will be highly appreciated.


Comment system sorting madness

I have a website in which I'm loading all of the users' comments by the number of likes they have. This has caused me some troubles. Let's say comment #1 has 5 likes, comment #2 has 2 likes, and the rest have 0 likes. We have the following comment id's:               1   2   3   4   5   6   7   8   9   10      Now let's assume someone else "likes" comment #4. Now the id's ordered are:               1   2   4   3   5   6   7   8   9   10      Let's assume I'm loading 3 comments at the same time. At scenario #1, I loaded comments:               {1, 2, 3}      Now when I click "load more," I load:               {3, 5, 6}      Loaded #3 twice! And comment #4 is never viewed. Problems also happen when a comment is deleted, but that's for later. How can I work around that? I saw websites that order by "likes" or something similar and I almost never encounter duplicates and/or missing comments. Any tips? Thanks.


Why didn't "cloud computing" offer appear earlier?

Cloud computing is a model of renting resources - servers and data storage. Both servers and data storage have been around for much more than a decade so far. Yet cloud computing offers only appeared several years ago. What's the deal here? What was the critical change that triggered massive adoption and massive marketing of cloud computing offers?


What are the harms of a cowboy coding style on a small personal project

Consider it is as a small personal project and is not intended to be maintain in future, what can be possible harm of cowboy coding style in such case?


monitor .net web applications

I am a junior dev, I am on a team with an internal ticketing system (more/less) I want to improve our monitoring so that I can tell when functionality on my app is broken. current alarms only alert if the web site is hard down. I want to alert if clicking on a link causes a 500. I am having a hard time finding other teams that are implementing what I am asking, and the only documentation I can find is the ASP.Net health monitoring overview from http://msdn.microsoft.com/library/bb398933.ASPX#Features and i was wondering if there are any examples you're aware of? The existing teams suggest making a timer that waits 2 minutes and does something to check health and reports up to another server if it's alive or not - how can I make a method that... more accurately checks health of my web app? is there a way to simulate a function and see if it breaks or not?


Inverse of Extract Interface refactoring

I'm working with a Java project that has several interfaces, many of which have only one implementation. (See related question) For a given revision of the software, one could think this acceptable because the interfaces were some plan for future extensions. However, when I look at the 200+ revisions over several years, those interfaces _never_ had more than one implementation, (nor were they used in unit-testing). It seems that in these cases of probable bloat (YAGNI) owing to the Interface Anti-pattern, it would be useful to apply the _inverse_ of Extract Interface. However, Inline Class (the supposed inverse according to refactoring.com) is not what I'm referring to. What's the name of the refactoring that removes an unused interface, substituting the sole class that implements it?


I am the single programmer working on a website handling both frontend and backend. Recently in my task list I have to provide a social news feed (activities among friends) which should summarize activities from different modules (at least 7 modules). It has taken at least 20-25 days for me to develop that. Remember in news feed every action can be performed right on the news feed + there must be some kind of aggregation which should aggregate similar activities e.g. User A, B and C liked your item. How can I convince my client that the task was complex and the time I took is fair?


Should I expose a "computed" value as a property or a method?

I have a C# class that represents a content type in a web content management system. We have a field that allows a web content editor to enter an HTML template for how the object is displayed. It basically uses the handlebars syntax for substituting object property values into the HTML string:
{{Title}}

{{Message}}
      From a class design perspective, should I expose the formatted HTML string (with substitution) as a _property_ or _method_? **Example as property:**               public class Example     {       private string _template;       public string Title { get; set; }       public string Message { get; set; }       public string Html        {         get         {           return this.ToHtml();         }         protected set { }       }            public Example(Content content)       {         this.Title = content.GetValue("title") as string;         this.Message = content.GetValue("message") as string;         _template = content.GetValue("template") as string;       }            private string ToHtml()       {         // Perform substitution and return formatted string.       }       }      **Example as method:**               public class Example     {       private string _template;       public string Title { get; set; }       public string Message { get; set; }            public Example(Content content)       {         this.Title = content.GetValue("title") as string;         this.Message = content.GetValue("message") as string;         _template = content.GetValue("template") as string;       }            public string ToHtml()       {         // Perform substitution and return formatted string.       }       }      I'm not sure from a design standpoint does it make a difference or are there reasons why one approach is better than the other?


How does assembly relate to machine/binary code. For example here is how to print to the screen in mikeOS(a small pure assembly OS), mikeOS it uses NASM to assemble.               BITS 16         ORG 32768         %INCLUDE 'mikedev.inc'          start:         mov si, mystring         call os_print_string              call os_wait_for_key              ret              mystring db 'My first MikeOS program!', 0      Where os_print_string and os_wait_for_key are defined as               os_print_string     equ 0003h   ; SI = zero-terminated string       and               os_wait_for_key     equ 0012h   ; Returns AL = key pressed      in mikedev.inc respectively and defined as               os_call_vectors:         jmp os_print_string     ; 0003h      in kernal.asm Now nasm must do a lot more work under the scene when assembling, I have no idea what. In other words assembly language is a wrapper to some degree to machine code just as say C is a wrapper to assembly. If I said cout >> "Hello World" for example in C++, this is then compiled into it's assembly equivalent and them assembled into machine code. So I am trying to understand out how 0003h and 0012h seem to dictate everything that is going on when printing to the screen. How do these two values, a) Tell the CPU/PC system which bus to send the corresponding bytes that represent the required string to the monitor bus and not say to the sound card. b) In this case the string is sent to the monitor, obviously, now my understanding is that you have a frame buffer that can store a maximum number of bytes. So say the resolution of your screen is set at 1024 x 768 which is 786432 pixels and a refresh rate of 60hz on the screen, therefore the FB will contain this number of byte values and hence will be sending this many bytes to the monitor every 1/60 sec. The first byte in the FB corresponding to the first pixel on the screen and the last to the last on the screen etc. So how does the CPU/GPU know which byte to put in which position in the FB. It's like saying to the GPU 'ok I need this pixel at coord (245,232) green so I will leave it to you to put this pixels value in the correct position in the FB' etc. How does this work.


How to correctly design NoSql database schema?

I would like to learn something more about NoSQL databases, so I've chosen to create a new project from scratch to handle football results. In my traditional relational database, I have tournaments, teams, results and class tables. All are obviously related. What might be a good approach for designing a project like this, using a NoSQL approach instead?


Manager keeps changing requirement specification after every demo.

## Background of my working environment My manager has no background or understanding of computers or software whatsoever. It is highly likely he hasn't seen code in any form (not even from a physical distance of 10 feet or less) in his life. There is _no one_ who understands the complexity of what I am asked to implement. To the point that if I semi-hardcode no one would know. On Joel's test we score an unbelievable score 0. ## The problems   * The manager and at times other "senior" keep changing the requirement specification. Changes which, if good engineering be done and not patchy "fixes", require change in the underlying design.   * There is _absolutely no one_ who looks at code (probably because no one knows how to, or even if it should be done) which means no one will ever be able to:      * Appreciate the complexity of the problem or the elegance of the solution.     * Suggest improvement to the approach.      * Appreciate the quality of the code.     * Point out where the code can be improved.   * A lot of jargon is used which makes sense grammatically but fails to make any sense any other way.   * Doesn't feel, behave or work like a software company. ## The question What should be done? _Especially regarding there being no one who would point out improvements in my code._ ## Update To answer HLGEM's (and possibly others) question about what I've done to try and fix it. I offered to set up Redmine and introduce source control to everyone. I said I would recommend distributed (git or mercurial) but will also talk about centralized ones and let the team decide. Response was that things are being done and will be done within weeks. Haven't seen that nor am I aware if other parts of the company use it.


Fetching instructions from memory

So, I am a noob in assembly language and machine instructions. When the discussion came up as to how funtion calls are implemented at the processor level, someone said that the `CALL` instruction pushes the address of the next instruction to be executed on the stack before updating the `EIP` and then someone asked how do we know the address of the next instruction. And then someone asked while `EIP` points to the current instruction in memory how does the processor know how many bytes from `EIP` need to be read so that the whole instruction is read. I assumed that all instructions are fixed length so the processor would read those many bytes as would constitute the instruction and then the decoding process would determine how many more bytes need to be read to fetch the operands. However when searching about the instructions I came to know that the instruction sizes vary. So we are back to the same question: How does the processor know the number of bytes to read to get the instruction from memory to the instruction cache?


does anyone know how to use the PyQt 'uic' module method 'compileUiDir'?

I don't find the docstring to be very clear:               def compileUiDir(dir, recurse=False, map=None, **compileUi_args):         """compileUiDir(dir, recurse=False, map=None, **compileUi_args)              Creates Python modules from Qt Designer .ui files in a directory or         directory tree.              dir is the name of the directory to scan for files whose name ends with         '.ui'.  By default the generated Python module is created in the same         directory ending with '.py'.         recurse is set if any sub-directories should be scanned.  The default is         False.         map is an optional callable that is passed the name of the directory         containing the '.ui' file and the name of the Python module that will be         created.  The callable should return a tuple of the name of the directory         in which the Python module will be created and the (possibly modified)         name of the module.  The default is None.         compileUi_args are any additional keyword arguments that are passed to         the compileUi() function that is called to create each Python module.         """      with regards to the map keyword argument and there is no simple example to go with it. Is it expecting a map argument? as in:               uic.compileUiDir("ui/", map=("ui/", "../widget/test.py"))      and how is it formed? I basically have a few `.ui` files in the `ui` directory and wish to compile them and place the resulting `.py` files in another directory called `widget`. They have names like `test1Widget.ui`, `test2Widget.ui`, etc. and I would like for them to be renamed to `test1.py`, `test2.py`, etc. Can anyone give me some pointers please?


What is the pass mark for MS exam (particularly 70-515)

I am looking at taking the 70-515 (web apps with .net4) exam soon, and I am wondering what the pass mark is? The training material's test exams set the pass mark at 80%, but from past experience (taking 1.0 exams 6 years ago) I thought it was only 70%. Also, can anyone confirm if the number of questions on the exam is 45? Thanks.


Can compilers check whether certain axioms hold for a user defined type?

Suppose the following type is defined (C++ syntax, can be conceptually applied to any statically typed language.)               class T {        int val;        friend bool operator<(const T& lhs, const T& rhs) {           return lhs.val < rhs.val;        }        // Ideally, if we should make them "friends"        // Also, this doesn't make them belong to the type itself as they're not member functions        friend bool operator>=(const T& lhs, const T& rhs) {           return !(lhs < rhs);        }        // Also the following implementation is interesting        friend bool operator>=(const T& lhs, const T& rhs) {           return lsh.val >= rhs.val;        }     };      So, the compiler can definitely check whether T supports operator< or operator>=, it can just look up the declaration.   This gets more complicated should these be defined as "friends" instead of member functions, but it can be done as far as I'm concerned. However, can the compiler check whether the "common axiom of sorts" hold? (Can as in is it possible to check this in all scenarios? Doesn't matter whether or not this would be standard-compliant.) Say:   not (a < b) == a >= b Should we define one in terms of the other, it is definitely possible in this particular scenario, but this is naturally not the only axiom that needs to be checked, what about:   (a > b) => (b < a)   and it's also not necessary (unfortunately) to define our behaviour in terms of something that has already been defined. And sometimes it wouldn't be even possible. So, if the compiler can check whether certain axioms hold, how? Generating random values from certain ranges? Is it possible to devise and proof correctness of such ranges? This is mainly related to C++ concepts that unlike C++ concepts lite, should also be able to "support axioms", whatever that means, I just can't see a clear way as to how they can be enforced. Or will the creator of the type have to state what axioms his class obeys? C++ dropped the "concept maps" as far as I know.


How to set up variable installation directory?

I have a couple projects that depend on additional files, like images or config files. When compiling and installing a programs like `Okular` with `cmake`, I can specify an installation directory and let `make install` install to that. Somehow, that program will figure out that all its dependencies are within that folder, not withing the main Linux file system. So far, I had absolute paths, like `/etc/config.ini`. The problem is that I cannot test the program without it installing it to my system any more. How can I do that easily in C++ and Python?


C# Design, many properties, complex constructor and equality

I'm still a relative novice with OOP, so I am still trying to understand some of the best practices for how to design "good" objects. I know this question is probably a rather subjective, which is why I am here rather than on stackoverflow. I am designing an object that will have 20 separate string properties, none of which are required. These constraints are fixed and cannot be changed as it is an implementation of an outside data source that I have no control over. The design problem I am running into is how to effectively construct an instance of the object and be able to compare equality by comparing each field without violating normal best practices.   * A 20 argument constructor seems very wrong, especially since every field is a string, and there are cases where many of them will be null. I could use the optional arguments in C#4 to reduce the number of arguments that are actually called, but since everything is a string, I would have to use named parameters when calling the constructor, and that seems that it would be even uglier.   * I have thought about trying to group the properties into smaller classes, but the most logical grouping still has an object with 10 properties, and at least half of the remaining properties have no logical grouping.   * I could give each property a public setter, but that would make the object mutable, and thus complicate matters for overriding `GetHashCode()`. And I really don't need the object to be mutable. Once it is built, there should never be a reason to change it, but I don't want to rely on that because who knows what someone will try to do with it.   * Implementing `IEquatable<T>` is a possibility for the equality test, but my understanding is it is recommended to also override `Equals(object obj)` and `GetHashCode()` when implementing `IEquatable` so all `Equals` methods have the same behavior. Is this an edge case where overriding `Equals` without overriding `GetHashCode` should be done? I don't intend on using this object as a key in a dictionary or as a member of a `HashSet`, but I can't predict what someone else would try to do in the future. Or should I just abandon the idea of doing an equality comparison on all of the properties with Equals and implement my own `Compare()` method? Or is there a better method for building the object that would allow it to still be immutable without having to pass all of the arguments through a constructor or a method? EDIT: In response to Sign's comment, the purpose of the object is ultimately to be able to compare the data from the outside data source to our internal data to ensure it is accurate. Both data sets contain address information, but they are broken up differently. The internal data, is generally stored as a typical address (Street, City, State, Postal Code, County, Country), but there are variations when you have a suite/apartment # or a floor in a building. The external data is broken down even further into smaller pieces. So this object is supposed to be a common link between the 2 data sources and allow the user to compare like fields for equality. EDIT #2: Ultimately, I chose Doc Brown's answer because a modified version of his dictionary idea (with Enums as Keys instead of strings) was the simplest way to go without having a messy constructor and still provide the immutability I was hoping to have. In the long term, I am going to experiment with some of Oliver's suggestions as some of his edits did have a lot to offer.


How to do a login page for third party service without letting them sign on?

We have a unique situation (at least for me, first time seeing this). We have a web form where accountants can fill in requests and that part is taken care of. But after their login we redirect them to a third-party website where we need more information from them. The process is crazy right now since we have to give our account login info to all people filing with us. So is there a way in PHP or any other solution where we can after that form on our website auto login with our information to that third party website in a way that our credentials are not visible to the users using the service?


My Asp.net MVC is running like a dodo ! Any recommendations

Following is the Url for my website, http://www.price-tag.org . If you visit any category link, you will see it performing very slow. For example, if you visit http://www.price-tag.org/Store/Section/Computers , you will see a lag before the sub categories are loaded. This is just the very first phase and i have just added few categories to the database and nothing much. If it's working like this in the very beginning, what will happen when I start adding products. I am using Entity Framework Code-first approach. Following is the code for one of the action that retrieves the list of categories.               PriceCompareEntity pe = new PriceCompareEntity();         //         // GET: /Store/     public ActionResult Section(string id)     {         if (!string.IsNullOrEmpty(id))         {             var catsAndSub = pe.Categories.Where(cat => cat.Name == id).FirstOrDefault();             if (catsAndSub == null || catsAndSub.ParentCategoryId != null)             {                 return View("NoSuchRootCat");             }             else             {                 ViewBag.Title = catsAndSub.MetaTitle;                 ViewBag.Description = catsAndSub.MetaDescription;                 ViewBag.Keywords = catsAndSub.MetaKeywords;                 return View(catsAndSub);             }         }         else         {             return View("NoSuchRootCat");         }     }      I am really worried and bit disappointed. After so much of hard work for last month or two, the results aren't any good. If things are going to be this slow, my whole project will sink. Can't imagine how slow will it be if i add a few hundreds of products to the site. Nobody's gonna bother visiting a dodo website. Have I done something wrong in the development ? And What can i do to get things right and straight. While surfing net, i came across web cache and other stuff, but they are very advanced and need quite bit learning. Besides, my website isn't any facebook or SO with millions of user so going that advanced into the subject seems a far cry and will take a lot of time to get things done. **Update** I have taken down the website, so links might not show the original content.


When using MVVM, should you create new viewmodels, or swap out the models?

Say I have a viewmodel like this:               public class EmployeeViewModel     {         private EmployeeModel _model;              public Color BackgroundColor { get; set; }         public Name         {             get { return _model.Name; }             set             {                 _model.Name = value;                 NotifyPropertyChanged(Name);             }         }     }      So this viewmodel binds to a view that displays an employee. The thing to think about is, does this viewmodel represent an employee, or a "displayable" employee. The viewmodel contains some things that are view specific, for instance the background color. There can be many employees, but only one employee view. With this in mind, when changing the displayed employee, does it make sense to create a new EmployeeViewModel and rebind to the view, or simply swap out the EmployeeModel. Is the distinction even important, or is it a matter of style? I've always leaned toward creating new viewmodels, but I am working on a project where the viewmodels are created once and the models are swapped out. I'm not sure how I feel about this, though it seems to work fine.


Some problem about QT when using Qtablewidget

QApplication a(argc, argv);         Qt_test w;         QTableWidget * table = new QTableWidget(&w);         table->setRowCount(1);         table->setColumnCount(3);         table->setGeometry(QRect(30,30,340,140));         QPushButton * btn = new QPushButton("btn1");         table->setCellWidget(0,1,btn);     //      //  table->removeRow(0);     //      table->setRowCount(3);         table->setCellWidget(0,1,btn);         w.show();         return a.exec();      This is my code ! and what makes me confused is that : the table is blank without the expected button !


Is it fine for a class that creates objects to delegate them?

I have a large list of intercommunicating components; so I decided to have one class create all of them and then subsequently delegate them to other classes to facilitate finer tweaking and wiring together. By "finer tweaking", I mean that the components are modified to their final state; and by "wiring together" I mean that components are given a way to communicate in a specific manner. After they are all wired together, I send all the components over to an organizer to be properly organized into a GUI. I read somewhere that a class should only create objects or use them, but never both; so, I am trying to follow that and also limit each class's responsibilities. This initializer/delegator class does both initializing and delegating, so **should I further split it into an initializer and delegator?**


Taking too long to return results MySQL

I am confused why do the server is taking too much time in execution of a following query:               SELECT tbl1.Column1 FROM Table1 AS tbl1      INNER JOIN Table2 AS tbl2 ON tbl2.Column4 = tbl1.Column1      It took about 20 minutes to return the results. MySQL config (my.ini) file looks like the following:                   [mysql]              # CLIENT #         port                           = 3306         socket                         = X:\wamp\bin\mysql\mysql5.5.8\data\mysql.sock              [mysqld]              # GENERAL #         user                           = mysql         default-storage-engine         = InnoDB         socket                         = X:\wamp\bin\mysql\mysql5.5.8\data\mysql.sock         pid-file                       = X:\wamp\bin\mysql\mysql5.5.8\data\mysql.pid              # MyISAM #         key-buffer-size                = 32M         myisam-recover                 = FORCE,BACKUP              # SAFETY #         max-allowed-packet             = 16M         max-connect-errors             = 1000000              # DATA STORAGE #         datadir                        = X:\wamp\bin\mysql\mysql5.5.8\data\              # BINARY LOGGING #         log-bin                        = X:\wamp\bin\mysql\mysql5.5.8\data\mysql-bin         expire-logs-days               = 14         sync-binlog                    = 1              # CACHES AND LIMITS #         tmp-table-size                 = 32M         max-heap-table-size            = 32M         query-cache-type               = 0         query-cache-size               = 0         max-connections                = 500         thread-cache-size              = 50         open-files-limit               = 65535         table-definition-cache         = 4096         table-open-cache               = 4096              # INNODB #         innodb-log-files-in-group      = 2         innodb-log-file-size           = 128M         innodb-flush-log-at-trx-commit = 1         innodb-file-per-table          = 1         innodb-buffer-pool-size        = 2G              # LOGGING #         log-error                      = X:\wamp\bin\mysql\mysql5.5.8\data\mysql-error.log         log-queries-not-using-indexes  = 1         slow-query-log                 = 1         slow-query-log-file            = X:\wamp\bin\mysql\mysql5.5.8\data\mysql-slow.log      Both Tables have primary keys. Regards, F. Ahmed


Managing threads in Java with a good pattern

This morning I began writing a minimal chat using Java socket and threads but it took some minutes for me to experience a lot of problems in the MVC management. Currently I have 3 classes:   * Main, this is just the main class used for starting the Control.   * ChatController, I use this for managing Model and View classes (this is a Controller class).   * Host, a class containing a Socket attribute and two Scanner and PrintStream attributes for reading and writing to and from the socket. The problem here is which class extending from Thread to let the program both read and write features concurrently. My professor told me to extend the ChatControl (hence, the Controller) class, but I think it is too much hard- coding (and also, I don't like the method/attributes inherited from Thread to be visible from the ChatController class). So, is it correct extending the Control class from Thread for managing the thread or should I consider to implement another class for tasking this problem (or even trying some other patterns)? If you need some source, find it on pastebin.


Extracting lambda expressions from linq queries and readability

Every now and then when I have a complex lambda, I do something like this:               Func<SomeObject, bool> equals = o =>         o.ID == someID && o.Name == someName && IsAdd || ...     var myList = MyThings.Where(equals).ToList();      Let's assume that the logic in equals can not be simplified. Does extracting the lambda from the linq query improve, or reduce readability? The alternative being:               var myList = MyThings.Where(o => o.ID == someID && o.Name == someName && IsAdd || ...).ToList();


Application program interface

We usually test the web API s manually using J meter. Is it possible to create a software that will automatically create test scripts for the tests, and perform the testing ? I want to use J meter in the back end as the testing software.


In software, what does the term "Embedded" entail?

So I've been looking at furthering my knowledge into embedded and lower level hardware programming, however, every time I look for jobs that mentions _"embedded"_ it's always high level stuff. To me, that doesn't make a whole lot of sense. So what exactly does "embedded" entail? When I think of _embedded_ I think of lower-level microcontroller programming and such. If _embedded_ is not the proper title for this, then what should I be searching for?


How to Write Unit Tests When One Fix Will Make Many Failing Tests Pass?

I have two test cases to test a fix to code that is using the wrong criteria for selecting objects from a collection:   1. Given one object in the collection matching the bad criteria, ensure that no object is returned.   2. Given two objects in the collection, with the later one matching the bad criteria, ensure that the earlier object is retrned. Right now, both of these tests will fail. The problem is, as soon as I make the fix, both tests will pass. Is this ok? I thought we needed a _single_ failing unit test before writing the code. I haven't heard it's ok to have multiple failing unit tests before writing code.


Can you share an explanation or experience that gave you clarity about how to use SQL SELECTS?

I have been programming for a long time, like 13 years (only professionally for about 4). I've become familiar with things like QBasic, Visual Basic, C#, .NET, Java, C, C++, Javascript, JQuery, etc. I can tackle almost any code and figure out what is going on or fix it, as well as create new solutions. However, no matter how hard I try, or how many times various DB people try and explain to me a solution for SQL, or how to create a SQL query that selects the things I want, I can't seem to 'get it'. What I mean is, I can understand why the new or modified query they write for me works, but I can't seem to get it into my head enough so that I can figure this out on my own or write my own complex queries. Was there any experience you had, or explanation you heard, that gave you enlightenment about SQL? This is not a yes or no question though, PLEASE share it!


Why are interfaces called interfaces?

From what I understand so far, an interface is a list of methods that need to be implemented by whoever wishes to use that interface. If so, would it make any difference to call it a specification instead of interface, or is it more sophisticated than a specification?


How does "dogfooding" work?

I heard that twitter practices "dogfooding," meaning that they use their own API for the website. However, I don't really understand how that's true. When I use Firebug, I see that all the AJAX calls are made to some URL like:               https://twitter.com/{username}/{whatever else}      Rather than:               https://api.twitter.com/1.1/statuses/...      If they are using different URL's, how are they using their own API? I think I have the wrong notion of what an API is... Also, how would it work with OAuth? Do they validate themselves? How does one use his/her own API ("dogfood")?


Creating deterministic key pairs in javascript for use in encrypting/decrypting/signing messages

So I have been searching everywhere and havn't been able to find anything with the sufficient information I need.. so Im a bit stumped on this one at the moment What I am trying to do is create a public/private key pair (like PGP) upon a users account creation, based on their passphrase and a random seed. The public key would be saved on the server, and ideally the private key would never be seen by the server whatsoever. The user could then sign in, and send a message to another user. Before the message is sent, the senders key pair would be re-generated on the fly based on their credentials (and maybe a password prompt) and used to encrypt the message. The receiver would then use their own re-generated private key to decrypt said message. The server itself should never see any plaintext passwords, private keys or readable messages. Bit unsure how on how I could go about implementing this. Iv been looking into PGP, specifically openPGP.js. The main trouble I am having is being able to regenerate the key-pair based off a specific seed. PGP seems to have a random output even if the inputs are the same. Storing the private key in a cookie or in HTML5 storage or something also isnt really an option, too unreliable. Can anyone point me in the right direction?


Either I'm not confident I just don't know anything

My name is Sael and I'm 14 years old. Since I was 12 and I got my first computer I instantly go interested in making games. So of course like any other I googled it, got discouraged and forgot about it for a few months. When I was 13 I decided to continue programming, and decided that java would best suit me. Now after a year, I have a basic understanding of java and how it works (it just clicked instantly one day). Anyways, my problem is that I know how I'm going to make a simple game in my head, but as soon as I click that "New Project" button on eclipse, I'm instantly lost and can't figure out where to start. I can't do much without a tutorial beside me since my mind is so dependent on it. So here's the question : what can I do to get past this problem of mine, and have any of you felt like this before?   * sorry if my English is a bit incorrect, Spanish is my main language* _I've made Minecraft mods before_


Web Services and code lists

Our team heavily discuss the issues how to handle code list in a web service definition. The design goal is to describe a provider API to query a system using various values. Some of them are catalogs resp. code lists. A catalog or code list is a set of key value pairs. There are different systems (at least 3) maintaining possibly different code lists. Each system should implement the provider API, whereas each system might have different code list for the same business entity eg. think of colors. One system know [(1,'red'),(2,'green')] and another one knows [(1,'lightgreen'),(2,'darkgreen'),(3,'red')] etc. The access to the different provider API implementations will be encapsulated by a query service, but there is already one candidate which might use at least one provider API directly. The current options to design the API discussed are:   1. use an abstract code list in the interface definition: the web service interface defines a well known set of code list which are expected to be used for querying and returning data. Each API provider implementation has to mapped the request and response values from those abstract codelist to the system specific one.   2. let the query component handle the code list: the encapsulating query service knows the code list set of each provider API implementation and takes care of mapping the input and output to the system specific code lists of the queried system.   3. do not use code lists in the query definition at all: Just query code lists by a plain string and let the provider API implementation figure out the right value. This might lead to a loose of information and possibly many false positives, due to the fact that the input string could not be canonical mapped to a code list value (eg. green -> lightgreen or green -> darkgreen or both) What are your experiences resp. solutions to such a problem? Could you give any recommendation?


Minimize useless tweaking of a numeric app

I'm developing a numeric application (nonlinear optimizer), with a zillion knobs to tweak and rising. It's not my first foray into this domain, but this time there are even more variables in the code and I'm on a tight schedule. Don't want to waste time fiddling. Days or even months can potentially be wasted adjusting variables, recompiling, and reprocessing benchmark datasets. The resulting data is viewed and trouble spots are checked. The overall quality of the solution is reported by the program but the meaning of the report could change over time. (Numeric units for the report are one thing I'm trying to nail down.) One main problem is organizing result files to identify each with specific code changes. Note taking can be a pain, is there software to help with this? Are there agreed best practices to making this kind of development cycle reliably move forward? The solver package converges to its optimal solution with mechanical determination, but I'm all too familiar with the way an excess of design decisions can mire development.


Reusing open-source code that doesn’t specify a license

I am creating a module for a CMS. I found a PHP code in github that does some work for me. The author has not clearly stated the license for the code. Since it is in github and is publicly available, can I use the code in my module or should I get the author's written permission? I am planning to sell my module for a small price.


Why are some minor update versions of Java skipped?

Up until around January 2013, the minor updates of major Java versions were always consecutive: 6u30, 6u31, 6u32, 6u33 and so on. The same is true for Java 7 updates. But, starting around January or February 2013, some minor version numberings were skipped. Take a look here: http://en.wikipedia.org/wiki/Java_version_history#Java_7_updates As you can see, the minor updates are 7u10, 7u11, 7u13, 7u15, 7u17, 7u21, 7u25. Where did 7u12, 7u14, 7u16 etc. dissapear ? Was there a specific reason why they were skipped ? If they were actually faulty and couldn't be released, then:   * how come there is no significant uptake in the time-gap between them ?   * how come up until January/February this year this never happened, but is constantly happening ever since ? I tried searching for an answer to this, but couldn't find anything. So I thought someone here might have a clue about this.


Keys as attributes for ajax calls

I have been told its kind of a bad idea to use a key as an attribute of an xml tag. I find the very handy for ajax as i can just stick the key i need in what ever element is being clicked,changed, or whatever. I can see how this is a security risk but have only used the tactic in internal apps. On external application/sites what would be a better way to handle this. I would assume just embedding another unique field that isn't numeric. Basic example... I have a button than when pressed would update the price of an item in the database. Then using JS on button press i would take the id and pass it back to the controller to update the item.


best way to quickly stash your cognitive state when you just can't avoid interruptions

I don't even know if this question makes sense ... but let me let you grok it... > _**imagine ..._** _You're totally absorbed into some programming > thought/idea/concept, your brain is in it's most active state thinking up a > solution to a problem, or asJoel Spolsky puts it -- you're deep into your > "zone" -- AND, suddenly someone or some event breaks your engrossment -- > something that you just can't avoid, something you have to attend to._ > **_... imagination complete .. back to reality_** Something that can break your concentration can be...   * you're summoned for an urgent meeting   * your code broke the daily build and your colleague is calling you   * you just recalled something you had to do but forgot doing it   * your teammate has some exciting news to break and insists you to listen   * your girlfriend (or boyfriend) has just come over Now assume you've got only 5-10 minutes before you **_have to_** leave what you were deeply into, and entertain the interruption. My question is -- how do you, quickly "save" the state of mind you were in, when the diversion came. Do you write it in "some form" on a paper or computer, or do you just "remember" it somehow. How do you salvage those exact thoughts within 5-10 minutes so that later on when you come back you can catch up right from the "point" you left. It often so happens to me that i just can't recollect those exact thoughts i was thinking before the blow -- and i feel like i've lost a good idea or solutions to a problem. i try to think retroactively trying hard to get to that SAME cognitive state that had me excited about an idea -- but i get frustrated not being able to "get there". does something like this happen to you. how do you "recover" from this? _**\-- UPDATE --_** My main concern is not code -- it's those "abstract ideas" that haven't been yet converted into code that i need to "save" somehow


Client Request Explanation of "Benefits" as part of consulting fee

I gave my rate to my client with a simple breakdown as requested. I listed out the components of my rate 1) Salary 2) Benefits 3) Overhead (tax, suppliers, etc etc) The client is ok with 1) and 3) But he wants a further breakdown of 2) Benefits (incl. vacation, sick days, insurance, etc) I am just using a very conservative and typical rate for benefits. Is this request typical? How should I say no? Thanks


Fractional and Cartesian Coordinates

I have a set of fractional coordinates. I also have a rotation matrix that operates on cartesian coordinates. Does anyone know how I could convert my rotation matrix so I can operate on the fractional coordinates? The fractional coordinates are functions of the basis vectors a,b,c and the corresponding alpha, beta, gamma. The following link explains how to do coordinate transformations. I'm just not sure about how to use the listed matrices to operate on the rotation matrix. http://en.wikipedia.org/wiki/Fractional_coordinates Any ideas? Thanks


Starting a new project and need ideas for handling Phishing/Brute Force attacks AND Logging access

I'm starting a brand new project. The main access from the client side app will be via an API written in ASP.Net MVC3.   I'm looking for discussions on how best to handle logging information for security access as well has how to handle Phishing and Brute Force.   On the Information side of things, I'd also like some ideas on what to keep track of to help me both better improve the application in the future and to be able to market it better.   Anyone got any suggestions or links?


Maximum project duration for Feature Driven Development Project

Is there a duration limit for FDD Project when those projects are likely to fail due external and internal factors? For example XP projects should kept short due the openess of the concept and dependents on the individuals in the team and lack of documentation which is vulnerable to disturbances like losing team members and so forth.


Does Groovy follow Tennent's Correspondence Principle?

Here's an interesting discussion of Tennent's Correspondence Principle, and a brief description from Neal Gafter: > The principle dictates that an expression or statement, when wrapped in a > closure and then immediately invoked, ought to have the same meaning as it > did before being wrapped in a closure. Any change in semantics when wrapping > code in a closure is likely a flaw in the language. Does the Groovy language follow this principle?


Why do PHP variables need to be preceded with a dollar sign?

I understand that all PHP variables need to be preceded by a dollar sign (e.g. `$someValue = 1`), but why is this the case? Why was this design choice made? The reason I ask is my girlfriend asked why when I mentioned that PHP variables need to begin with a dollar sign, and I realized I had no idea why this syntactic choice was made. Any ideas?


Is code commonly generated from UML?

So when I was at university I was educated on the benefits of UML and its future in code development. But from my industry experience, I've found that while we do use diagrams—ranging from ER diagrams, class diagrams, state diagrams, to work flow diagrams—all of it is for communication purposes. That is, I've never generated code automatically from diagrams, and from a communication standpoint, I generally try to keep my diagrams as simple and easy to understand as possible. But when I look at Visio and Enterprise Architect, it seems they have many different types of graphs, shapes, properties objects, most of which I don't use. Do people use UML to do more sophisicated things such as code or database generation?