Unit tests and language-native function calls

Is there a best practice for calling language-native functions when writing testable code? I have experimented a little with php code and have come up with two methodologies:   * create a wrapper class for all native functions and mocking this wrapper when writing tests   * using "namespace magic": calling all native functions without specifying the global namespace (`aFunction` in stead of `\aFunction`) and then writing a method stub in the given namespace during testing, which will result in the code to be tested using the stub instead of the native function Is there a more commonly used approach? What are the benefits and shortcomings of the most commonly used methodologies to test language-native function calls?


Is SQL declarative?

I ask because so many of the questions I see in SQL amount to: "This is slow. How do I speed it up"? Or are tutorials stating "Do this this way and not that way as it's faster". It seems to me that a large part of SQL is knowing just how an expression would be performed and from that knowledge chosing expression styles that perform better. This doesn't square with one aspect of declaritive programming - that of leaving the system to decide how best to perform the calculation with you just specifying what the calculation should produce. Shouldn't an SQL engine not care about if you used `in`, `exists` or `join` if it is truly declarative shouldn't it just give you the correct answer in reasonable time if possible by any of the three methods? This last example is prompted by this recent post which is of the type mentioned in my opening paragraph. **Indexes** I guess the easiest example I could have used relates to creating an index for a table. The gumph here on w3schools.com even tries to explain it as something unseen by the user that is there for performance reasons. Their description seems to put SQL indices in the non-declarative camp and they are routinely added by hand for purely performance reasons. Is it the case that their is somewhere an ideal SQL DB that is much more declarative than all the rest but because it is that good one doesn't hear about it?


"Middle ground" architecture for client-server iOS apps?

I see two obvious approaches to the architecture for an iOS app which needs to talk to a server to do its job. **Pretend to be a web browser** Under this approach, the app fetches a chunk of data (typically JSON) from the server in response to a user action (navigating to a new view controller, tapping an "Update", whatever), puts up a spinner or some other progress indicator, then updates the view when the request completes. The "model" classes are mapped directly from the incoming JSON and possibly even immutable, and thrown away when the user moves off the screen they were fetched to populate. Under the "pure" version of this approach you set the appropriate headers on the server and let NSURLSession and friends handle caching. This works fine if you can assume the user has fast, low-latency network connectivity, and is mostly reading data from the server and not writing. **Sync** With the "sync" approach, the app maintains a local Core Data store of model objects to display to the user. It refreshes this either in response to user action or periodically, and updates the UI (via KVO or similar) when the model changes. When the user modifies the model, these changes are sent to the server asynchronously; there must be a mechanism for resolving conflicts. This approach is more suitable when the app needs to function offline or in high latency/slow network contexts, or where the user is writing a lot of data and they need to see model changes without waiting for a server round-trip. * * * Is there a third in-between way? What if I have an app which is _mostly_ but not always reads, but where there are writes the user should see those updates reflected in the UI immediately. The app should be usable in low/no network situations (showing any previously cached data until a request to the server has time to respond.) Can I get the best of both worlds without going full Core-Data-with-sync (which feels heavyweight and is difficult to get right) but without also inadvertently implementing a buggy and incomplete clone of Core Data?


Best approach of testing ravendb database queries speed

Iv'e seached the internet for a while but am not able to find any examples how to test ravenDb query speed. What I'm trying to achive is to compare two session.query and find out witch of those two has the best performance speed. How can I do that? //Thanks EDIT: I'm buliding a mvc Notes-app were a user can create an account and save notes. Lets say I have these these two classes:               public class SingleNote : ContentPage     {         public string Header { get; set; }         public string Note { get; set; }         public string Category { get; set; }     }      And this one:                   public class LoginViewModel     {         [Required]         [Display(Name = "Username")]         public string UserName { get; set; }              [Required]         [DataType(DataType.Password)]         [Display(Name = "password")]         public string Password { get; set; }     }      Is it best to put a List of the users singleNotes in the LoginViewodel and store all the user notes there or should I put a property in the the SingleNote-ravenDocument that refers to the user. What I'm then trying to achive is to test these to diffrent type of queris and se witch of them gets the best performace speed. So, can I do some testing of that and compare these two queries witch gets best performance speed: Case 1: where I have put the prop string UserThatOwnsTheDoc in SingleNote- class               `var listOfSpecificUsersDocuments =             RavenSession.Query<SingleNote>()                     .Where(o => o.UserThatOwnsTheDoc == User.Identity.Name)                     .ToList();`      Case 2: where I have put the prop List SingleNotes in the LoginViewModel               var userDocumentWitchIncludesAListOfSingleNotes = RavenSession.Load<LoginViewModel>("UserName/1");


RSpec vs Test::Unit in Rails

I've never been really convinced of the advantages that you get by switching over to RSpec from Test::Unit in Ruby on Rails (despite reading from time to time about RSpec). What is it about RSpec that most Rails project seems to be using it? (some code examples clearly indicating advantages of one over the other would be much appreciated)


one single compressed js file VS compressed requirejs module files

I just started using requirejs and I love it. I have one concern though. I've been compressing all my js files into one single file. Even with requirejs optimizer, I need to load module files from the server time to time and I'm concerned with it. Performance and user experience wise, which one is better?


What factors should I consider when choosing names for identifiers?

What factors do I need to consider when choosing names for identifiers such as variables? I am concerned about space issues, i.e. extra memory consumption when choosing longer names. As an example, take these two variables:               bool noExp = true;     bool willNotExpireEver = true;      Each one will take up memory the size of `bool`. But what about the variable names? They are after all characters that have to be stored somewhere. Where does the space for them get allocated? Am I wasting pace by choosing longer names?


Map of functions vs switch statement

I'm working on a project that processes requests, and there are two components to the request: the command and the parameters. The handler for each command is very simple (< 10 lines, often < 5). There are at least 20 commands, and likely will have more than 50. I've come up with a couple of solutions:   * one big switch/if-else on commands   * map of commands to functions   * map of commands to static classes/singletons Each command does a little error checking, and the only bit that can be abstracted out is checking for the number of parameters, which is defined for each command. What would be the best solution to this problem, and why? I'm also open to any design patterns I may have missed. I've come up with the following pro/con list for each: **switch**   * pros      * keeps all commands in one function; since they're simple, this makes it a visual lookup table     * don't need to clutter up source with tons of small functions/classes that will only get used in one place   * cons      * very long     * hard to add commands programmatically (need to chain using default case) **map commands -> function**   * pros      * small, bite-size chunks     * can add/remove commands programmatically   * cons      * if done in-line, same visually as switch     * if not done in-line, lots of functions only used in one place **map commands -> static class/singleton**   * pros      * can use polymorphism to handle simple error checking (only like 3 lines, but still)     * similar benefits to map -> function solution   * cons      * lots of very small classes will clutter project     * implementation not all in the same place, so it's not as easy to scan implementations **Extra notes:** I'm writing this in Go, but I don't think the solution is language-specific. I'm looking for a more general solution because I may need to do something very similar in other languages. A command is a string, but I can easily map this to a number if convenient. The function signature is something like:               Reply Command(List<String> params)      Go has top-level functions, and other platforms I'm considering also have top- level functions, hence the difference between the second and third options.


Can the Strategy pattern be implemented without significant branching?

The Strategy pattern works well to avoid huge if...else constructs and make it easier to add or replace functionality. However, it still leaves one flaw in my opinion. It seems like in every implementation there still needs to be a branching construct. It might be a factory or a data file. As an example take an ordering system. Factory:               // All of these classes implement OrderStrategy     switch (orderType) {     case NEW_ORDER: return new NewOrder();     case CANCELLATION: return new Cancellation();     case RETURN: return new Return();     }      The code after this doesn't need to worry, and there is only one place to add a new order type now, but this section of code still isn't extensible. Pulling it out into a data file helps readability somewhat (debatable, I know):               <strategies>        <order type="NEW_ORDER">com.company.NewOrder</order>        <order type="CANCELLATION">com.company.Cancellation</order>        <order type="RETURN">com.company.Return</order>     </strategies>      But this still adds boilerplate code to process the data file - granted, more easily unit testable and relatively stable code, but additional complexity nontheless. Also, this sort of construct doesn't integration test well. Each individual strategy may be easier to test now, but every new strategy you add is addition complexity to test. It's less than you would have if you _hadn't_ used the pattern, but it's still there. Is there a way to implement the strategy pattern that mitigates this complexity? Or is this just as simple as it gets, and trying to go further would only add another layer of abstraction for little to no benefit?


Does a BSD-licensed project need a signed statement from each contributor?

Today I read on Fossil SCM's mailing list: > The problem with BSD is that you really should get a signed form from each > contributor stating that their contribution is BSD. This is automatic with > GPL, since releasing your contributions under a compatible license is a > prerequisite for viewing the code in GPL. This makes GPL great for a highly > collaborative environment, with lots of contributors. BSD is more permissive > (less burdensome) for readers, but that makes it a little tougher for > writers since they now have to send in some paperwork. Could someone explain why, and what are the possible consequences of not having such a signed statement from project's contributors?


WPF vs. WinForms - a Delphi programmer's perspective?

I have read most of the major threads on WPF vs. WinForms and I find myself stuck in the unfortunate ambivalence you can fall into when deciding between the tried and true previous tech (Winforms), and it's successor (WPF). I am a veteran Delphi programmer of many years that is finally making the jump to C#. My fellow Delphi programmers out there will understand that I am excited to know that Anders Hejlsberg, of Delphi fame, was the architect behind C#. I have a strong addiction to Delphi's VCL custom components, especially those involved in making multi-step Wizards and components that act as a container for child components. With that background, I am hoping that those of you that switched from Delphi to C# can help me with my WinForms vs. WPF decision for writing my initial applications. Note, I am very impatient when coding and things like full fledged auto-complete and proper debugger support can make or break a project for me, including being able to find readily available information on API features and calls and even more so, workarounds for bugs. The SO threads and comments in the early 2009 date range give me great concern over WPF when it comes to potential frustrations that could mar my C# UI development coding. On the other hand, spending an inordinate amount of time learning an API tech that is, even if it is not abandoned, soon to be replaced (WinForms), is equally troubling and I do find the GPU support in WPF tantalizing. Hence my ambivalence. Since I haven't learned either tech yet I have a rare opportunity to get a fresh start and not have to face the big "unlearning" curve I've seen people mention in various threads when a WinForms programmer makes the move to WPF. On the other hand, if using WPF will just be too frustrating or have other major negative consequences for an impatient RAD developer like myself, then I'll just stick with WinForms until WPF reaches the same level of support and ease of use. To give you a concrete example into my psychology as a programmer, I used VB and subsequently Delphi to completely avoid altogether the very real pain of coding with MFC, a Windows UI library that many developers suffered through while developing early Windows apps. I have never regretted my luck in avoiding MFC. It would also be comforting to know if Anders Hejlsberg had a hand in the architecture of WPF and/or WinForms, and if there are any disparities in the creative vision and ease of use embodied in either code base. Finally, for the Delphi programmers again, let me know how much "IDE schock" I'm in for when using WPF as opposed to WinForms, especially when it comes to debugger support. Any job market comments updated for 2011 would be appreciated too.


How to avoid halting of the JVM due to a deadlock in java?

I have read many websites talking about how to avoid and how to design etc. I completely understand those strategies. My question is based on the following preconditions:   1. You have a company with 1000's of developers.   2. There are different teams working on the same product but as modules.   3. New developers writing new code not knowing the overall system, please consider an Enterprise application.   4. High available software development where a downtime of 15 mins is considered as an SLA violation. I could write few more preconditions but I thought these could be strong enough to support my question about why I might need a recovering strategy for a "Deadlock" in a software. Please note that re-designing the modules whenever we find a deadlock is not realistic. Now this being said. Can someone take sometime to provide an input or brainstorm on an idea of how to resolve a deadlock if at all it happens, so that we can report it and move forward, instead of halting completely.   1. Run a deadlock detector that runs periodically to look for deadlocks in the system.   2. If a deadlock is detected, notify with an event to resolve the deadlock.   3. The deadlock event listener will then kick in and act upon the deadlocked threads.   4. For each thread identify the contention.   5. Write an intelligent algorithm that could either release the locks and kill the thread or release the locks and re-evaluate the thread.   6. In step 2 we handle the notification in multiple ways, out of which logging is one of the listener. I know how to go about steps 1,2,6. Will need help with 3,4 and 5. I know that Oracle RDBMS already has a deadlock detection and resolution strategy in place, I wonder if they would ever share their strategies in this thread :) Can't add my comment as an answer so adding it as a comment here. ================================================================= I completely understand the risk of killing the threads. I was 100% certain that I would get answers like this but I was also hoping that someone would suggest something new. I'll keep the thread open as there is no answer in here that I already do not know, thank you very much for trying though.


Do Makefiles Matter?

I'm currently working on a small library as a hobby project. I am the only one who actively codes for it, but a few of my friends have expressed interest in participating in the future. When using the library for my own purposes, I usually just add the appropriate source files to my project using an IDE. (E.g., dragging a `.h` and `.cpp` file into Xcode.) As the library grows in size and complexity, however, I've been trying to move towards a more professional approach to organization. I've considered setting up some sort of makefile that future participants can use to compile the library into a "monolithic" library file. This might be beneficial to me as well, since I code on multiple computers. Would such a venture be worth the effort? Note: I tried looking at the Boost library to see how they do things, but it's pretty difficult to navigate without any previous experience and I had trouble making sense of the structure.


Maximizing number of nested triangles

There is a finite set of points on a plane (about 1500 points in the current task). I need to construct triangles on those points such as each triangle lies completely inside one larger triangle: ![enter image description here](http://i.stack.imgur.com/GSvTE.png) Now I want an algorithm to maximize the number of such triangles. Where can I start? I think one of the ways would be to choose a "center" and to find three directions from this center with most point density near those directions. Or just choose an arbitrary center triangle manually and then iteratively choose a larger triangle with the least area or the least distance.


How can I convince my company to move to MVC?

I currently write web apps using asp.net web forms and getting my company to move to another technology is like [insert funny line here]. I would really like to start writing apps using MVC, but they fear any type of change. How is the best way to convince/ease them into using MVC? I guess this can go for moving to any new technology. ### Update Decided to go the rogue developer route and just started using it. I recreated a small app in MVC and learned the ropes that way, and moved up from there.


What method is the easiest/fastest way for developing Android Apps

Which one of these is the easiest/fastest choice for developing simple Android apps/games? I'm familiar with all this technologies.                  • Android SDK or NDK        • C# on MonoDroid platform        • Adobe Flash & Adobe AIR        • Corona SDK        • Converting tools like PhoneGap      Fundamentally, Could you explain adventages and disadventages of this methods.


Architecture diagram of a computer virus

I am looking for an architecture diagram of a computer virus. Does anyone have a link to a good example? **Edit** Looks like I am getting hammered with downvotes. I agree that there is no single architecture for a virus. But somethings must be included for a program to be a virus. Example for components in the SAD:   * Replication method   * Trigger   * Payload   * Hosts targeted   * Vulnerabilities targeted   * Anti detection method **Edit 2** Found a good example here: http://static.northpole.fi/download/1318959037124281/w32_duqu_the_precursor_to_the_next_stuxnet.pdf


Service to test app on all the iPhones?

I have some developers creating an iPhone app, often the app will not work on one type of iPhone even though it worked on another one using the same version of iOS. Therefore, I am looking for a service where I can test the app natively on all the iPhone versions running various versions of iOS. I would like to be able to interact with the iPhones myself, so that I know that a specific bug has actually been fixed before, pushing to App Store and waiting 9 days for the review before I can hear the sad news from customers. Googling got me nowhere. Do such services exist?


Abstract class + Inheritance vs Interface

Hello fellow programmers, I am reading a book on C# and the author is comparing Abstract classes and Interfaces. He claims that if you have the following "abstract class:"               abstract class CloneableType     {     public abstract object Clone();     }      Then you cannot do this:               public class MiniVan : Car, CloneableType     {}      This, I understand. However he claims that because of this inability to do multiple inheritance that you should use an interface for CloneableType, like so:               public interface ICloneable     {     object Clone();     }      My question is, isn't this somewhat misleading, because you can create an abstract class which is "above" class Car with the method Clone, then have Car inherit that class and then Minivan will inherit Car with all these methods, CloneAble class -> Car class -> Minivan Class. What do you think? Thanks.


What's the best approach to handle javascript/ajax code in a project?

In a general sense, for medium/big projects, what's the best way to handle javascript/ajax code? Is it better, to have a script file where to put each script or, to add the script directly into the html file between tags? I know it doesn't make any difference in terms of result, but i would like to understand what's is easier to mantain in long terms.


Is the MVC pattern used in industry a lot? What's all the hype?

I'm a student but I am hopefully moving into the software industry soon. There seems to be a lot of hype about the MVC software pattern. I noticed that PHP frameworks are often MVC, what about non-web languages.. is it the same with them? For my masters dissertation (C++), I chose the MVC pattern because it nicely separates out the logic and user interface. In industry is it used a lot? If so, what are the main reasons and what are other competing, popular designs?


When the current sprint consists of mostly spikes, should the sprint be shortened?

Spikes are mostly quick research tasks aimed at establishing the feasibility or prototyping of some idea. Thus, they are structured so that the tasks either finish-fast or fail-fast. However, when a dozen or so spikes are added to the current sprint, there is a possibility that several of them will fail-fast altogether. Let's say there are 4 possible ways of doing something, and the task is to choose the most suitable one and come up with a prototype. If the first attempt fails then try the next possible way, and so on. If the first pick is already a clear winner, then the next 3 aren't necessary anymore. So, when the current sprint consists of mostly spikes, does it make sense to also shorten the sprint time to maybe a few days, so that reprioritization can happen more frequently?


Can the version of Git vary between team members?

We are about 40 developers working on the same code base and we use Git for version control. My question is: can there be problems if, for example, some developers have a much older version of Git installed on their system ? Or should we try to enforce some rule that says something like "you should upgrade Git on your machine to the latest version at least once per year" ? Maybe in older versions of Git, the structure of the objects may be slightly different. Or there may be some bugs in the algorithm that calculates which lines were added/removed from files. These issues can cause corrupt repositories or different values for the SHA-1 hashes in places where it should have the same value.1 Obviously, since Git is a distributed VCS, a corrupt repository won't ever mean critical loss of data, since there are 40 other people from which you can clone a new copy. So it's more a curiosity than a concern. I suspect that backwards- compatibility is something extremely important when it comes to releasing a new version of Git; but still: the potential issues mentioned above are a possibility. 1 = as far as I know, we had no such problems... yet.


Incanter for real world statistical projects

I'm interested in statistical computing. **R** is a leader platform obviously but what about Incanter?   Incanter is at the top of my list since I'm a Clojure and JVM guy. Do you have any real world projects with Incanter? Is it a proven platform or I have to fall back to **R**?   What are the advantages of **R** over Incanter? What I'm going to miss?


What cannot be unit-tested in mobile app?

I really value unit-testing in developing webapps. I haven't had any experience in developing mobile apps. Is there anything that cannot be unit- tested in mobile apps? And what is the workaround for this? Is there any common gotcha that we must be aware in unit-testing mobile apps?


What is "Simplified JavaScript"?

Douglas Crockford makes reference to **Simplified JavaScript** in this article about **Top Down Operator Precedence**. Unfortunately he only makes references to it in this article. The best explanation I found **here**. But I still don't have a clue what it actually is. **What is Simplified JavaScript?**


Transition from a "look ma, I can do this" web developer to someone who creates products that people and businesses can rely on

I am doing web development for the past 6 years. But somehow, I never got the feeling that I did a good job. I always felt that my code was not production quality. I felt like someone who delivers sub-par products. **An analogy:** Me developing apps for paying clients is like.... a 14 year old who just knows how to shoot and move around the basketball court without falling down, playing among professionals in the NBA. That should be an accurate description :| **I wouldn't buy from me, if I were the client.** I want to move from this current position to a stage where I feel confident that my websites web apps are "professional", "secure", "scalable", (insert all requisites of a product that is worth paying for or relying on for your business). **My question is:** **1\. What are the things I should learn, and..** **2\. From where can I learn those..** **..in order to create truly professional websites and web applications that other people/businesses can rely upon?** I am sick of feeling like an amateur even after so many years. I want help in getting started. I can learn if I know _what_ to learn. I can learn given enough time and things to experiment with, but I don't want to make my clients guinea pigs. **Here is what I know and don't know:**   * I know or can learn the needed syntax in C# to convert the required business logic from concept to working code.   * I can write somewhat complex select queries and even a few joins if needed to fetch data. Of course I can insert, update, delete. But that's it. I know nothing else in SQL server.   * I know enough web front-end technologies to develop good UI. This is not a problem area.   * I know enough about hosting/domains to register and buy hosting and point servers at each other so that example.com actually loads the website. Not much more than that.   * For all practical purposes, ZERO knowledge or experience in handling security and server load   * No idea about caching, at any level.   * I only know the coding best practices, dos and donts. I don't know the same for real world apps that thousands of people are going to use.   * Every time I read a question in SO that has anything to do with a production application, all the answers and the question itself is all Greek and Latin to me. I feel inspired that there is so much to learn, but I can't figure out how to start. * * * I will primarily be working with the Microsoft Stack. So any answer specific to it will also be great.


Is Java a good choice for cross-platform games?

I'm looking to create a game in Java and would like it to work on Windows, Linux, and Mac. I'm pretty sure C# is a bad choice for this, and I don't have enough experience in C or C++. I want to stay away from Flash. Therefore, is Java a good choice for me? Mostly, I use C#, and think that Java is similar, so I assume it won't be that hard to learn. But is it fast enough? Is there a language more suited for my needs than Java?


Providing Estimates When working With Unfamiliar Technology?

I was presented with a new problem recently, to provide an estimate for a project in which I must use a framework (and potentially bits of another framework) that I am unfamiliar with. It's much easier for me to provide estimates when I'm at liberty to use what I'm familiar with, but it was as though a crippling paralysis by analysis had kicked in when an estimate was requested for work in unfamiliar territory. My solution, in retrospect, was wrong. I merely began working. How might I better estimate projects and tasks when I am required to work with unfamiliar languages/technologies/frameworks?


Secure way to remember usernames and passwords

Maybe it was already discussed. After browsing through some alike questions here about password management, I still would like to ask this question. If there are 100 sites which require username password to login. It would be a nightmare to make up another username and password just for the uniqueness. However if we use the same username and password, we expose ourselves to crossite attack. Maybe we can make 100 different username and password, but how can we remember it? Brain is not trustworthy. Professionals recommend not to write down any password on paper. And there are those password management software. I've never used these software so I am rather blind there. Do you trust those things? Imagine if someone stole your computer and try to break into these software, do you has the risk to lose all your identity?


Is Google App Engine's level of support robust enough for real-world production?

Google App Engine has been great for trying out ideas and learning stuff, but so far I haven't seen much confidence in the community in using it for production applications. One significant issue that has come up over and over again is that when things go wrong, it's nearly impossible to actually talk to anyone at Google. This is really scary if your company is depending on this service for the production app. However, their literature on Premier accounts looks promising, with the promise of better levels of support. What has been your experience with using Google App Engine when it comes down to resolving support issues? Does it really take 4 hours to just acknowledge a P1?


Should I provide some way to disable my software post-delivery?

I'm debating the value of putting remote disable (or destruct) functions into my software before delivering it to clients... As a hypothetical example, consider the development of a Silverlight app where you're worried about the client not paying you. You create a function which when a specific query string is entered it deletes everything in the database. Destroying data might be a bit of an extreme example. Making the application either partially or completely unusable would be another example. What are the benefits and risks of doing this? If you've done it, why did you do it, and how did you go about it?


Mask oAuth API key and token for pure client-side technologies

If I were to build a Twitter or Facebook application using pure client-side technologies like HTML and javascript, how would I mask/hide my API keys? For example, for Twitter I have consumer key and consumer secret. In order for me to call Twitter's API I'll have to pass these keys to authenticate my app. If I am using pure client side technologies, I leave myself exposed. Therefore, the API keys are up for grab and anyone can authenticate as my app. How can I prevent this? Can I prevent this at all? This question is very similar to this thread, however, it's not a desktop application.


Transitioning from being a bespoke development to a COTS development house

Currently one of the major applications that our organisation produces would be regarded as bespoke software as it is specifically designed for one specific client organisation. However, we have specifically retained the intellectual capital on the project and a number of different organisations in different countries (with different languages and character sets) now look like they want to purchase our software solution. Our current approach to development passes 9 ½ out of the Joel Test and is improving. However, our approach is all about satisfying the requirements of one specific client and responding quickly to their needs (regardless of whether something is a bug or a change request). If we want to transition to producing more of an 'Off the Shelf' approach with multiple client organisations---rather than just one client organisation---on a common code base, what are the major differences and what pitfalls do we need to be aware of to successfully make the transition?


How to refer to specific areas of code in documentation?

I'm about to leave a project, and before I go my boss has asked for me to document code (I've not documented very well). It's not a big deal, the project is not terribly complex. But I'm finding places in my documentation where I would like to say, "Notice on line XYZ that such-and-such happens." In this case, it doesn't make sense to refer to a specific line number, since adding or deleting a single line of code would immediately outdate the documentation. Is there some best-practice for referring to a specific line of code without referring to it by line number? I've considered littering the code with comments like:               /* linetag 38FECD4F */      Where "38FECD4F" is some unique tag for that specific line. Then I can put in the documentation, "On the line tagged '38FECD4F', notice that such-and-such happens." Any other ideas? I feel like it's generally better to document code units as a whole, rather than specific portions of them, but in the case of this particular project there are LONG swaths of procedural code, which have never been refactored into smaller units.


Is STL implemented with OO?

There are several design patterns like Adaptor, Iterator implemented in STL. Does that mean STL is implemented with OO concepts?   What is the relationship between OO and template parts of C++? I learned that virtual member function which justifys the OO is contradict with template, is this correct?


Selling a Joomla extension with third party jquery plugin

Let's suppose I want to create an extension for Joomla that uses a jQuery plugin or any third party library. Imagine that I create a Joomla module that uses jquery Nivo Slider plugin (MIT License) http://nivo.dev7studios.com/license/. I'm not sure If I could sell this module with this license. Could I sell it if the plugin has a GPL License?


Is this XOR value swap algorithm still in use or useful

When I first started working a mainframe assembler programmer showed me how they swap to values without using the traditional algorithm of:               a = 0xBABE     b = 0xFADE          temp = a     a = b     b = temp      What they used to swap two values - from a bit to a large buffer - was:               a = 0xBABE     b = 0xFADE          a = a XOR b     b = b XOR a     a = a XOR b      now               b == 0xBABE     a == 0xFADE      which swapped the contents of 2 objects without the need for a third temp holding space. My question is: Is this XOR swap algorithm still in use and where is it still applicable.


Were there major changes in testing practices in ASP .NET between 3.5 and 4.5?

Obviously, testing methods are language-independent. An integration test stays an integration test no matter what the technology. But platforms implement some kinds of testing support. And the details vary between implementations, so a programmer has to learn how to use the tools of their framework. And platforms evolve, so best practices in one version may become obsolete or at least inefficient in the next version. See for example this StackOverflow question about unit tests for which at least the first three answers seem to be valid: One describing the correct solution for the current version, one describing the solution which used to be best before the .NET framework included an ExpectedException attribute, and one describing a generic solution which is tool-independent. My question is: were there any major testing-related changes between the .NET framework versions 3.5 and 4.5? Something as disruptive to testing as introducing generics was to programming in general, or introducing the Membership framework was to authentication? Or were there only small enhancing changes? I am asking this because I wonder whether learning materials written for 3.5 are still reasonably valid today.


What phases of a traditional waterfall project should Scrum replace?

My team and I are using Scrum to manage software development projects. In my company there has been a move towards more structure in all IT projects using a waterfall methodology. This is fine by me as there are lots of non-software- development projects which will benefit greatly from this and it is not threatening our use of Scrum. However, we need to work out how our Scrum processes (which do a great job of taking a Product Owner's requirements and turn them into working software) fit into the broader project process. Our new waterfall project process includes explicit activities for the following things (not necessarily sequentially and not necessarily in this order):   1. Production and approval of business case.   2. Resourcing.   3. Requirements analysis.   4. Design.   5. Build.   6. Test.   7. Training.   8. Communications.   9. Go live.   10. Risk & Issue Management.   11. Benefits realisation. Bear in mind that a project may be required to deliver more than just software. It may also include server infrastructure to host the software and network / desktop infrastructure to make it available to users. I think Scrum will manage 3, 4, 5 & 6 happily but probably only for teams who find it adds value, which is probably only software development... We could get other teams to use it for the production of infrastructure deliverables, but they don't see the need or benefit and nor do I (Scrum is good for large, risky projects and they are building a bunch of standard PCs). Likewise we could have a User Story in the Product Backlog for the Project Manager (not typically a member of the Scrum Team) to produce a benefits realisation plan. Are we approaching this correctly? Is there a better way to integrate these two styles of working or are they exclusive and we should use one or the other?


What class structure allows for a base class and mix/match of subclasses? (Similar to Users w/ roles)

I have a set of base characteristics, and then a number of sub-types. Each instance _must_ be one of the sub-types, but can be multiple sub-types at once. The sub-types of each thing can change. In general, I don't care what subtype I have, but sometimes I do care. This is much like a Users-Roles sort of relationship where a User having a particular Role gives the user additional characteristics. Sort of like duck- typing (ie. If my `Foo` has a `Bar`, I can treat it like a `ThingWithABar`.) Straight inheritance doesn't work, since that doesn't allow mix/match of sub- types. (ie. no multi-inheritance). Straight composition doesn't work because I can't switch that up at runtime. How can I model this?


Validating objects with each other - Design Pattern needed

I am running a zoo application. My zoo includes an abstract class of 'animal', and several deriving classes - 'zebra', 'elephant', 'orangutan', 'baboon' and so on. Of each class I have several instances. My question is: I want to check out if two animal instances can mate. The business logic is divided to two parts:   1. I want to check if each mating partner is fit for mating, e.g. not too young or too old or sick etc.   2. I want to check if the two partners match - e.g. a zebra cannot mate an elephant, but an orangutan can mate with a baboon. I assume the first requirement would be implemented by an abstract function which would reside under the animal baseclass. But what about the second requirement? How would you design the classes in the most general matter that adding new types of animals would not require much of an overhead?


Finally block for methods - is it a bad idea?

The `finally` block for a `try-catch` structure is well known, and gives a really easy and elegant way to deal with some must-be-done code. Therefore, I can see no reason why It shouldn't be good for methods too. For instance, lets say I'm writing some very complicated logic in a method, and I expect to end up with a bunch of boolean flags that will in turn lead to some decisions. Many times in such kind of methods I have branches of code where I would want to "break" the flow and just perform the "real stuff" that I called this method for, with the satisfying information I gathered so far. So, Why isn't there such pattern? Or is there?


Displaying items with a countdown timer

I am creating a widget for rotating topics. The functionality is as follows:   * Each topic is displayed one by one on the homepage and has a duration of 30 seconds.   * A countdown timer is displayed on the page. When it reaches zero the current topic gets marked as "shown" and the next topic is displayed.   * Users can choose to "like" topics, in which case the topic gets an additional 5 seconds duration (the countdown timer needs to update itself at this point).   * The countdown timer always needs to display the current allocated duration for the topic, so for example if a user "likes" a topic then people accessing the site should instantly see the updated duration for that topic. Basically everything needs to be shown in "realtime". The topics are stored in a MySQL database. I am having trouble with the last two points in the above. The way I have tried to do it so far is to have an AJAX request which is sent every second to deduct 1 second from the current topic duration. The request response is the current topic duration. The problem with this is that it will only work so long as somebody is accessing the site. I know I can probably create a CRON script to run this process in the background, but for it to run every second would be a bit crazy. There has got to a be a much simpler solution to this problem. What would be the most efficient way to go about this?


Does the VS version setting in Settings.settings matter?

Looking through the server vs local code on a humongous legacy project, I see this in Settings.settings:               <?xml version='1.0' encoding='utf-8'?>          <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">       <Profiles>         <Profile Name="(Default)" />       </Profiles>       <Settings />     </SettingsFile>      Is there a problem with having this VS2010 project reference 2004 this way? Or does it not matter?


How to query a very long list of properties fast

I have a structure for storing item properties on SQL Server:               ItemId PropertyId Value     1      1          a     1      2          b     2      1          a     2      2          5      Currently there are over 130000 items and 10000 properties and the numbers are growing. Current row count is a little over 15M. If I created a pivot table for this data, it would have a little over 1.3 billion cells, 15 million of which are not null. Users can form custom expressions on this data like:               X: P1 = 'a' (rule X selects items which have property 1 with value 'a')     Y: P2 <> 'b'     Z: P3 like '%c%'     T: P4 > 5 (rule T selects items which have property 4 with a value greater than 5)      and they form filters by using expressions like:               (X AND T) (items that match both X and Y)     (X AND Y) OR (Z AND T)     (X OR Y) AND (Z OR NOT T)     (X OR Y AND T) OR Z      I need to query the result of a few filters (generally 4 or 5) as a response of a single web request. How can I do this fast? Is there a storage method or a super efficient algorithm to get this filter results? It'd be great if this is possible on SQL Server but I am also open to solutions like storing this portion of data on a no sql database.


Hashing growth strategy

What is a good growth strategy for hash tables? If the number of elements exceeds the number of buckets, I increase the number of buckets with the following formula:               n = int(n * 1.618033988749895) | 1;      Does that sound sensible? (The `| 1` part makes sure I get an odd number.)


Question on design of current pagination implementations

I have checked pagination implementations on asp.net mvc specifically and i really feel that there is something less efficient in implementations. First of all all implementations use pagination values like below.               public ActionResult MostPopulars(int pageIndex,int pageSize)     {          }      The thing that i feel wrong is pageIndex and pageSize totally should be member of Pagination class otherwise this way looks so much functional way. Also it simplify unnecesary paramater pass in tiers of application. Second thing is that they use below interface.               public interface IPagedList<T> : IList<T>     {         int PageCount { get; }         int TotalItemCount { get; }         int PageIndex { get; }         int PageNumber { get; }         int PageSize { get; }         bool HasPreviousPage { get; }         bool HasNextPage { get; }         bool IsFirstPage { get; }         bool IsLastPage { get; }     }       If i want to routing my pagination to different action so i have to create new view model for encapsulate action name in it or even controller name. Another solution can be that sending this interfaced model to view then specify action and controller hard coded in pager method as parameter but i am losing totally re-usability of my view because it is strictly depends on just one action. Another thing is that they use below code in view               Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount)      If the model is IPagedList why they don't provide an overload method like `@Html.Pager(Model)` or even better one is `@Html.Pager()`. You know that we know model type in this way. Before i was doing mistake because i was using Model.PageIndex instead of Model.PageNumber. Another big issue is they strongly rely on IQueryable interface. How they know that i use IQueryable in my data layer ? I would expected that they work simply with collections that is keep pagination implementation persistence ignorant. What is wrong about my improvement ideas over their pagination implementations ? What is their reason to not implement their paginations in this way ?


What acceptance test frameworks have you used? What are the pros and cons?

For business or tester facing tests on projects (not unit tests), I've typically used FitNesse, but I've dabbled with RSpec and I'm interested in learning Selenium and Robot. Do you have experience in these (or other) acceptance testing tools? What are the pros and cons? For FitNesse, I can think of the following pros and cons initially. PROS:   * Wiki based editing, which most people understand   * Lots of support and plugins for different languages   * Completely self contained, you just download and go CONS:   * Refactoring the tests can be a little clunky   * You need to know (or document) the various properties that each method in your test fixture expects. There's no "intellisense" or IDE to do this for you that I'm aware of.


Can I use Xcode 4.2?

Can I use the new Xcode 4.2 to make apps for older version of the iOS? Will they work?   I like the new features like the Storyboard and Automatic Reference Counting.


The value of potential shippability when the product is not minimally viable yet

The main benefit of having a potentially shippable product at the end of each Sprint is the ability to release the product quickly in case market conditions change. However, usually in the first half year or more the product doesn't have enough value to be actually shipped. So why spend all this energy to make a potentially shippable increment each Sprint if you know with complete certainty that the product won't be shipped?


Super Fast File Storage Engine

I basically have one big gigantic table (about 1.000.000.000.000 records) in a database with these fields: id, block_id, record id is unique, block_id is not unique, it contains about 10k (max) records with the same block_id but with different records To simplify my job that deals with the DB I have an API similar to this:               Engine e = new Engine(...);     // this method must be thread safe but with fine grained locked (block_id) to improve concurrency     e.add(block_id, "asdf"); // asdf up to 1 Kilobyte  max          // this must concatenate all the already added records added block_id, and won't need to be bigger than 10Mb (worst case) average will be <5Mb     String s = e.getConcatenatedRecords(block_id);      If I map each block to a file(haven't done it yet), then each record will be a line in the file and I will still be able to use that API But I want to know if I will have any peformance gain by using flat files compared to a well tunned postgresql database ? (at least for this specific scenario) My biggest requirement though is that the getConcatenatedRecords method returns stupidly fast (not so with the add operation). I am considering caching and memory mapping also, I just don't want to complicate myself before asking if there is an already made solution for this kind of scenario ?


Clearing the lowest set bit of a number

I can see in this tutorial on bit manipulation, under the heading "Extracting every last bit", that - > Suppose we wish to find the lowest set bit of x (which is known to be non- > zero). If we subtract 1 from x then this bit is cleared, but all the other > one bits in x remain set. I don't understand how this statement is true. If we take `x = 110`, subtracting 1 would give `101`. Here, the lowest set bit is not cleared. Can anyone tell me how I'm approaching this problem in a wrong way?


Are Vim or Emacs practical for languages like .Net or Java?

So, I am primarily a .Net developer who does some stuff in Java, Python and a few others from time to time. I have heard a lot of people praise Vim and Emacs for greatly increasing efficiency once the basics are nailed down. I can definitely see how many of the features could be very useful with sufficient practice, and even believe the learning curve is probably worth the effort. However...it seems that you would really have to be some sort of wizard of macros and hotkeys to be as efficient in Vim or Emacs as the average developer is in Visual Studio, Netbeans, Eclipse, or other platforms. I have been starting to learn to use Vim and think some of its features are awesome (column editing for example), but it seems that many of the tools provided by the heavy weight IDEs simply could not be replaced buy even the most juiced up text editor. A few processes I would be skeptical anyone could ever be more efficient at in Vim include (I know VS best, so I will stick to those):   * generating dbml files for Linq-to-SQL   * Automated testing   * designing UIs   * Creating/organizing projects and solutions I know Vim and Emacs can do a lot of the same things very powerfully that VS can (like intellisense, refactoring, etc.) and it may be able to do some or all of the examples that I provided, but is it realistic to say that someone working on these platforms would actually benefit from Vim or Emacs?


Teaching Programming to Kid / Teen

I know this topic has be discussed before, but I thought this might be a bit more of a detailed question... A family friend is a 12yr old boy with ADHD, and a very bright kid at that. He seems to have a solid instinct of computers, and I really think he would excel at programming. For example, today he was kicking around our place and so I opened up Visual Studio Express C#, and showed him how to create a console application (he was the one typing it all out). In about 10 - 20 minutes he was writing his own code, ReadLine()s and Writeline()s etc, and even started working on a loop. Made me think that even something like C# would definitely be within his grasp. Although Lego Mindstorms came to mind, his family isn't particularly well off and is likely not feasible. I thought about lending him one of my intro to C# books, but with the ADHD I don't know if he would have the patience to actually go through it. I also think something like Alice or Scratch would be too childish for him, and wouldn't catch his attention... I'm trying to figure out what the best way to approach this would be, and what sort of material is out there that he could teach himself how to program. Any thoughts or suggestions?? One thought I had was this book, but it may be too advanced without a basic C# background at least... Amazon C# Game Book: Thanks!


Difference between Web API and Web Service?

I have heard about Web Services and Web API's a lot, is there any difference between them or are the same?


Benchmark of asynchronous code

Asynchronous programming seems to be getting quite popular these days. One of the most quoted advantages is performance gain from removing operations that block threads. But I also saw people saying that the advantage is not that great. And that properly configured thread pool can have same effect as fully asynchronous code. My question is, are there any real benchmarks that compare blocking vs. asynchronous code? It can be any language, but I think C# and Java would be most representative. Not sure how good would this benchmark be with Node.js or similar. **Edit** : My attempt at general question combined with unclear terminology seems to have failed. By "asynchronous code" I mean what some answers described as event or callback programming. In the final result, operations that would block thread are instead delegated to some callback system so threads can be utilized better. And if I wanted to ask specific question : _Are there any benchmarks that compare throughput/latency gain of async/await server code in .NET? Or any other similar comparison?_


How would my custom language be categorized?

I'm developing my own scripting language to solve some unique challenges for a project. The language takes source code and converts the contents into tokens, and then a command factory is used to convert those tokens into something that can be executed. An example of a script might look like this.               accept: always;     reject: title has "something" or body has "something else";     reject: title length < 10;      Each line in the script ends with a `;` terminator, and each line starts with a named rule that ends with `:`. Each rule uses a command followed by arguments. The commands can be joined together using logical operators. The number of arguments a command can have is fixed. So when I find a command I can expect X number of additional tokens for the syntax to be correct. The goal is human readable code because non-programmers will be using it. An alternative way of writing the same above code using a C style structure would be.               accept(true);     reject(has(title,"something") || has(body,"something else"));     reject(length(title) < 10);      What is the term used for a parser that handles a language where `()` for structuring arguments is omitted, and there are no clear boundaries defined for arguments. I would like to read up on how these kinds of parsers are implemented. To ensure I'm not overly reinventing the wheel or running into common problems.


Align draggable elements in line and generate without overflow or new line

I have this script I'm working on. What it should do is generate a new div every time I press a button and I've already done that, but those are not draggable. I think that happens because of the onLoad function but alternative do I have? The second problem is that when I click one of the blue boxes, all of them must arrange in a line like you see them when you load my jsFiddle link, and if the line is full and you click the "New Square" button, instead of overflowing or add a new line, it would close the last box instead and add a new box before all of the other boxes. I'm sorry to bother you with those questions, but I am a PHP and MySQL programmer, I just started using jQuery. jsFiddle HTML:

     <input type="button" class="button" value="New Square">      jQuery:               $('.round').draggable();          $('.button').click(         function (){     $("#container").append("

");         });          $('.round').click (              );      I had more code in jQuery, but I removed all of the useless options because I want you to easily understand what I want to do.


Enforcing organizational standards for software in Scrum

Organizations, especially organizations with a recognized brand, have various standards for software. This includes things like security, usability, code quality and readability, UI design, test automation and so forth. In our organization we have a lead for each of these areas. Each lead is a very experienced individual and is trusted by management. Each lead is responsible for the software to meet the standards in the lead's area of expertise. The Scrum Guide says: "Development teams are self-organizing. No one (not even the Scrum Master) tells the Development Team how to turn Product Backlog into Increments of potentially releasable functionality;" My question is how can an organization trust teams to produce a product that meets the various standards mentioned above, if the leads (trusted by the organization) have no ability to enforce the quality in each of the areas?


Is hiring a "chief intern" a good idea?

I'm starting an internship program for our software department and I was wondering about creating a position ("chief intern", intern supervisor, or whatever one should call it) with the following responsibilities:   * **Train** interns   * **Coach** interns   * **Manage projects and tasks** for interns   * **Supervise** intern's work in terms of **rhythm and quality**   * **Act as a liaison** between the main team's needs and interns performance/aspirations   * Evaluate and facilitate intern's progress **when they want to grab a higher-level domain-specific task** (at this point, a main dev team member can do mentoring)   * **Get freely involved in the main team's software development tasks so that he himself can grow** , and have full mentorship from the main dev team. I'm thinking that an apprentice-level engineer (below Jr., or Jr.; but being a graduate and working full-time) can handle this for a while (he will be trained by the main dev team first), until one of two things happen:   1. He/she **decides to move on to the main dev team** by recommending an appropriate replacement (or me finding another one as a new hire)   2. **Keep leading** the interns while still being able to grow to Jr. Eng., Eng., Sr. Eng I know the notion of a "chief intern" is common within the medical world, but I don't really know about that in the software world (I was a freelancer for most of my university years). A side-intention to this is also that, if this ends up being a higher rotation position (organically) because the intern supervisor wants to join the main dev team, **this could help interns that aspire this position emerge as leaders**. **My main intention for this, though, is removing distractions from the main team but without making the interns suffer the lack of attention, which could lead to boredom and little intern retention.** Is this "chief intern" idea common (or good at least)?, are there any obvious risks to it that I might not be seeing? * * * **Edit** : I have a draft plan for the kind of work the interns would be doing: Are R&D mini-projects a good activity for interns? **Edit #2** : My intention is not keeping them isolated, but having someone focus on giving attention to them when we cannot. **Edit #3** : I'm now convince it is a good idea, but I will take the organic approach to hiring someone in such position: do it myself until I cannot. This way I'll know better what to expect from a person I hire for this role in the future, as well as what works and what doesn't with interns.


Communicating with Vendors

We are a small software team (as far as programmers go) and have a team of vendors on the other side of the world that program for us. We own the product, and simply dictate to them some of the tasks to work on. I am one of the lead programmers and also the project manager of this particular project, so I am a programming and fulfilling requirements as well as outlining them. I am having difficulties communicating with the vendors exactly what is expected of them. Let me start by saying we are fairly new at this and I don't have a lot of experience leading a team of vendors, especially when it is difficult to communicate verbally in English, and they work during my night and then I come into the code they pushed while I was asleep. Problem is, I end up spending a lot of my day just checking what they did, and fixing bugs and cases they didn't think of. They're not thinkers, they do exactly what I tell them, and nothing more or less. Most of the time, I feel like it would just be easier to do it myself. My question is how do most teams like this communicate? Right now we have weekly telephone meetings and I email them nightly the progress I made, as well as what is expected of them. When I think "how to communicate with other programmers" the answer seems to be UML. That's what it is. I certainly am very familiar with UML, learned it in school, but have never really used it on the job. It's just not something we do, in fact generally the requirements for a task are in my manager's head. I can get those into a spreadsheet or a flowchart, but never an official diagram. Is UML something teams like this actually use? In all reality, I feel like I learned a lot in school that no one actually does. If so, which diagrams are the most useful/used? From my knowledge, in this project where we are revamping something that exists in the system already from the ground up, I feel like the following would be a good approach:   * Create a quick ER diagram containing any added/updated/used entities in the project.   * Create a _detailed_ use case model, clearly defining and numbering each use case.   * Create a sequence diagram for the complex use cases (as well as their alternate flows) to show exactly what is expected each step of the way. I feel like this would be a good start. We don't really do a good job of capturing requirements currently, we kind of just start coding based on something we drew up on a whiteboard. Obviously this needs to change as well, to avoid getting a week into a project and realize that we forgot something. What are your suggestions/experience? Unfortunately we're sort of flying blind and just don't have anyone experienced enough in these situations to go to. I want the project to be a success, but I can't keep having the vendors (understandably) making mistakes because I assume they know X or Y. How can I utilize them more effectively?


Custom HTML Tags: Are there any specifications stating a standard way to handle them?

It seems like for years they've just been given default styling and inline display. Is there a spec somewhere that has dictated this? I've looked over the RFC's but I'm not particularly good with RFC-ese, and I didn't notice anything anywhere. For example               <body>        Some content <mycustomtag>something else</mycustomtag> more content.     </body>      I can still style it with CSS, and the browser doesn't outright vomit... so it seems like there is some sort of expected behavior. Was that dictated by a specification?


Understanding UML composition better

The difference between Composition and Aggregation in UML (and sometimes in programming too) is that with Composition, the lifetime of the objects composing the composite (e.g. an engine and a steering wheel in a car) is dependent on the composite object. While with Aggregation, the lifetime of the objects making up the composite is independent of the composite. However I'm not sure about something related to composition in UML. Say ClassA is composed of an object of ClassB:               class ClassA{         ClassB bInstance;         public ClassA(){             bInstance = new ClassB();         }     }      This is an example of composition, because `bInstance` is dependent on the lifetime of it's enclosing object. However, regarding UML notation - **I'm not sure if I would notate the relationship between ClassA and ClassB with a filled diamond (composition) or a white diamond (aggregation).** This is because while the lifetime of _some_ `ClassB` instances is dependent of `ClassA` instances - there could be `ClassB` instances anywhere else in the program - not only within `ClassA` instances. * * * **The question is:** if **_some_** ClassB objects are composed with ClassA objects (and thus are dependent on the lifetime of the ClassA objects), but **_some are not_** \- would the relationship between the two classes in UML be an aggregation or a composition relationship??


Simplifying C++11 optimal parameter passing when a copy is needed

It seems to me that in C++11 lots of attention was made to **simplify returning values** from functions and methods, i.e.: with move semantics it's possible to simply return heavy-to-copy but cheap-to-move values (while in C++98/03 the general guideline was to use output parameters via non-const references or pointers), e.g.:               // C++11 style     vector<string> MakeAVeryBigStringList();          // C++98/03 style     void MakeAVeryBigStringList(vector<string>& result);      On the other side, it seems to me that more work should be done on input parameter passing, in particular when **a copy of an input parameter is needed** , e.g. in constructors and setters. My understanding is that the best technique in this case is to use templates and `std::forward<>`, e.g. (following the pattern of this answer on C++11 optimal parameter passing):               class Person     {         std::string m_name;          public:            template <class T,                   class = typename std::enable_if                   <                       std::is_constructible<std::string, T>::value                   >::type>         explicit Person(T&& name)              : m_name(std::forward<T>(name))          {         }              ...     };      A similar code could be written for setters. Frankly, this code seems boilerplate and complex, and doesn't scale up well when there are more parameters (e.g. if a surname attribute is added to the above class). Would it be possible to add a new feature to C++11 to _simplify_ code like this (just like lambdas simplify C++98/03 code with functors in several cases)? I was thinking of a syntax with some special character, like `@` (since introducing a `&&&` in addition to `&&` would be too much typing :) e.g.:               class Person     {         std::string m_name;          public:            /*            Simplified syntax to produce boilerplate code like this:                 template <class T,                   class = typename std::enable_if                   <                       std::is_constructible<std::string, T>::value                   >::type>         */         explicit Person(std::string@ name)              : m_name(name) // implicit std::forward as well          {         }              ...     };      This would be very convenient also for more complex cases involving more parameters, e.g.               Person(std::string@ name, std::string@ surname)         : m_name(name),           m_surname(surname)     {     }      **Would it be possible to add a simplified convenient syntax like this in C++?** What would be the downsides of such a syntax?


How can a Java programmer make the most of a new project in C or C++?

As a Java programmer, I'm looking to learn either C or C++ by writing a database manager. Obviously, Java shares many idioms with C and C++, but yet both bring vastly different program design challenges. I'm looking to for a way to make this exercise as educational as possible. **What aspects of taking on this project in C or C++ can help me make a decision about which approach will teach me the most, as a Java programmer?** One particular target of this exercise would be at least a subset of the spatial extensions in PostgreSQL. Obvious issues to consider would be goodness of fit of C vs. C++ for:   * modeling concepts of databases in general.   * modeling spatial modeling in particular Another major point would be the degree of expected difference from Java. Would a good, idiomatic design in C++ be enough different from a design in Java to teach new, different concepts, or would it mostly be the same concepts with slightly different syntax? Would a good design in C contain more concepts that were new or different than one in C++?


Third-party open-source projects in .NET and Ruby and NIH syndrome

The title might seem to be inflammatory, but it's here to catch your eye after all. I'm a professional .NET developer, but I try to follow other platforms as well. With Ruby being all hyped up (mostly due to Rails, I guess) I cannot help but compare the situation in open-source projects in Ruby and .NET. What I personally find interesting is that .NET developers are for the most part severely suffering from the NIH syndrome and are very hesitant to use someone else's code in pretty much any shape or form. Comparing it with Ruby, I see a striking difference. Folks out there have gems literally for every little piece of functionality imaginable. New projects are popping out left and right and generally are heartily welcomed. On the .NET side we have CodePlex which I personally find to be a place where abandoned projects grow old and eventually get abandoned. Now, there certainly are several well-known and maintained projects, but the number of those pales in comparison with that of Ruby. Granted, NIH on the .NET devs part comes mostly from the fact that there are very few quality .NET projects out there, let alone projects that solve their specific needs, but even if there is such a project, it's often frowned upon and is reinvented in-house. So my question is multi-fold:   * Do you find my observations anywhere near being correct?   * If so, what are your thoughts on quality and quantitiy of OSS projects in .NET?   * Again, if you do agree with my thoughts on "NIH in .NET", what do you think is causing it?   * And finally, is it Ruby's feature set & community standpoint (dynamic language, strong focus on testing) that allows for such easy integration of third-party code?


Removing dependencies on subclass-specific behavior

I have a `Message` class which can contain multiple types of payloads (or sometimes no payload), each derived from a common `Payload` class. However, this becomes problematic because the `Message` class wants to know about the `Payload` subclasses for various reasons such as:   * Checking for `Message` equality              if (message parts besides the payload are equal) {         switch(type) {             case Payload::Type::RESPONSE:                 return *static_cast<ResponsePayload*>(payload.get())                     == *static_cast<ResponsePayload*>(o.payload.get());                 break;                  case Payload::Type::SETUP:                 return *static_cast<SetupPayload*>(payload.get())                     == *static_cast<SetupPayload*>(o.payload.get());                 break;                  ...         }     }        * Deserializing (since the deserialization methods are static because the payloads are immutable)              switch(type) {         case Payload::Type::RESPONSE:             load = ResponsePayload::fromJSON(payloadValue);             break;              case Payload::Type::SETUP:             load = SetupPayload::fromJSON(payloadValue);             break;              ...              case Payload::Type::START:         case Payload::Type::STOP:         case ...:             break; // Load stays null              default:             THROW(Exception, "Error in program logic: we forgot to parse some payload");     }        * Ensuring a `Payload` is attached to a `Message` while constructing it:              switch(type) {         case Payload::Type::RESPONSE:         case Payload::Type::SETUP:         case ...:             ENFORCE(IOException, payload != nullptr, "For this message type, a payload is required.");             break;              case Payload::Type::START:         case Payload::Type::STOP:         case ...:             ENFORCE(IOException, payload == nullptr, "For this message type, the payload should be null");             break;              default:             THROW(Exception, "Error in program logic: we forgot to handle some payload");     }      Alarm bells are going are going off in my head - this violates SOLID like there's no tomorrow and obviously doesn't scale well since I have to add `case` statements every time I add a new payload. Is there a cleaner approach I could take?


Why isn't java used as a build language?

If Java is a general purpose language, and building a program is something that can be described using the Java language, why isn't this the best way to write build files and instead we use tools like Ant, Maven, and Gradle? Wouldn't that be more straightforward, and also remove the need to learn yet another programming language? (BTW - this question can also be applied to other languages, like C#)


How to use namespaces to separate interface from implementation, in c++?

As far as I can tell, you can make your interface known to others by providing your .h file. Your .cpp is the implementation. Then they can see the function names, the parameter types, the return type, maybe a description of how to use a function, and maybe what it does in the .h file. Then I read in posts here about using namespaces to separate the interface from the implementation. What does that mean? Doesn't a namespace only let you know that a name exists in that namespace? So please provide an example, I can't find any.


Learn HTML5 CSS3 and JavaScript

What is best way to learn these technologies which would enable me to understand all the 3 in a combined perspective rather than individually?


Which programming frameworks offer good multilingual support?

I'm starting a new company, and our software will be a SaaS solution offered to municipalities around the world. Their interface will be web-based. I am trying to figure our which software development frameworks and which software platforms would be able to support a fully multi-lingual system. In this I mean that I need to be able to have the same screens operate in different native languages (including right-to-left), both for display and data-entry. I want to be able to maintain a single application for all languages. I need to be able to add new languages pretty quickly (= no development) once the system is set up.   Since I am starting from scratch, I have the privilege to research and choose in advance, and not force a solution into an existing application.   Also, I have experience in leading development on Java, .NET, C++ and C, so I am open to use any technology that will meet my business needs. I would appreciate recommendations with pros and cons.


Question about Java nested classes design decision

I was shocked today to discover that this code compiles cleanly in Java:               public class A {       public static class B {          private static void x() {}       }       private static class C {          private /* So, private to what exactly? */ static void x() {}       }       public static void main(String[] args) {         B.x(); C.x();       }     }      It seems Java's private keyword indicates only top-level-class-privacy; which, given the general convention to name Java source files by class, means that Java effectively provides only file-level private visibility, not true private visibility. (The equivalent code in C++ does not compile with a visibility error.) Would anyone be able to explain why Java was designed this way? Or is this just Java's way of telling everyone not to use nested classes? (It certainly hacks in an implementation of a two-way C++ friend relationship, but we already have package-level visibility for that; this seems to make the one-way equivalent impossible. Moreover, it necessitates the compiler creating more hidden accessor methods to circumvent the visibility, and under-the-hood downgrading of nested class visibility control to make all this not error out at runtime. Really, why the trouble?)


Promotion or De-motivation

I am working as a programmer for last 3 years, recently my company has promoted me as a project manager. Now I am facing resource management issues and I am not comfortable as a manager and I want to continue my profession as a programmer. I have talked to my director to step me back as a programmer but he forced me to continue as a project manager as this is one step ahead from programming. Now suggest me what should I do?


Do you actively think about security when coding?

When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?


can a team lead's work ever be done working remotely

I am currently a software developer. As a next milestone in my career I am thinking I must establish myself as team leader which leads a small development team in order to meet deliverables, deployments, etc. I've read various post in this site itself which discusses the pros and cons of working from home. But I am not sure if this aspect was quite discussed/debated. I haven't stepped into the team leading role per se, but I would like to know the responsibilities that come with the title, and if (and how) that can be managed while working from home.


How do you organize your local development environment?

> **Possible Duplicate:**   >  How do you organize your projects folders? I'm interested to learn how everyone keeps their local development projects organized in a logical manner. What do you do to keep your dev projects organized in a manner that allows you to easily find things?


Two related, but independent projects -- Two repositories or one?

I've made two "complimenting" projects. These two projects are stand alone, but are almost designed to be used together. They are both fairly small projects as well. I'm wanting to host the code on GitHub, but I'm not sure if I should use two repositories or one for this. What do you think I should do?


Why is this syntax convention?

It says in the book (APress Ganesh / Sharma) about Java 7: > You create a method named `fill()` in the Utilities class with this > declaration: >   >   >     public static <T> void fill(List<T> list, T val) >   > > You declare the generic type parameter `T` in this method. After the > qualifiers `public` and `static`, you put `<T>` and then followed it by > return type, method name, and its parameters. This declaration is different > from generic classes—you give the generic type parameters after the class > name in generic classes. But why `<T>` as in `public static <T>` ? The syntax looks odd and appears nowhere else in the Java language. What does the `<T>` mean in this case and why is it used?


Is a PHP array an example of a dynamic data structure?

I did my homework, and it says that dynamic data structures are "data structures that change in size as a program needs it to by allocating and de- allocating memory from the heap". So I was wondering, are PHP arrays examples of dynamic data structures, or are they limited to binary trees and double-linked lists? Thanks.


Go-like interfaces + multi-methods make sense?

Thinking about the design of a potential new language, I wonder how related are the concepts of built a OO similar to GO interfaces and multi-methods (I get this from http://docs.julialang.org/en/latest/manual/methods/). If I understand this right, the interfaces are simply a group of methods that must be implemented by each descendant, and multi-methods provide a nice way to specialize them without do a lot of boilerplate or casting. However, Is my intuition that both could work well together, but wonder if is correct. For example, if a interface declare:               type Animal interface {         Speak() string     }          func (d Dog) Speak() string {         return "Woof!"     }      but in julia is more like:               speak(x::Dog) = return "Woof!";      So this feel like that both do the same, but different. Will be a mess to do both? When could that make sense? Also, what make a "better" path, if only one must be used?


What is the applicability of CORS?

I have a system which needs to do cross-origin requests and having trouble understanding the relevance of CORS. At first glance it doesn't appear to provide me with any type of security I'd actually want for my service.   1. Since CORS is honoured only on the client side my server must still make zero assumptions about the request. There is no guarantee a request is coming from a browser at all, thus CORS headers cannot be used as access control.   2. The target server decides who is allowed to talk to it, and the origin server has no control. My JavaScript is also not secure on the client and subject to alteration. A malicious server could simply accept all CORS requests and thus all data could leak out of my application. I see only a narrow scope of where CORS is actually helpful. This is the Facebook like scenario. Default cross-origin restrictions prevent a malicious page from making requests to Facebook on behalf of the user. CORS simply allows certain domains to do this. However, I still don't see the value in CORS here because some simple DNS setup would allow the same behaviour. So what I am missing about CORS? In which scenarios is it relevant and advantageous to use (compared to simple DNS CNAME's)?


how much memory should android app use

We are planning to develop an android application. the application will use API and data transfer will be via SSL. I should write documentation and set functional and system requirements for the appliaction. One of the main requirements is that how much memory should the application use. Of course Android OS manages itself how much memory allocate to it at different satges of its activeness, but a great deal depends on appliaction. Is there any specific defined practice on how much memory should a typical android app use and that it is in use in advanced world of android developement, e.g. the appliaction of X type should use no more that 7 MB if they are active? How to set the requriement so that developers pay enough attention to this specific parameter?


MySQL left join + performance

SELECT                        *    #Case 1                 cp.* #Case 2                  FROM crawl_page AS cp             LEFT JOIN artist AS a                 ON cp.cpURL LIKE CONCAT('%',a.artistPageID,'/',a.artistPageURL,'%')                  WHERE cpPageType = 'SONGS'                 AND cpPageAdded < (                     SELECT cpCrawlDate                      FROM crawl_page                      WHERE cpURL = 'http://www.example.com/page-52/'                 )                      AND a.artistID IS NULL                    LIMIT 1      In this query when I use 1st case (selecting everything from both tables) time taken for query is fine about 0.468 sec. But if I do case 2 (selecting only from main table) it takes hell much time 26 second. It's not problem just to use case 1, but I can't get the idea how does it work and why? Thanks


Mapping values over a curve

I have a value between 0 and 8000 and I want this number to resolve to another number between 0 and 2000. I could just divide it by 4 but I have a special need here. For values above 4000 I want the mapped value to be biased towards the 2000. But for values lower than 4000 I want the mapped value to be biased towards 0. This is actually for a game where you are given bonus points between 0 and 2000 depending on how quickly you complete the task. So if you are very fast and do it in 7500 milliseconds you should get 1875 points (exactly 7500 / 4). If you do it in 6000 milliseconds you would get 1450 points (a little under 6000 / 4). If you are slow and do it in 1000 milliseconds you would get 50 milliseconds (well under 1000 / 4). The idea is to reward fast players more than slow players but still let slow players feel like they've achieved something. I feel an "eased-out" value mapping would achieve this. I hope this makes sense. Can you help me figure out some code that achieves this?


Fortran 90 - How to create a coordinate system

So I need to code a simple program, and I need to define 2D coordinates? Is there any coordinate system I can use in Fortran? I was told it might have to be all in arrays? And if so, can anybody push me in the right direction as to how to set up 2d arrays? Many thanks.


Why are reference-counting smart pointers so popular?

As I can see, smart pointers are used extensively in many real-world C++ projects. Though some kind of smart pointers are obviously beneficial to support RAII and ownership transfers, there is also a trend of using shared pointers _by default_ , as a way of _"garbage collection"_ , so that the programmer do not have to think about allocation that much. Why are shared pointers more popular than integrating a proper garbage collector like Boehm GC? (Or do you agree at all, that they are more popular than actual GCs?) I know about two advantages of conventional GCs over reference-counting:   * Conventional GC algorithms has no **problem with reference-cycles**.   * Reference-count is generally **slower** than a proper GC. What are the reasons for using reference-counting smart pointers?


Job prospects for open source project experience

I would like to know whether work experience in Open Source Projects will really brightens the job prospects/resume of a developer other than their day time programming job or doing certifications are more than enough for a developer?


Application of LGPL license on a simple algorithm

The "scope" of the GNU license is troubling me : I know it has been answered many times ( here, here, ... ) but shouldn't we take into consideration the complexity and originality of a code before using GPL license ? I explain : I'm working on a pet project using the DTW algorithm that I have written in C using the pseudo-code given on the wikipedia page . At one point I decided to change it for a C++ implementation ( just for hone my c++ skill ) . After doing so, I've looked for an existing implementation on the web, to compare the "cleanliness" of it, and I found this one : Vectored DTW implementation, which is part of limproved, a C++ library licensed under GPL v3 . Personnally, I don't mind the GNU license because it is a personnal project, which will never led to any kind of commercial purpose, but **I wonder if this implementation can abide a company using it to open their code** ( and other FOSS permissions ). Theoretically, I think it can ( I may be wrong :p ), but the algorithm in question is so simple (and old) that it should not.


Client-Side V.S. Server-Side Searching?

I am currently helping to design a web site and application in HTML. We would like the user to be able to search the site/app for desired content via a search bar. We would also like to include an advanced search ability to allow for different search options and more concentrated searches. We are having trouble deciding whether to program the search function on the Client-Side (with JavaScript) or on the Server-Side (with PHP). What are the pros and cons of both and what would you recommend?


Computational Complexity of Correlation in Time vs Multiplication in Frequency space

I am working with 2d correlation for image processing techniques (pattern recognition etc...). I was wondering if there is a theoretical approach on how to tell when to use multiplication in frequency space over correlation in time space. For sizes of 2x frequency space is obviously faster but how about small, prime sizes like e.g. 11?


When learning Android, should I focus on the latest and greatest?

I'm a Java developer and I'm going to start working with Android to get familiar with mobile apps. I've worked with Ajax toolkits, but haven't done any mobile development. I've seen a huge change in development on certain toolkits where the learning curve really jumps up, as in GWT 1.5 versus 2.4. I'm just wanting to jump in and get the basics (along with best practices) down for now. I don't know if Android 2 versus version 4 would do that, but version 4 might just throw in extra features that I might not need to know about for now and take away from my main focus. Is it better to go with the latest version of Android or, to make sure the fundamentals are covered, take an older version that would be easier to get in and start developing with?


How to Use Subversion Repository Inside Git Repository?

I'm developing a project in Git. IT depends on another project, that's in a Subversion repository. I'd like to be able to make changes to the Subversion project in the tree, and commit to/update from the Subversion repository from within the Git project. Is that possible?


What to do when request is sent to server and while waiting for response internet connectivity lost?

I am sending a huge amount of data to server. Now while I have sent the data and waiting for server response, suddenly my android device gets internet connection lost.   So what I used to do is, showing an alert dialog of connection lost, but at server side the data was already processed and it updated somewhere e.g. on any URL. But my android phone does not know this as it did not get response ever. How to resolve it.   Whether it could be done on server side or on android itself How?   How server would know that android phone is not going to listen the response?   It may be client-server communication optimization perspective.


estimation method at the "just finished definition phase"

We are basically using Waterfall life cycle methodology. Requirement Analysis: I get a use case created by some one else. Design (talking only about Low level design): I get some little feeling about how would I design it, may be either instantly/ or after some time. Coding+Unit Testing: In case of unit Testing I am not using any TDD, but I am trying to get full code coverage, through mocks and etc. after the coding is done. I am being asked about estimates just after the Requirement walk through. Since I have only a fair amount of idea about how the design will look like, I have no way to say about estimates. As for the coding part is considered, how can I get the total number of methods at the "just finished definition phase" (I never know how much will I be refactoring at this stage), Unit Testing with full code coverage: I haven't written a code, then How can I know how many behaviors are there to test for one method and hence time. Is there some scientific way/ or other way to know this at this stage? **Note:** I have already read this possible similar question. I can break down all my tasks to small units, but I am having problem to give an estimate for each unit. **Edit1** This is part of my problem too it all started from here. Our Organization also unit tested (or correctly saying performed integration testing) manually or through emulators etc. So whenever some enhancements come for a particular client You need to create test data again, and what about any breaking changes You have introduced. So, I introducing Automated Unit Testing, but now there is again a problem for correct estimation which is necessary to give the organization farsighted view of "time estimate of creating a test suite with code" in simple words build to validation team. Kindly help.


Very-Loose Coupling and Dependency Injection for Database Management

I'm currently setting up a MongoDB database for a web-app. I'm running node.js and using Mongoose to help manage mapping, validation ect. I'm wondering if it's a good idea to really decouple MongoDB from my code, just on the off-chance we want to switch to something like CouchDB a little later. Specifically, I'd make a `databaseManger` module that is responsible for setting up Mongoose/Mongo, defining the mongoose models, managing replica sets, and doing some extra validation. This manager would export a generic API, and handle the details of the queries internally. The manager would then be passed around via dependency injection. Does this make sense? Or am I kind-of redoing some of the mongoose functionality? Any advice is appreciated.


Merge two different API calls into One

I have two different apps in my django project. One is "comment" and an other one is "files". A comment might save some file attached to it. The current way of creating a comment with attachments is by making two API calls. First one creates an actual comment and replies with the comment ID which serves as foreign key for the Files. Then for each file, a new request is made with the comment ID. Please note that file is a generic app, that can be used with other apps too. What is the cleanest way of making this into one API call? I want to have this as a single API call because I am in a situation where I need to send user an email with all the files as attachment when a comment is made. I know Queueing is the ideal way to do it. But I don't have the liberty to add queing to our stack now. So this was the only way I could think of.


Workflow on Development and Production Servers for a Consistently Updating Website

We have three developers, one system administrator, and an artist that primarily work on a single website (forum) on our spare time to consistently develop features for the forum (but there are other projects that we work on). Because our system administrator recently joined, we dropped managed hosting for a single server and decided to rent out two unmanaged servers (one for testing and the other for production). In the old server, we simply used Git as a middleman for pushing updates from the non-unified developer team into the server without conflicting updates. Pull other developer updates. Push our own updates. Revert if something breaks. Since we have two servers now, we plan to push updates to the development server and somehow have it push updates to the production server. Developer(s) -> development server (bare) -> production server We want to keep the repositories in the development server and the work tree of the web site on the production server (web server). Is there an efficient way to do this without pushing from the dev server to production? Is there a better workflow for two servers in general? P.S. The development team consists of high school teenagers and some college kids that have never developed on teams for for-profit businesses.


Game to decide which team member gets the window seat in a fair way

During team formation, we have a conflict where 2 developers both really want the same coveted window seat with a lush view of a creek & the woods. What sort of game / activity can we place them in that will:   1. Decide who gets the seat   2. Provide a random (not skill based) chance of winning   3. Allow both team members to participate in the selection   4. Not be a single player game masquerading as a two player game (drawing straws for example - the outcome is based off of the first player's actions when there's only 2 people)


How should I architect a RESTful webservice to use 3rd party (i.e. Google, Facebook, Twitter) for authentication?

For my job we have a nice RESTful webservice we've built out that we use to drive a couple websites we have. Basically the webservice lets you create and work with support tickets, and the website is responsible for the front end. Any webservice requests use an auth header which we use to validate the user and their password for each call. This year we're looking to expand our login options so that users on the website can log in via Google, Twitter, and Facebook (possibly others). However I'm having a lot of trouble figure out how to architect this so the webservice can use the 3rd party authentication providers to ensure the users is who they say they are. Is there any best practices out there for how to do this? Currently we're thinking of having the website handle authenticating the users themselves, and then use a new setSessionId call that registers their current session with the webservice back end. Each additional request to the webservice will pass along that sessionId and will validate it. These seems okay, but I have that feeling in the back of my head that I'm not thinking this through and all my forum browsing and reading oauth and openid specs is just confusing me more. Any tips for how to tackle this?