Complexity in nested loops

Foreword:   * In this post, I will make the common confusion between `O(n)` and `Theta(n)` as complexity notations.   * I will write pseudo-code to talk about algorithms, using whatever notation I find to my liking. * * * I know, yet another question about nested loops and complexity. I recently wrote a nested algorithm, that would work as a bottleneck of a more complex application. It somehow looked like this:               while(firstLoopRunning) {         foreach(element in myArray) {             doSomeAction(element);         }     }      My keen-eye brought me to the conclusion that, as doSomeAction is in `O(1)`, the algorithm had to be in `O(n²)`. I know however that nested loops can have a different complexity. For instance the following is in `O(n.log(n))`:               for(i in 0..n) // n is constant in this loop         for(j in 0..i) // j goes up to i and not to a constant             print(j);      Then I thought, hey, I know that myArray has a maximum length. In this particular case, I _know_ by design that there will never be more than 8 elements in myArray, so the algorithm could look like this:               while(firstLoopRunning) {         // Let's do this one in Java, myArray would actually be an ArrayList         try {             doSomeAction(myArray.get(0));             doSomeAction(myArray.get(1));             doSomeAction(myArray.get(2));             doSomeAction(myArray.get(3));             doSomeAction(myArray.get(4));             doSomeAction(myArray.get(5));             doSomeAction(myArray.get(6));             doSomeAction(myArray.get(7));         } catch(ArrayOutOfBoundsException ex) {            // Just a lazy way for me to avoid checking if the index exists         }     }      And voilà! Here it is in `O(n)`! Moreover, I know for a fact that compilers usually transform _fake_ loops such as this one:               for(i in 0..8) // not really a loop         someCall(i);      into a sequence of calls. Which brought me to a first conclusion: > A iteration over an array which length will have a known finite upper-bound > is in O(1). I think I'm right about this one (aka: correct me if I'm wrong). On the other hand, we are working with finite data and the whole point of the complexity theory is to work on theorically infinite data. So let's use another classical example: we are iterating over the squares in a grid (=~ bidimensional array), so clearly an `O(n²)` algorithm. What if however we would to put all the squares in a single list and change this:               // O(n²) algorithm over myGrid[][]     for(i in myGrid)         for(j in myGrid[i])             yieldAction(myGrid[i][j])      into this               // O(n) algorithm over myFlatGrid[]     for(i in myFlatGrid)         yieldAction(myFlatGrid[i mod rowLength][j])      Basically the same thing but different complexity, yet no loop has in fact been gained. Granted that the grid can grow in both dimensions so the variable really is quadratic, but in a way it can definitely be treated in a linear way (even though that's not worth it). But I must be missing something. What sense does it make that if a twist the data a litte, I can change the complexity of an algorithm on a theorical point of view although the exact same number of operations is performed?


What data is available regarding cowboy coding?

I'm not a programmer; I'm a freelance writer and researcher. I have a client who is looking for stats on certain "threats" to the apps market in general (not any specific app store). One of them is cowboy coding: specifically, he wants to see numbers regarding how many apps have failed to function as intended/crashed/removed because of errors made by, in essence, sloppy coding. Note that I'm not here to debate the merits of cowboy coding, and whether or not it is sloppy. Is there any data about this type of development?


How to make Unit Tests to make sure stored procedure is deleting row from the database?

I'm new to unit testing and I need some help with the following. I have created a small project to help me learn how to make Unit Tests. The functionality for one of the forms in my application deletes a user from the User table (and other rows in mapping tables). Currently, the unit test I have created to test this sets up the required objects and then calls the business rules method (passing in the user id) which calls the data access method to execute the stored procedure that deletes the rows in the tables. Is this the correct method to test whether something is being deleted successfully? Should the unit test / setup method first insert some test data which the unit test then deletes?


Automatically update copyright date range from git?

As I write, we're 10 days into 2012. I bet many programmers are editing the copyright string at the top of their source files to something like:               // Copyright 2008, 2010-2012 Some Company Unlimited      Your version control system knows when files were modified so surely it can help write or rewrite these strings. So my question: is there a script that can examine git logs for each file and output (or better insert) a string like that about? I'm using git so that's of primary interest but do let me know if such scripts exist for other systems. **Update:** We need a script that does this:   * Walks all source files in our working copy   * Locates existing copyright string and identifies years e.g. 2007,2009-2011 would be {2007, 2009, 2010, 2011}   * For each year that is not mentioned, diff between 1 Jan and 31 Dec (or today if current year). Examine diff and decide if it's worthy of a mention in the copyright string   * Insert new copyright string.


What does it mean for SVN "to pollute the local source tree"?

I'm reading "Professional Team Foundation Server 2010" by Wrox, and in an advantages/disadvantages list, the said: "Like CVS, SVN makes use of .svn directories inside the source folders to store state of the local working copy, and to allow synchronization with the server. However, it can have the affect of polluting the local source tree, and can cause performance issues wiht very large projects or files." What does the bit about pollution mean? I've used SVN for C# & ASP.NET projects for a long time and haven't encountered any problems. What probably does this quote think I should have been watching out for?


Drag and drop application design

I am hoping to create a mind-mapping like application and it needs to have a central workspace that will hold the map. Users should be able to drag items (like rectangles, texts, etc.) from a container to the workspace. The important thing is when a user is dragging an element to the workspace, _the element should move with the mouse, **not** just the text._ What I'm looking for is something like the web apps LucidChart, Cacoo, MindMeister, etc. So is this possible to do in Java without too much hassle? And if yes, what is the application design (algorithm)? I have searched many resources but have only found ways to drag only the text, images or the like. Not the entire element itself. It would be even better if I could make it to drag an entire JButton, so the users can create a map of JButtons. Sorry if this is not the place to post this (should I post it in StackOverflow or here?).


Safari for windows not showing that my ipad is connected

I want to inspect some code on the ipad and I have enabled the developer menu on safari(windows version). However, my safari developer menu doesn't detect the ipad that is connected to it via the usb ... Version of ipad ios - 6 Version of Windows - 7 Version of installed Safari - 5.1.7 How do I make this happen ?


Using SVN poorly - is Mercurial the answer?

At work we use SVN, but in name only. We don't branch or merge. We keep two copies of the repository, one serving as the "tag" branch that gets copied when we do a deployment and kept for bug fixes and immediate "this has to go live asap" type of features. We have to remember to copy changes made in one copy to the other copy (the "trunk"). We have a dozen projects inside a single folder in the repository, instead of splitting them out. In short about the only thing we use SVN for is being able to commit. Everything else is done manually. I've been evaluating Mercurial; I have used Git in the past (I'm the only one on the team who has used a DVCS), and I'm picking up Mercurial quickly. I'm debating introducing Mercurial to the rest of the team as a "better way" of doing things because branching is a snap, merging is a lot easier, and we can commit things locally to our heart's content and only push them to the central branch when they're ready. We would get all of the benefits of SVN (and we aren't getting many benefits right now anyway since nobody really understands SVN) plus for new features we don't have to have tons of unversioned files floating about so if we have to rollback we're screwed. The workflow seems a bit simpler - we just have to remember that "Commit" is local and "Push" is like SVN's commit, and "Pull" is like SVN's Update (what the team refers to as "get latest"). Is this a good approach to take? Keep in mind that the team is very flexible and will go along with anything that will improve our quality of work and make how we do things easier - the CIO even asked me when I mentioned how we weren't using SVN to it's potential "Is there something better we can use?" so he's on board with it too.


Database Password problem when using GIT to manage project that uses Spring to initiate Datasource

## Program Situation I use Spring Framework to code my Web Service, using Dependency injection to inject a DataSource bean into the DAO bean that will be used by the Web Service. I have all the database properties(Url, Password, Username, the stuff I don't want people to see) written in the DataSource Bean XML! ## Workplace Situation I have git setup to commit my entire project....(Hint: Including my DataSource Bean XML which has my password written in plain text) I thought of using the .gitignore but the Bean XML is a crucial component in my Web Service project and it shouldn't be ignored. (Right?) But I also don't want the world to see my password. **_What should I do?_**


w3c library license: does it prevent the inclusion in/distribution with paid software?

From W3C Software Notice and License: > Permission to copy, modify, and distribute this software and its > documentation, with or without modification, for any purpose and without fee > or royalty is hereby granted My app depends on the xml-apis 1.4.01 library that in turn includes W3C software and I need to distribute it along with my non-free app. I am not explicitly charging for the included xml-apis/W3C components. Does the stated license statement exclude such a paid distribution? Don't answer if you are not aware of the GPL linking exception.


User defined type for healthcare / Medical Records variable name prefixes?

I was reading Code Complete regarding variable naming in trying to find an answer to this question and stumbled on a table of commonly accepted prefixes for programming word processor software. Well, I'm not a word processor software programmer, but if I was, I'd be happy to use those user defined types. Since I'm a programmer for a smallish healthcare ISV, and have no contact with the larger community of healthcare software programmers (other than the neglected and forsaken HealthCareIT.SE where I never had the chance to ask this question). I want to know if there is a coding convention for medical records. Like Patient = pnt and Chart = chrt and Medication = med or mdctn or whatever. I'm not talking full on hungarian notation, but just a standard that would fit in code complete in place of that wonderful chart of word processor UDT's which are of so little use to me.


Implementing multiple tables for the same entity due to processing power on Client apps

I reached a design/architectural issue on the large application I'm working on, at the point of writing possibles solutions on a chalkboard. Our product consist of a **client-server** information system whose implementation was built on REST paradigms. A particular use case defines the use of multiple resources (most of them available only server-side) in order to process data into actual information, before being sent to the client-side. You can think of it as a massive processing of a queried resources **to present them in a certain order**. It's almost like **a huge sorting algorithm**. Due to the fact that most of the resources used by the algorithm are available only server-side (because they don't fulfill any other purpose on the client) and the fact that massive processing power is needed to perform it, it's not practical to reproduce this client-side. Also to prevent possible reverse- engineering. To fulfill a requirement we need to implement local storage on the client-side application, which means we would need to present this _sorted_ information even if no network is available. In order to present them, we are considering the possibility of duplicating the database table for this resource, into a table that will be used only to store already sorted results. To this point, what are the advantages and disadvantages of this approach, and what best practices are going to be needed into consideration. I'm also open to any design pattern, used to solve this problem, that I'm not aware of.


How to collect industry usage of data persistence technologies?

In our organization, we are using various data access/persistence technologies in different projects. The ones used till now are Hibernate, JPA, Spring Data JPA, JDBC, Spring JDBC, MyBatis, and QueryDSL. How do I find out what is the industry usage of these technologies? i.e. which is used more widely than others - or even a pie chart showing the distribution of such technologies. Also curious to know which technologies are being used by major players - like big silicon valley companies, or prominent investment firms. Do you know a way to find this data? Can the firms like Forrester or Gartner would have such a data? Thanks in advance.


Is an agile methodology appropriate in this situation?

Imagine a project where the interface to be delivered has been locked down 90%, and you are already in possession of a solid architectural design. Would an agile methodology still offer any value in this situation? It seems to me that agile methodologies (and I'm thinking Scrum), offer most value where there is a high degree of uncertainty about the requirements.


Do professional software developers still dream of creating industry/world-changing apps?

I'm a hobby programmer. The absence of real world deadlines, customer feedback, or performance reviews leaves me free to daydream about having and implementing The Next Great Idea That Changes the World. Of course I'm aware I probably have a better chance of winning the lottery, but it's fun to imagine knocking out some fully-homebrewed app that destroys the status quo. I know many professional programmers have side projects, some for profit others not. I was wondering on the way to work this morning (non-IT boring work) if having to code for your food tended to dampen the dreaming? Does greater experience leave you jaded and more focused on the projects at hand? Not trying to be a downer, just interested in the mindset of the real software professional :-)


What constitutes a programming language and how does one copyright a programming language?

I've decided to create a programming language of my own, mostly just for fun. However, I got interested in the legal aspect of it all. You can, for example, licence specific programs under specific terms. However, how do you go about licensing a _language_? Also, by that I don't just mean the implementation of the language (compiler & VM), but the standard itself. Is there something else to a programming language I'm missing? What I would like to achieve by such licensing:   1. Make it completely FOSS (can a language even be FOSS, or is that the implementation that can be FOSS?)   2. Establish myself as the author (can you legally be an author of a language? Or, again, just the implementation?)   3. Make it so that anyone implementing my language would be required to attribute me (MIT-style. Please note that I do not have any hopes for anyone actually ever doing that though, I'm just learning.) I think that the solution would be to separately license the VM and the compiler for my language, as "the official implementation", and then license the design document _as the language itself_. What exactly am I missing here?


What's new in Expert F# 2.0?

I own the first edition of Expert F# by Don, et al. and I'm considering buying the next edition, Expert F# 2.0. But I'm wondering if it's worth it. Sure the syntax will be updated and all, but I'd be more interested if there were new topics covered or just compelling expanded coverage of the same topics otherwise. Glad to hear from anyone who owns both editions, thanks.


Does Visual Studio 2012 Express support NUnit tests?

I am currently using Visual Studio Express 2012 Desktop (the free version). I now have received source code with NUnit tests included. I can not bring them to run with Visual Studio (not seeing them in the Test Explorer) and I seem not able to install the official NUnit Plugin. **Can someone confirm that the Express version does not support nUnit or tell me how to do it?**


What is the meaning of # in R5RS Scheme number literals

There _is_ a partial answer on Stack Overflow, but I'm asking something a teeny bit more specific than the answers there. So... Does the formal semantics (Section 7.2) specify the meaning of such a numeric literal? Does it specify the meaning of numeric operations on the value resulting from interpreting the literal? If yes, what are the meanings (in English -- denotational semantics is all greek characters to me :))?


How does event bubbling generally work and is it synonym to event propagation?

I'm trying to wrap my head around the general workings and principles of event dispatching in event-driven (sub-)systems. Although I have used it on quite a few occasions in for instance Javascript, Flash (Actionscript 2 and 3) and have even made a simple event dispatching system in PHP for myself at one time, I've never really understood event bubbling and/or propagation that well. **First question:**   Is event bubbling synonym to event propagation? **Second question:**   Am I correct in my understanding that when an event "bubbles", this means that it gets "moved" up the hierarchy of objects? **Third and most important question:**   If my understanding in question 2 is correct; how is this "moving" up the hierarchy of objects generally implemented?   Does it generally mean that the parent object "redispatches" the same event to _its_ parent (until it reaches the root object)? And if so; do all these objects in the hierarchy need to listen to their children for these events, or am I missing something vital principle in my understanding about event bubbling, where there's no need to let parent object register them selfs as listeners of child object events? If you could illustrate these basic principles by means of some simple pseudo code, I'd be more than grateful.


What is software maintenance?

I'm a hobbyist programmer, so no professional experience. People here often talk about doing maintenance of software at work. The author of this question talks about doing 90% maintenance and 10% development at his job. My question is: what is 'software maintenance' anyway? Is it mainly about fixing bugs? If so, does that mean that people spend most of their time at work fixing bugs? Or does 'maintenance' include other things, other than bug fixing?


Is double password protection safe for admin authentication?

I was looking at some of my past codes, and I viewed one of my admin boards I've made. I had it setup so that the admin has to define/enter 2 passwords for his account. Is this really double-safe or was I deluded? It seems that it's reaaally hard to force-match username and 2 passwords from the client side. I've got it limited to 100 tries, dogh...


How to make non-technical management more realistic when it comes to developing software

I manage a small in-house development team for a large organization. We develop for both internal and external clients. I find it impossible to educate the non-technical senior management about the importance of team work, testing, etc etc. However, the most difficult thing is trying to make non-technical people understand what is realistic to expect from us in terms of running concurrent projects and timescales etc. It is definitely still a case of people think we just press a few buttons and applications build themselves. Does anyone know of a simple business case template for non-technical managers to justify the investment in my team's time?


Mobile Web Framework that will only control rendering and page transitions

I have been using jQueryMobile for a bit now, and there are some things I like about it and others I do not. First I will give a bit of background. I have a light weight mobile application that has a few configurations and 6 pages. Ideally I Would like to load all pages into the DOM (they interact with each other quite often and pages will be switched in the same frequency). The application will post for some JSON every **_n_** seconds and refresh the values on the page (yes it is primarily a information display app). with the jQuery Mobile framework the only real thing I like is how easy it is to have a standardized UI a crossed all devices and browsers, I'm really not using too much else out of the framework other than the basic page navigation (if you are familiar with the framework; a bare-bone multi-page design is all i need). Why I want to step away from jQueryMobile is how weighty it is. Not only do you need to include the mobile library, but also the base jQuery libraries. This I do not like because I'm not using jQuery anywhere else on the site. Any suggestions on light-weight mobile frameworks that have a similar rendering as jQueryMobile?


Programmer's blog - How often should I post?

I've decided to write a blog to see if it helps me, and maybe even others, as programmers, and to help invest myself in programming communities. Because I've just started, I have plenty of ideas, but I've been unsure if I should write articles on all these ideas at once, or space them out more regularly. I'm guessing it won't matter if I write them quickly, but I was concerned that my other content would be lost behind the newer content, and that I could exhaust content too quickly before I think of more topics. So, should I write them quickly as possible, or publish them more slowly and regularly?


Why are PHP function signatures so inconsistent?

I was going through some PHP functions and I could not help notice the following:               <?php     function foo(&$var) { }          foo($a); // $a is "created" and assigned to null          $b = array();     foo($b['b']);     var_dump(array_key_exists('b', $b)); // bool(true)          $c = new StdClass;     foo($c->d);     var_dump(property_exists($c, 'd')); // bool(true)     ?>      Notice the `array_key_exists()` and `property_exists()` function. In the first one, the property name(key for an array) is the first parameter while in the second one it is the second parameter. By intuition, one would expect them to have similar signature. This can lead to confusion and the development time may be wasted by making corrections of this type. Shouldn't PHP, or any language for that matter, consider making the signatures of related functions consistent?


Server-side event logs through DB or writing to file?

I am developing a web application as well as the API the web application uses. I'm trying to determine whether it is better to log events (to determine the path that leads to an error as well as to determine whether the site has been compromised) in a database or simply by writing to a file. On the one hand, I don't want to bog down my database with a queries every single time I need to log an error. On the other hand, I don't want to have to dig through a giant event / error log file. I'm thinking of turning into re- write mode once the file / table reaches 10,000 or 100,000 events. I know the general factors I should consider:   1. Performance (both DB and general--in my case I'm using PHP and Postgres)   2. Ease of finding the path a user took to create a bug or error (I'm almost certain DB is better for this)   3. Scalability - Is this the same solution I'm going to be using with 20 users as I am with 100,000 users? Can you tell me how these two possible solutions fit in with the above-- really, I think the most important one for me is performance. How demanding is it to write to a file vs. writing to a DB and if every single event and command sent by the user (and there will be many) is logged (before a re-write limit), which solution will end up being faster?


Is there a correlation between buzz words and ability?

We've just been through a hiring cycle and one thing that struck me was the fact that interviewees that threw every buzz word on the planet at us tended to rate the lowest. We gave them each a simple design problem and asked them how they would approach it. The people that sketched a simple process flow on the board were generally the ones that impressed. The ones that leant back and then said something like "This look like a typical xxx pattern. It's an interesting paradigm and probably requires a phase-shift in your current methodology" didn't generally impress.


What are the advantages to BDD for a solo developer?

I have found this lines below about the advantages of BDD (Behavior Driven Development) > The domain experts define what they need in the program in a way that the > developers can not misinterpret (or at least not as much as in most other > approaches). Are there any more advantages apart from that?   If I'm working alone (I'm not in contact with managers that could write BDD features),   do I need to use BDD?


Career advice: stay with PHP or start a new career in something else ( .Net?)

I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes. I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen. So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites. My main concerns are the following:   1. Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.   2. Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :). Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs. PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family. I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome. **Update** Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.


Help on clarification of a formal statement concerning algorithms running time

I am reading the following in a book on algorithms (Cormen's to be specific): > That is, we are concerned with how the running time of an algorithm > increases with the size of the input in the limit, as the size of the input > increases without bound. I can not understand what is the meaning of the phrase: `with the size of the input in the limit`.   What is the limit refering about? **UPDATE:** Please note that at this point in the book (early fundamentals of chapter 2) there has been no formal definition or mention of Big O or other asymptotic notation except a vague reference on Theta notation Any help?


When would be the best time to start porting the code of my own project?

If I have a personal programming project that I plan to port in another language so it could run in other environments, would it be more ideal to start porting the code as soon as possible and work on two versions concurrently? Or would that slow down my production a lot, and should I wait until I have finished some key components of the program?


Transform math formula into code (line-line intersection)

I'm having hard times transforming a math formula to code. I can solve it on the paper easily, but it's hard for me to bring it into code form. Is it generally possible to bring a math formula _directly_ into a program, or, if not, how can it be transferred? Taking, for example, the Pythagorean Theorem: `a² + b² = c²`. Having `a` and `b` defined in the code, it is straight forward to apply this formula.               c = sqrt(pow(a, 2) + pow(b, 2))      Currently, I'm having hard times bringing the line-line intersection, that I've solved on paper, into my program. Assuming a line being defined as `L: O + a * D`, one can find the intersection of two lines by setting them as equal.               L1: O1 + a * D1     L2: O2 + b * D2          => O1 + a * D1 = O2 + b * D2      Using pen an paper, I would have already defined values and can solve the equation by splitting the equation into three sub-equations and applying simple substituion (I hope you can read my hand writing): ![enter image description here](http://i.stack.imgur.com/APIIP.jpg) ## My actual problem ... is that substitution can not be applied algorithmically, or I don't know how to do. The equation `L1 = L2` must be transformed to a generalized formula that can be directly translated into code (like `a² + b² = c²`), but I don't know how. I was hoping for a step-by-step explanation (either as answer or linked) on how to come to the formula/algorithm I am searching for. I know there are quite many websites that describe the intersection of two lines, but I would like to understand how to find the algorithm **from a mathematical starting point**.


TDD - Outside In vs Inside Out

What is the difference between building an application **Outside In** vs building it **Inside Out** using TDD? These are the books I read about TDD and unit testing:   Test Driven Development: By Example   Test-Driven Development: A Practical Guide: A Practical Guide   Real-World Solutions for Developing High-Quality PHP Frameworks and Applications   Test-Driven Development in Microsoft .NET   xUnit Test Patterns: Refactoring Test Code   The Art of Unit Testing: With Examples in .Net   Growing Object-Oriented Software, Guided by Tests\--->This one was really hard to understand since JAVA isn't my primary language :) Almost all of them explained TDD basics and unit testing in general, but with little mention of the different ways the application can be constructed. Another thing I noticed is that most of these books (if not all) ignore the design phase when writing the application. They focus more on writing the test cases quickly and letting the design emerge by itself. However, I came across a paragraph in xUnit Test Patterns that discussed the ways people approach TDD. There are 2 schools out there **Outside In** vs **Inside Out**. Sadly the book doesn't elaborate more on this point. I wish to know what is the main difference between these 2 cases.   When should I use each one of them?   To a TDD beginner which one is easier to grasp?   What is the drawbacks of each method?   Is there any materials out there that discuss this topic specifically?


Building an RPC framework

I'm curious about what it takes to build a simple and robust RPC framework. I've only looked at a few ruby frameworks but they are all lacking in some way. What I want out of an RPC framework is some kind of registration/discovery mechanism and a simple plugin architecture. Pretty much all the frameworks out there provide a simple plugin mechanism but I haven't found one that provides a simple discovery mechanism. The only one that does provide something in terms of discovery is MCollective but that has its own set of issues that I've run into while trying to use it at work. So how hard would it be to build one from the ground up using tcp sockets or maybe 0MQ? Any issues I should be aware of ahead of time before I start this project?


NoSQL (Azure Table Storage) RowKey design for ordered data

I store large quantities of GPS data in storage tables. Each partition can reach up to 1 million entities. Each GPS entity that is inserted into the table is actually sequential to the previous data inserted, so order matters. Sometimes I need to perform the following query: > _**Get the previous/next 3 GPS entities from the current entity (within the > same partition)._** Options for RowKey design:   1. **Create an incrementing integer.** But how do I track what the current size of the table is? There is no way to get table row count, or to get the last inserted row.   2. **Use DateTime Ticks.** But how do get the previous/next entity using ticks? I'm using the SDK version 2.0 in C#.


Not getting paid for hours you've worked?

So I was reading from a previous thread about App vs Game Development:   If it was for you to chose Game Development vs Application Development, which will you chose? Which brought me to this site: EA: The Human Story A lot of it talked about developers working something like 85 hours a week, and not getting paid overtime, or anything. Just getting paid for the 40 hours. Is this normal for most software companies? I mean where I work I'm only an entry level guy but I get overtime, and anything over 40 hours is considered this. But it got me thinking "Holy crap" I could never do that. My FREE time is important to me. But is this commonplace in most software companies? Or is more a rarity to certain types (game development, etc)? Because it got me scared! Like I understand having to put some extra hours in for a project... but like 80! that's ridiculous.


What is the best way to learn how to develop secure applications?

I would like to get into computer security in my career. What are the best ways to learn how to program securely? It seems to me that, besides textbooks and taking classes in the subject, perhaps learning how to "hack" would be one of the best ways to learn. My reason for thinking this is the thought that the best way to learn how to prevent someone from doing what you don't want them to is to learn what they're capable of doing. If this is the case, then this poses another question: How would you go about learning to hack in an ethical manner? I definitely don't want to break laws or cause harm in my quest.


Haskell web frameworks survey

There are several web frameworks for Haskell like Happstack, Snap, and Yesod, and probably a few more. In what aspects do they differ from each other? For example:   * features (e.g. server only, or also client scripting, easy support for different kinds of database)   * maturity (e.g. stability, documentation quality)   * scalability (e.g. performance, handy abstraction)   * main targets Also, what are examples of real-world sites / web apps using these frameworks? Many thanks.


What to Return with Async CRUD methods

While there is a similar question focused on Java, I've been in debates with utilizing Task objects. What's the best way to handle returns on CRUD methods (and similar)? Common returns we've seen over the years are:   * Void (no return unless there is an exception)   * Boolean (True on Success, False on Failure, exception on unhandled failure)   * Int or GUID (Return the newly created objects Id, 0 or null on failure, exception on unhandled failure)   * The updated Object (exception on failure)   * Result Object (Object that houses the manipulated object's ID, Boolean or status field to with success or failure indicated, Exception information if there was one, etc) The concern comes into play as we've started moving over to utilizing C# 5's Async functionality, and this brought the question up of how we should handle CRUD returns large-scale. In our systems we have a little of everything in regards to what we return, we want to make these returns standardized... Now the question is what is the recommended standard? Is there even a recommended standard yet? (I realize we need to decide our standard, but typically we do so by looking at best practices, see if it makes sense for us and go from there, but here we're not finding much to work with)


Approaching SICP in Clojure instead of Scheme

I am a third year bachelor student in a software engineering program, and I brought up the idea of reading SICP to an adviser to gain a deeper and more fundamental understanding of the principles behind all this software we engineer. He suggested not to learn Scheme to complete the book (because it's not as common as modern dialects of Lisp) but to do the exercises in Clojure instead. It's an already difficult book, if I do attempt the book's exercises in the more modern Clojure, how would that work? For example, I can't find any real solutions, the syntax they teach for Scheme is different, etc.


ANSI C pointers corrupted values

I am working on ANSI C and having some issues with the pointers. That is that after a point in my program the pointer's values change without me interfering, is something like overwriting them. I know that this could happen in C, but while being a beginner, can not find a remedy for that. Is there a straightforward way of solving this? As I understand, many people will have faced similar issues. Thank you guys for your answers,were very helpful,was indeed a memory problem solved by just allocating larger blocks of memory!!! Thank you again!!!!


Next power of 2 for a number (in search for better "bit-twiddling" way)

I just wonder if there exists _better_ (i.e. faster?) way to get the next power of 2 for a given number than the following one (maybe some _better_ sort of "bit-twiddling" hack is possible?) ...               static size_t     npow2(size_t n)     {             n--;             n |= n >> 1;             n |= n >> 2;             n |= n >> 4;             n |= n >> 8;             n |= n >> 16;             return n + 1;     }      Thanks for your ideas.


Importing Data from Google Analytics

I am planning on building a web app with many different public-facing HTTP servers; each of which will have Google Analytics (GA) installed on them. I'd like to create a "dashboard" app that consolidates the GA data into one screen. I've been perusing the documentation for this so-called GA API, but I can't tell what the end result of the GA API is:   * Does the GA API allow me to do exactly what I am looking for it to do? Or...   * Does the GA API do something entirely different (like allow me to share my data with Google+ or something else weird) Since an API can be used to CRUD any kind of data, I guess I'm asking which way the GA API goes: is it for querying (reading) data from 1+ server instances, or is it for modifying data on those servers or somewhere else? Thanks in advance!


What order do you develop program layers?

I liked the question about favorite program layer: What is your favorite program layer to work on? What order do you build them in or do different team members develop corresponding parts simultaneously?


What are deferred callbacks?

I understand the idea of a callback, where I pass a function into another function and that function then uses the supplied function at will. I am struggling to understand deferred callbacks, even after googling it. Could someone provide a simple explanation please? I program in Ruby, but also know C/C++ a bit, but most of all I was a experienced assembly language programmer. So I am wondering is it a bit like a stack of callback addresses that get pop'd? I am hoping to learn jquery or node.js and these deferred callbacks seem integral to both. I understand basic threading principles (though mutex object makes my head hurt ;)


Test Driven Development for Complex Games

I'm coding a game in my spare time, but I am mostly still a beginner when it comes to programming. I'm sorry if this question is off topic or if it ends up not being helpful to anyone else, but hopefully it will be. I've spent a lot of time reading books about the design of code, as well as different methodologies and approaches to coding. In the course of this research I keep running into the concept of Test Driven Development. The people who espouse this idea usually seem very passionate about it. I do believe that it can help the speed and efficiency of writing software. Time is a very precious resource so I would rather learn to do things the best way rather than muddle through without trying to expand my knowledge of the programming craft. Anyway, possibly because I am a beginner, I cannot imagine how to apply test driven development to games. I've found a couple of articles on the subject but they were not very helpful. Most of the examples of unit tests that I have seen are very simple boilerplate examples, or examples from software that is not at all like a game. In my own coding, I try to approach it with a similar mindset to test driven development, although I'm sure it does not actually qualify as TDD. I write the minimum amount of code to try to implement whatever feature I am adding to the game, and then I immediately test the game to see if it works. If things don't happen as I intended, I immediately make changes to get it closer to what I want. If it is not working or broken, and if I cannot find the bugs by reading the code, I step through the methods in the debugger until I find the unexpected behavior, and then I remove it. What I am trying to say is that I am constantly testing the game, pretty much after each and every incremental change. Testing drives my development. The "unit test" is in my head, because for example I know what the unit in my game is supposed to be doing, so I test to make sure that it is doing it, and if not, I try to fix it right away. On to my actual question. How can one write unit tests for a complex game? By complex, I mean with many emergent aspects of gameplay, such that the meat of the gameplay emerges from the interaction between the many different elements inside the game combined with the player's choices. For example, a roguelike rpg with a procedural world. What kind of unit tests would one write for a game like that? How could one apply test driven development to such a game?


I have a legacy project that I'm working on, how should I improve its structure?

I have a slightly old PHP project I'm working on for a client (I think it was started around 5 years ago), it makes extensive use of the outmoded `mysql_query` function, which is concerning not only because it's now deprecated but because it could also open security holes. The project doesn't seem to have much of a structure either, I think the original developer had some kind of method when working on it, but there's no documentation and I'm not able to get in contact with him regarding said project. As I've been going through I've been switching the database queries to use PDO, and trying to clean things up a little, but it's quite a big project (a few hundred php files) and I don't want to spend too much time restructuring things at it detracts from the time I've got allotted to this each month. What should I do? Would a rewrite be a good idea? Or should I simply try and re-mold the current project into something a little nicer?


Android Icons Square

I created an action bar icon for an Android app I'm working on and it seems to downscale my icon. The thing is, it isn't a square icon. The width is greater than the height. Do I really HAVE to provide square icons or is there a workaround for this? I don't really want to ditch my icons just because of this...


What are the key differences between Java's and Python's OOP support?

The only language I've ever used is Java. I like it a lot but decided it's time to learn another language :) . I'm interested in learning Python. It seems like a good choice because it's partly similar to Java (e.g. full class based OOP support) and partly very different (e.g. dynamically typed). I was reading some tutorials and am starting to learn the basics. Some of what I've read so far is confusing and I'm starting to think that maybe there are major differences in the OOP implementation of the two languages. I want a clear picture of this: please explain the key differences of the OOP support between the two languages.


Asynchronous Web Language

I'm searching for a suitable way to make web requests to databases and display results in real-time. The data will be used in an interface for staff, so there cannot be any blocking or lag as time is a key factor. So far, I've been using PHP for the backend of the system. However now that I've come to the interface, I'm slightly stuck. I've used java (android) asynchronously before, and ideally am after a similar method of processing calls. From what I've read there is no current way of using php truly asynchronously. **What** is a good web language to use for this purpose? or what are my available options?


In an interview, is it better to code a brute-force solution to a tough question, or to spend the interview examining the question carefully?

Sometimes interview questions are hard, whether the interviewer intends them to be, or not. It can come down to a choice of whether to use the limited interview time to code up an ugly, inefficient, brute-force solution, or spend the time understanding every aspect of the problem with the interviewer. For example, Problem 91 at Project Euler can be solved by a not-so difficult brute-force solution of calculating every possible triangle, writing an isRightTriangle() test, and popping all triangles that pass the test into a set. But the two pair of X/Y coordinates make that an O(x^4) solution with a high constant value. A friend and I just came up with a solution that is much more elegant and efficient, but the two of us spent 3 hours on it and drew dozens of diagrams, tested multiple formulae, examined multiple approaches, etc. Not every interview question is fair. Also what's easy for one person may be hard for another. If someone struggles with a question, would you be more impressed by a brute force ugly solution that works? Or excellent problem comprehension and in-roads toward an elegant solution, but no coded solution? Is there a rule like after 20 minutes you should just start coding no matter what?


How to force evaluation in Haskell?

I am relatively new to Haskell and I am trying to learn how different actions can be executed in sequence using the do notation. In particular, I am writing a program to benchmark an algorithm (a function)               foo :: [String] -> [String]      To this purpose I would like to write a function like               import System.CPUTime          benchmark :: [String] -> IO Integer     benchmark inputList = do                              start <- getCPUTime                              let r = foo inputList                              end <- getCPUTime                              return (end - start) -- Possible conversion needed.      The last line might need a conversion (e.g. to milliseconds) but this is not the topic of this question. Is this the correct way to measure the time needed to compute function foo on some argument inputList? In other words, will the expression `foo inputList` be completely reduced before the action `end <- getCPUTime` is executed? Or will `r` only be bound to the thunk `foo inputList`? More in general, how can I ensure that an expression is completely evaluated before some action is executed?


Why does F# Core define generic array types?

I just noticed that the FSharp.Core namespace includes generic array types of up to 4 dimensions, i.e. Core.[]<'T>, Core.[,]<'T>, etc. C# and VB seem to be doing just fine with System.Array - although it's not clear to me how they manage to support strongly-typed specialized array types like int[], string[]. I guess this becomes two questions then:   * How does C# support strongly-typed specialized array types like int[] based on the non-generic System.Array?   * Given that C# manages to do this, why does F# define generic array types?


How would you test Google Maps "Get Directions" feature?

(I imagine this would be a good interview question, but in my case it's more pragmatic than that.) We have a large & complex application that models an extremely long and sophisticated chemical reaction process between dozens of chemical components. We are at the stage of designing Acceptance Tests for the application, but we are somewhat daunted by the intractable number of possible paths to test. It occurred to me that our situation is very much like what the Google Maps dev team must have faced when it came time to test the route-planning algorithm in their "Get Directions" feature. Obviously they couldn't test (verify and validate) every possible route. So how did they get confidence that their application would work in every situation? And since I don't expect to find out how _they_ did it, let me ask you: How would _you_ go about designing a test suite with adequate code coverage, to satisfy yourself that a given application is robust -- when it is literally impossible to probe every potential path through the system? What I'm looking for are the principles that you would use to break down an intractable problem into smaller, tractable pieces, the sum of which provide a satisfactory estimate of the whole: "I can't test everything, but I can test this, this and this -- and that's enough." I'm not looking for an approach that is "provably correct", but rather one that is _prudent_ , given real- world budget/time constraints. (I'm using the Google maps example as something of a foil to solicit answers that are as specific as possible.)


Passing functions into other functions as parameters, bad practice?

We've been in the process of changing how our AS3 application talks to our back end and we're in the process of implementing a REST system to replace our old one. Sadly the developer who started the work is now on long term sick leave and it's been handed over to me. I've been working with it for the past week or so now and I understand the system, but there's one thing that's been worrying me. There seems to be a lot of passing of functions into functions. For example our class that makes the call to our servers takes in a function that it will then call and pass an object to when the process is complete and errors have been handled etc. It's giving me that "bad feeling" where I feel like it's horrible practice and I can think of some reasons why but I want some confirmation before I propose a re-work to system. I was wondering if anyone had any experience with this possible problem?


Is iron ruby on Silverlight a viable alternative to C#?

I've heard a lot of buzz about the Iron languages.. I mostly write line of business applications in c# and I'm not really enjoying c# these days. Is IronRuby mature and fast enough to be used in silverlight right now? As in am I gonna get a call in the middle of the night from an angry customer cause the silverlight app they depend on is buggy / grindingly slow?


Which language was used to create Visual Studio 2010?

In order to produce a plug in and incorporate it (merge) easily with Visual Studio 2010. I was wondering which language was used by Microsoft to create it? In order to offer our product to Microsoft, we must know which language is better to integrate with Visual Studio. Was it pure C++? A friend of mine told me it was written in C#.


Is your physical programming environment organized?

So the question is this: wherever you sit down and do your magic, is it neat and organized or chaotic and in disarray ? Do you find that your level of organization follows linearly with your current position in the project? (ie. The project is on track and life is good, few bugs and major milestones are being met, desk is clean enough to do brain surgery or the project is way off track, bugs are flying everywhere and my desk is a dumpster)


Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?

I believe it is. Why?   1. I've encountered many Software Engineers who believe they are somehow superior to QA engineers. I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.   2. The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.   3. The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.   4. A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's. Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer. What do you all think?


Project structure: where to put business logic

First of all, I'm not asking where does business logic belong. This has been asked before and most answers I've read agree in that it belongs in the model: Where to put business logic in MVC design?   How much business logic should be allowed to exist in the controller layer?   How accurate is "Business logic should be in a service, not in a model"?   Why put the business logic in the model? What happens when I have multiple types of storage?   However people disagree in the way this logic should be distributed across classes. There seem to exist three major currents of thought:   1. Fat model with business logic inside ~~entity~~ classes.   2. Anemic model and business logic in "Service" classes.   3. It depends. I find all of them problematic. The first option is what most Fowlerites stick to. The problem with a fat model is that sometimes a business logic funtion is not only related to a class, and instead uses a bunch of other classes. If, for example, we are developing a web store, there should be a function that calcs an order's total. We could think of putting this function inside the Order class, but what actually happens is that the logic needs to use different classes, not only data contained in the Order class, but also in the User class, the Session class, and maybe the Tax class, Country class, or Giftcard, Payment, etc. Some of these classes could be composed inside the Order class, but some others not. Sorry if the example is not very good, but I hope you understand what I mean. Putting such a function inside the Order class would break the single responsibility principle, adding unnecesary dependences. The business logic would be scattered across entity classes, making it hard to find. The second option is the one I usually follow, but after many projects I'm still in doubt about how to name the class or classes holding the business logic. In my company we usually develop apps with offline capabilities. The user is able to perform entire transactions offline, so all validation and business rules should be implemented in the client, and then there's usually a background thread that syncs with the server. So we usually have the following classes/packages in every project:   * Data model (DTOs)   * Data Access Layer (Persistence)   * Web Services layer (Usually one class per WS, and one method per WS method). Now for the business logic, what is the standard approach? A single class holding all the logic? Multiple classes? (if so, what criteria is used to distribute the logic across them?). And how should we name them? FooManager? FooService? (I know the last one is common, but in our case it is bad naming because the WS layer usually has classes named FooWebService). The third option is probably the right one, but it is also devoid of any useful info. To sum up:     * I don't like the first approach, but I accept that I might have been unable to fully understand the Zen of it. So if you advocate for fat models as the only and universal solution you are welcome to post links explaining how to do it the right way.   * I'd like to know what is the standard design and naming conventions for the second approach in OO languages. Class names and package structure, in particular. It would also be helpful too if you could include links to Open Source projects showing how it is done. Thanks in advance.


How can I judge whether a project is particularly complex or if I'm just slow in picking it up?

I'm making little progress on a major project. The source is massive, many layers of objects, macaroni code, double-diamond graphs of multiple inheritance, half-baked features frozen when the original writer left, and no one knows why many pieces of it were designed the way they were. So, I suppose any competent programmer would have some trouble figuring it all out well enough to fix bugs, finish the half-baked stuff and add new features. But I suspect I'm going slower than a typical programmer. How to judge whether the source is unusually bad, and I'm just doing as well as anyone could, versus the source is typical for a project like this and I'm just slow-witted or underskilled?


Should I use WADL to describe my RESTful API?

I'm about to embark on a project that makes extensive use of a properly RESTful approach. That is, it uses HATEOAS and serves up resources in a manner that allows for general exploration by a client. I would like to ensure that I provide a description of my endpoints in a manner that would allow client applications to be automatically generated in a wide variety of languages. I understand that for SOAP based web services I can use WSDL and that apparently there is WSDL2 that provides greater definition of the HTTP verbs in use with REST. However I see many articles swinging back and forth over it's utility. So, should I use WADL to allow external code generators to quickly build a client for my web application or is there a better standard that is expected?


How to refactor a myriad of similar classes

I'm faced with similar classes A1, A2, ..., A100. Believe it or not but yeah, there are roughly hundred classes that almost look the same. None of these classes are unit tested (of course ;-) ). Each of theses classes is about 50 lines of code which is not too much by itself. Still this is way too much duplicated code. I consider the following options:   1. Writing tests for A1, ..., A100. Then refactor by creating an abstract base class AA.   _Pro_ : I'm (near to totally) safe by the tests that nothing goes wrong.   _Con_ : Much effort. Duplication of test code.   2. Writing tests for A1, A2. Abstracting the duplicated test code and using the abstraction to create the rest of the tests. Then create AA as in 1.   _Pro_ : Less effort than in 1 but maintaining a similar degree of safety.   _Con_ : I find generalized test code weird; it often seems ... incoherent (is this the right word?). Normally I prefer specialized test code for specialized classes. But that requires a good design which is my goal of this whole refactoring.   3. Writing AA first, testing it with mock classes. Then inheriting A1, ..., A100 successively.   _Pro_ : Fastest way to eliminate duplicates.   _Con_ : Most Ax classes look very much the same. But if not, there is the danger of changing the code by inheriting from AA.   4. Other options ... At first I went for 3. because the Ax classes are really very similar to each other. But now I'm a bit unsure if this is the _right_ way (from a unit testing enthusiast's perspective).


Parsing a website's source

I want to create an application and maybe upload it to the play store but I am not sure if that what my app does is legal or not. I am downloading a page's source from a website to get some information I need. For example if I download a page about the song "Ramble On" by Led Zeppelin and parse this page source to get the song's name, maybe a link to an image and the lyrics. Would that be illegal or can I display these information to my users without getting any problem? Also the website says it's an "open 'wiki-style' [...].It's completely user built by people like you and used every day by fans and developers alike."


Amount of man hours to write a social network

I have big dreams of writing the next Facebook (unrealistic I know) and I'm in the planning stages as we speak and I'm umming and ahing about using a php framework for this and how many development hours it would actually save me. If any? Also is it unrealistic for one person to hand code an entire social network solo? Whats the largest application anyone has written on their own? I should also point out that I have a day job, so late nights and evenings it is. And pregnant partners to deal with :)


C++ XML Parsing: Suggestions on Approach for Parsing and Storing data

I am looking into developing a C++ application to parse xml (using the rapidxml framework), and I would like some advice on how to approach this. The file I want to parse is a XML game file that defines a set of addons for a starship ('outfits'), which have several attributes in common (like name and cost), but also fall into various categories. For example: Fixed weapons: range, rate of fire Turret weapons, range, rate of fire, turret slew speed Afterburners: acceleration modifier, fuel burn speed etc etc etc There are at least 5 classifications of outfits (and say 3 or 4 outfits that fall into each category), and some, like the weapons, have a few attributes in common with each other, but not with other categories like afterburners. I want to write parsing code to handle each type of object and store its data in objects. I also want to minimize how much code I have to retype (i.e. make use of good OOP style so I can add new categories or tweak existing ones in the future). **What is the best way to approach this?** I have already started the program, but I would like to have some input on the best approach. Since this is a really broad question, I will give you some of my thoughts/specific questions so you can see what I am looking for:   * Should I have a basic class called 'outfit' and use inheritance to customize the parsing for each specific category (i.e. 'fixed-weapons')? Should I have multiple levels of inheritance for similar categories (i.e. 'weapons'). How can I minimize code retyping so I only have to write the specific routines for each category?   * Where should I handle the errors: in 'outfit', or in the derived classes? How much error handling do I need?   * How can I easily access these objects later? Should I make a list-object with a vector containing each object? How can I access each object by name? Any input is appreciated; you don't have to give a complete and comprehensive rundown on how to do this (though that would be nice :P).


Which one subsumes the other: class-based object-orientation or prototypal inheritance?

In this talk: http://www.youtube.com/watch?v=hQVTIJBZook, Douglas Crockford claims that class-based object-orientation can be represented in terms of prototypal inheritance. The construction he gives is something like:               var theObject = function() {       var private1 = ...;       var private2 = ...;       ...       return {         public1: ...,         public2: ...,         ...       };     };      He also claims that the converse is not true: prototypal inheritance cannot be in general encoded using class-based constructs only. I have been thinking about it for a while, and it seems to me that both claims are wrong.   1. The supposed "encoding" of class-based object-orientation is wrong from an operational semantics point of view. In a typical class-based object-oriented language, member variables and functions are _known_ to exist, so they can be directly used. The prototypal "encoding" relies on testing _at runtime_ whether a member is present in an object/hashtable. Ergo, the semantics are different.   2. Prototypal inheritance actually _can_ be encoded in a class-based object-oriented language. I will use C++ as an example, but any other class-based object-oriented language could be used.               struct prototypal     {       std::shared_ptr<prototypal> base;       std::unordered_map<std::string, boost::any> members;            boost::any & operator [] (const std::string & key)       {         auto it = members.find (key);         if (it == members.end ())         {           if (base)             return (*base) [key];           else             throw std::logic_error { "Member not found." };         }         else           return *it;       }     };      Is my analysis wrong? Am I missing something?


git/svn Hooks for PHP/Zend Projects

just because i think we are not using the full potential of all possibilites here yet: What Pre/Post Commit Hooks (i.e. PHPUnit, PHPDoc) do you people use on your Team Git/SVN Servers? By now we do use a minification script (sadly only removes unneccessary space and comments and merges files), PHPDoc, PHPUnit and that's it already. Any good ideas that might be usefull as well?


Orthogonality of unit tests vs. concision of unit tests

I'm writing unit tests for a steering system for a video game. The system has several behaviours (avoid this area because of reason A, avoid this area because of reason B, each adding a bit of context to a map of the region. A separate function then parses the map and produces a desired movement. I'm having trouble deciding how to write the unit tests for the behaviours. As TDD suggests, I'm interested only in how the behaviours affect the desired movement. For instance, avoid-because-of-reason-A should result in a movement away from the suggest bad position. I don't care actually how or why the behaviour adds context to the map, only that the desired movement is away from the position. So my tests for each behaviour set up the behaviour, make it write to the map, then executes the map-parsing function to work out the desired movement. If that movement satisfies my specifications then I'm happy. However now my tests depend on both the behaviours working correctly, and the map parsing function working correctly. If the parsing function fails, then I would get hundreds of failed tests rather than a couple. Many test-writing guides suggest this is a bad idea. However if I test directly against the output of the behaviours by mocking out the map, then surely I'm coupling too tightly to the implementation? If I can get the same desired movement from the map by using a slightly different behaviour, then the tests should still pass. So now I'm suffering cognitive dissonance. What's the best way to structure these tests?


Storing graphs with json and db

I have a Rails 4 app having to do with graphs. These graphs need to be stored and I'm not sure of the best way to do it. Firstly, the app has a SQLite db in development and PostgreSQL in production. I would love to have graphs in JSON, but that can be achieved in several ways. Also, these graphs are going to be manipulated using some interface. I was thinking a graphical solution and a raw one in JSON. I have some alternatives to implementation:   1. Store the graph JSON files directly in the db. (how?)   2. Store the graphs in db with tables (graph, edges, vertex) (probably not...)   3. Store the graphs in db with tables and build a parser to manipulate the in JSON format. What is your recommendations?


How can I learn how to use Smarty effectively?

I have some experience in PHP4, but after learning the object-oriented parts of PHP, I'm having difficulty understanding how to use the Smarty template engine. The official documentation appears to require a level of knowledge I don't have yet so it doesn't seem like a good place to start. What do I need to know to jump into Smarty template development? Or if Smarty isn't the standard PHP template system anymore, how should I go about templating?


What features did c get from c++?

What features were added to C that were originally in C++?   When where they added and for what reason(what where the pro/con arguments)?   How do they differ in C as compared to C++?   Did the features originate in C++ or in another language? Examples (feel free to expand on): const, Function prototypes, implicit exit(0);


How to be Agile when new work keeps affecting completed work?

The project I'm working on is to re-skin an existing website. The functionality will stay the same, it's just the styles that are changing. In other words, I'm not modifying the HTML, only the CSS files. The site is pretty complex, with dozens of pages. Logged-in users can have a number of different roles, and depending on their role, the content of the page and what pages they are allowed to see varies. We're using Git and Github. I'm trying to write CSS that works as components, so when the same form elements, headings, etc. appear on multiple pages, they are consistent. Most of time this is working well. Sadly, the format and class names in the HTML are at times messy and unpredictable. When I fix something on one page it can break another. The job is also harder as no one knows exactly all the variations that are possible due to user roles; as such I'm continuously finding new variations as I go along. I'm making headway by putting a lot of comments in my CSS. If I need to remove a CSS rule, I'll comment it out so that I can still see it with Chrome dev tools, and I'll put a comment in the CSS saying why I removed it and for what page this was done. This means that if on another page I'm about to add a rule to fix a different problem, there is a better chance that I'll see how it'll break the first page. This allows me to either find a different solution that will work for both pages, or I can make the override page specific. This has been working quite well for me. If I had free reign and the only goal was to finish the project by the deadline, then this method would be fine. However, my manager is trying to mitigate risk by breaking the work into areas to be completed per sprint. This is counter to how I have been approaching things as something like my typography styles will affect all other pages on the site. The other issue is that the different stakeholders want to sign off on each section as I go along. The problem is, once I've finished a section it may change if I change CSS that affects it along with the new section I'm working on. I've asked that the stakeholders have a quick unofficial sign off in stages (e.g. per sprint), and have the final official sign off at the end of the project, but this is being met with resistance. I understand why it would be higher risk to do this, but the only way to guarantee that a signed off section will not change is to make ALL future changes page specific. In addition to this I'm being told that all work that I push to the Git repo should be ready to go live, and as such should not contain any code comments. This is risky for me as I won't know until I've finished the site if I will ever benefit from these comments or not. Has anyone else been in a similar situation and managed to find a compromise that worked for my development approach and also the desires of management and stakeholders to have a more Agile approach? A more Agile workflow works great when you can break the work into components and know that once something is done it won't be affected by future work. However the nature of this project makes this hard to achieve.


How well should a fresh graduate know a language?

I am CS student and have just few months before I graduate. I can write programs, but use pretty many manuals in the process. It's almost 50% writing/50% reading (maybe even more reading). What I want to ask is how much do you need to know a language (technology, method etc.) to say in you CV, that you know it? Thanks in advance. P.S. I feel uneasy to learn just one technology to perfection, because it's limiting my further possibilities.


How are comments expressed in programming language grammars?

I'm learning how to build parsers using grammars, but I got stuck trying to express comments, because they can appear almost anywhere. This indicates that comments can be stripped from the token stream before parsing takes place. Is that the standard practice, or are comments ever/often specified in grammars?


Testing To Prevent Cascading Bugs

Yesterday, Twitter was hit with a "Cascading Bug" as described in this blog post: > A “cascading bug” is a bug with an effect that isn’t confined to a > particular software element, but rather its effect “cascades” into other > elements as well. I've seen this kind of bug, on a smaller scale of course, on some projects I've worked on. They can be difficult to identify in dev/test environments, even within a test driven development environment. My questions are... What are some strategies you use, beyond the basic TDD and standard regression testing, to identify and prevent the potential trouble points that might only occur in the production environment? Does the presence of such problems indicate a breakdown in the software development process or simply a by-product of complex software systems?


SSIS: How long does it usually take to bring a new hire up to speed?

I’m a self-taught SQL developer that has worked for small to mid-sized companies. Most of my experience has been writing SQL statements for reporting, data scrubs, and never in a formalized IT department. For my last job I planned and executed a full migration and wrote all of the new business processes and trained end-users. For the most part I’m used to being the expert when it comes to developing database solutions, but this is only because no one in the room ever knew anything about databases. Now I’m working with a team of developers as an SSIS interface developer. For the most part it’s not rocket science but I’m finding it hard to get up to speed. There is a lot going on in the database and the packages are we’re developing are pretty complicated. I have spent much of my first month studying the system rather than coding. Is this normal? If so how long will it be before I’m being productive and contributing in a meaningful way. I’m used to hitting the ground running and being able to contribute from the get-go. How long does it usually take to bring a new hire up to speed?


Combining Code Review with Trust Metrics

I don't get the chance to partake of it at work. But I love the idea of **code review**. Especially of online open source code review like Gerrit Code Review. I love what **Trust Metrics** have done for forums and collective intelligences sites on the internet like stackexchange, reddit, and wikipedia. Would it be possible to combine the two and come up with an open source project management system. Something that ends up being mostly community driven. Perhaps a kind of wikipedia of code for a project. Where submitters become popular/trusted by having lots of patches reviewed favoriably by others, and accepted into the trunk. And popular/trusted submitters get their patchs accepted faster/easier. I'm looking for some opinions on the idea, or perhaps pointers to where its been done before, if thats the case. This might leave the lead maintiner little more to do than:   * wrangle the direction of the project by fast-tracking or vetoing specific patches.    * settling disputes when the CI tests break, or fixing it himself.  Is design by community worse than design by committee?


Algorithm for Learning development

This is a fairly general question. I know a bit of Perl and Python and I am looking to learn programming in more depth so that once I get the hang of it I can start developing applications and then websites. I would like to know of an algorithm (sequence of steps :)) that could describe my approach towards learning programming in general. I have posted small questions on Perl/Python and I have recieved great help from everyone. Note:- I am not in a hurry to learn. I know it takes time and that's fine. Please give any suggestions you think are valid. Also, please don't push me to learn Lisp, Haskell etc - I am a beginner.


function level error reporting: to combine/bundle errors or not?

What is in your opinion the best way to handle (at runtime) the situation when a **more than one** input parameter to a function is incorrect. I can see two ways. First one - a simply return an first error (by raising the exception or via some other way supported by a programming language) telling that the first of incorrect parameters is wrong. Alternatively, the function can check all the parameters, combine all the error messages into one and return it as a one. Or there might be some other approach. What would be your preference and why? Thank you.


Quicksort and middle pivot

I am having a head ache understanding quicksort with middle pivot. I found lot of explanations about using left most or right most, but not many about a middle one. Can I safely assume these?:   1. If left and right pointers meet at the same position, means that the element at that position is at its final sorted position, so I can split the list in two without including that element (list1 length + list2 length = list length -1).   2. If left and right cross each other ( so left > right), means that no element is at its final sorted position yet, so I must split the list in two using left and right as boundaries ( list1 length + list2 length = list length). Is this right? Thanks. **Update** : The reason why I want to use a middle pivot, is to implement the "median algorithm" that increases QS speed. In this techique, the pivot is selected by approximating the list middle value: http://www.brpreiss.com/books/opus4/html/page500.html


Boolean Method Naming Affirmative vs Negative

Should boolean methods always take the affirmative form, even when they will only ever be used in the negative form? Say I wanted to check whether an entity exists before creating one, my argument is that the first form below is better than the second form, whether or not the method is ever used in the affirmative form. In summary, I find `if(!affirmative)` easier to read than `if(negative)`. I have a colleague who disagrees, thoughts? **First Form:**               int entity_id = 42;     if(!entity_exists(entity_id)) create_entity(entity_id);      **Second Form:**               int entity_id = 42;     if(entity_not_exist(entity_id)) create_entity(entity_id);


Will Design Patterns Help me in this case?

recently I have been given a task of finding the combinations of the given word. For example, say The given word is **like** then possible answers are liek,lkie and so on. This has to be implemented in any language, doesn't matter, but the rule is we don't use the built-functions/API to find the combinations. And I guess we know design patterns are for solving any problem with a given solution. For example, Information Expert is a Design Pattern. Now my question is whether there is any design pattern for finding combinations? Or for these kind of things Design patterns wont suit and say i have to learn a good algorithm for finding the solution. Then what's the difference between Algorithm and Patterns, both try to solve the problem in a good efficient way, right? I don't know wthether my view is correct or not, please correct if I am wrong!


Can I use Dependency Injection without breaking Encapsulation?

Here is my Solution and projects:   * BookStore _(solution)_     * BookStore.Coupler _(project)_       * Bootstrapper.cs     * BookStore.Domain _(project)_       * CreateBookCommandValidator.cs       * CompositeValidator.cs       * IValidate.cs       * IValidator.cs       * ICommandHandler.cs     * BookStore.Infrastructure _(project)_       * CreateBookCommandHandler.cs       * ValidationCommandHandlerDecorator.cs     * BookStore.Web _(project)_       * Global.asax     * BookStore.BatchProcesses _(project)_       * Program.cs **Bootstrapper.cs** :               public static class Bootstrapper.cs      {         // I'm using SimpleInjector as my DI Container         public static void Initialize(Container container)          {             container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), typeof(CreateBookCommandHandler).Assembly);             container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>));             container.RegisterManyForOpenGeneric(typeof(IValidate<>),                 AccessibilityOption.PublicTypesOnly,                 (serviceType, implTypes) => container.RegisterAll(serviceType, implTypes),                 typeof(IValidate<>).Assembly);             container.RegisterSingleOpenGeneric(typeof(IValidator<>), typeof(CompositeValidator<>));         }     }      **CreateBookCommandValidator.cs**               public class CreateBookCommandValidator : IValidate<CreateBookCommand>     {         public IEnumerable<IValidationResult> Validate(CreateBookCommand book)         {             if (book.Author == "Evan")             {                 yield return new ValidationResult<CreateBookCommand>("Evan cannot be the Author!", p => p.Author);             }             if (book.Price < 0)             {                 yield return new ValidationResult<CreateBookCommand>("The price can not be less than zero", p => p.Price);             }         }     }      **CompositeValidator.cs**               public class CompositeValidator<T> : IValidator<T>     {         private readonly IEnumerable<IValidate<T>> validators;              public CompositeValidator(IEnumerable<IValidate<T>> validators)         {             this.validators = validators;         }              public IEnumerable<IValidationResult> Validate(T instance)         {             var allResults = new List<IValidationResult>();                  foreach (var validator in this.validators)             {                 var results = validator.Validate(instance);                 allResults.AddRange(results);             }             return allResults;         }     }      **IValidate.cs**               public interface IValidate<T>     {         IEnumerable<IValidationResult> Validate(T instance);     }      **IValidator.cs**               public interface IValidator<T>     {         IEnumerable<IValidationResult> Validate(T instance);     }      **ICommandHandler.cs**               public interface ICommandHandler<TCommand>     {         void Handle(TCommand command);     }      **CreateBookCommandHandler.cs**               public class CreateBookCommandHandler : ICommandHandler<CreateBookCommand>     {         private readonly IBookStore _bookStore;              public CreateBookCommandHandler(IBookStore bookStore)         {             _bookStore = bookStore;         }              public void Handle(CreateBookCommand command)         {             var book = new Book { Author = command.Author, Name = command.Name, Price = command.Price };             _bookStore.SaveBook(book);         }     }      **ValidationCommandHandlerDecorator.cs**               public class ValidationCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>     {         private readonly ICommandHandler<TCommand> decorated;         private readonly IValidator<TCommand> validator;              public ValidationCommandHandlerDecorator(ICommandHandler<TCommand> decorated, IValidator<TCommand> validator)         {             this.decorated = decorated;             this.validator = validator;         }              public void Handle(TCommand command)         {             var results = validator.Validate(command);                  if (!results.IsValid())             {                 throw new ValidationException(results);             }                  decorated.Handle(command);         }     }      **Global.asax**               // inside App_Start()     var container = new Container();     Bootstrapper.Initialize(container);     // more MVC specific bootstrapping to the container. Like wiring up controllers, filters, etc..      **Program.cs**               // Pretty much the same as the Global.asax      Sorry for the long setup to the problem, I have no better way of explaining this other than detailing my actual problem. I don't want to make my CreateBookCommandValidator `public`. I would rather it be `internal` but if I make it `internal` then I will not be able to register it with my DI Container. The reason I would like it to be internal is because the only project that should have notion of my IValidate<> implementations are in the BookStore.Domain project. Any other project just needs to consume IValidator<> and the CompositeValidator should be resolved which will fulfill all validations. How can I use Dependency Injection without breaking encapsulation? Or am I going about this all wrong?


Combination of asp.net server side + html/js/jQuery client side

While working with asp.net, I came to an approach that uses asp.net services for the data/business logic layer and html/javascript/jquery for the UI layer, because I could not reach the needed level of customization of the user interface with asp.net web controls. While I've seen plenty of books describing usage of asp.net web controls and their integration with asp.net server side technology, and of html/js/jQuery client side web development without connection to any server side technology, I haven't seen any book dealing with combination of asp.net server side + html/js/jQuery client side. My question is, is this approach acceptable, or have I overlooked some widespread technology which is better suited to accomplishing such tasks? My constraint is that it has to be based on asp.net/mvc server side technology, because my management urges that.


Should I get a Math bachelors and then go into Computer Science?

This is my first question. I love Mathematics; I love the logic and the problem solving. At the same time, I enjoy Computer Science and hope to go into Artificial Intelligence research after I get my Bachelors degree, i.e pursue a PhD in Computer Science. Are there any advantages of having a firm grasp of Mathematics to studying Computer Science? Also, would I be at a disadvantage in getting a Bachelors in Mathematics instead of Computer Science when applying for graduate school to study Computer Science, particularly at institutions with high quality research infrastructure, like MIT and Stanford? Also, in reference to the first question, could you please tell me the advantages of a solid grasp of Mathematics, if there are any? Thank you.


Where does the term "Red/Black Tree" come from?

A Red/Black Tree is one way to implement a balanced binary search tree. The principles behind how it works make sense to me, but the chosen colors don't. Why red and black, as opposed to any other pair of colors or of attributes in general? When I hear "red and black," the first things that come to mind are checkerboards and Les Misérables, neither of which seems particularly applicable in this context.


Why are there so many numeric types (bit, int, float, double, long)?

I've learned PHP, Java, and C. Now I'm curious as to why there are so many types of numerical data types like bit, int, float, double, and long. Why not make only one type for numericals? Is there any benefit to this? Maybe if we use integers to hold such small numbers we can save memory?


Strange software development terminology

I have been working in a professional software development environment for a short while now. Over this short period of time I have heard some terminology I never knew existed. For example, in a status call a few weeks ago one of our developers said that he had been "hand-jobbing" things left and right. A few days ago, I heard a new one again, where someone in our company wants to "dog-food" some product of ours. So what is a "strange" term with respective definition, or list of terms that you know, that can improve on a new developer's professional vocabulary to improve on their communication and understanding of processes in the workplace? My list is as follows and I will add more as I come across them!   * Hand-jobbing: When a programmer resorts to some primitive or less-than-best-practice method of getting the job done, for the sake of getting something working, usually temporarily.   * Dog-fooding: When a company uses a product for internal use that they have or are currently selling to their customers, usually to save time and money, but also to show confidence in their own products. Also as a side note, I guess they don't have to really be TRUE software terminology as I've never heard anyone ever "hand-job" something as much as he did. However it should be something you have heard used in a professional environment that you would like to share.


Is perfectionism a newbie's friend or enemy?

> **Possible Duplicate:**   >  Where do you draw the line for your perfectionism? I see that the development community is very focused on doing things the right way and personally I would like to do the same too, however, is it a good or bad idea for a newbie to focus on design principles, design patterns, and commenting code when getting started, or is it better to let creativity run wild and potentially write sloppy code. Where should a newbie draw the line?


Are there standard guidelines for auditing software for possible buyout?

We are in the process of auditing a company with a view to buying them out. One of the key parts of this decision is the software they've developed over a long period of time. We always have the option of building our own, but we are all aware that it could take us longer to get operational if we build from scratch. My question is rather specific: I come from a development / PM background, and have been asked to do a full audit of this company's software, which is a web application. We want to know as much as possible about it before we make the decision of whether to buy them out, and after a basic demo, their system seems to do what we want, but we know that we'll need to modify it to a certain extent. I am looking for a template or framework to work through in order to produce my final report. Its been really tough finding anything through Google; most of what I've found is just basic checklists at best. I would need a template or framework that deals with infrastructure, design, architecture, hosting, etc. Has anyone had experience with this? I would be very grateful if someone is willing to share their template/framework with me.


How to help junior programmers whose first language isn't English?

I've just changed jobs and am now working with a junior programmer whose first language is Cantonese. They have a computer science degree but are working in their first programming role after many years outside the computer industry. They have been working for the past two years in almost total isolation and have developed a lot of bad habits. A fellow contract programmer also speaks Cantonese, but his spoken English is quite poor, is also frustrated by the juniors approach to programming and are unsure what to do. Despite working on projects together in Cantonese the projects over run as the lack of an agreed/reviewed design means they have a merry-go-round of updates until a solution is reached. Despite gentle verbal encouragement to do so both still struggle to create even the most basic design documents, enter proper check-in comments (i.e. not just 'bug-fix','updates' etc) and contribute at all to the project wikis. At present the junior programmer doesn't read blogs, books or technical resources. When I ask how they become a better programmer they say they just think more about their own code. They are highly prone to reinventing the wheel with what I can only generously say are uniquely imaginative solutions to well solved problems. I have tried to explain the KISS principle and SRP to them but I'm not convinced they understand the benefit. I'm sure I can't have explained it very well to be honest. Since I'm not sure if English comprehension is a problem then that is a problem in itself. Can you recommend ways I can help them when;   * I can't speak any Cantonese and don't see learning any being effective in a realistic time frame   * Sending links to resources like thedailywtf.com appears to go over their heads   * The programming books we've bought remain unread I've found the following SO questions which might be useful to them but point two above applies;   * Programming information in your mother tongue   * Does “English” hinder you to enhance your programming skills? Are there some programming exercises we could work through together? What tips are there to get some basic documentation created? Are there any Cantonese resources I could point them to? I appreciate how much easier it is when English is your native language. I genuinely want to help them as much as possible and not judge what could otherwise be perceived as an unwillingness to improve as a programmer.


If I hire you for "a day", how many hours are expected?

I've seen a lot of advice for freelance programmers which advocates quoting your rates in periods of a minimum of one day. That means that when someone asks your rate, you would say "$500 per day" rather than giving the equivalent hourly rate. If I agree to do 10 days of programming work for a client at a particular daily rate, how many hours are expected of me per day? What happens if I do 6 hours of actual programming on Monday and then do 8 on Tuesday.. is that two "days" or "1.75 eight hour days" or what? What's the standard?


What does "deploy to a physical machine" mean

I was asked whether I've ever "deployed to a physical machine" and I'm seeing this terminology when googling, but not getting a definition. What does it mean? What other way could someone deploy an application if not to a physical machine?


How can I apply Readme Driven Development to an ongoing project?

I'm assigned to a project where the goal is to update an existing software. This software was developed in a totally _ad hoc_ manner, which means that any documentation generated is outdated, confused and just plain useless. I do not want to retroactivelly produce all the missing artifacts, since this would just be a waste of time. The code base is ugly, and really need some serious refactoring, but this is another story. What I want is to apply Readme Driven Development to guide this project. So, basically, I want to write a Readme, which will document every change meaningful at the user level. The problem is, I have no idea about how to structure this document. For me, it's pretty clear that it should have a different layout than the traditional Readme. I really want to document changes, and not the current state of affairs. Any ideas?


Which patterns/architecture to apply for "Import Data, Process Data, Export Result"

I was wondering which architecture/patterns to choose for the following problem divided into three steps:   1. Import TestScript Description from File (e.g. .xls, .txt)   2. Process Described TestScript   3. Export Description with processed Results as .xml Here is what I got so far:   * Importer that reads in xls and creates a hierarchical object structure   * Parser that creates an Abstract Syntax Tree (If,then,else,end,command) from the object structure   * A Processor (VisitorPattern) of the AST. This Processor instantiates the command implementation, executes the command, collects the results and controls the flow (if, then, else) Currently the imported object structure already contains a field for the result and can just be serialized out as xml. But in my opinion it's not very elegant having a result field in the input objects. The main reason I don't like it is that I can not reuse the imported object structure in order to process it multiple times. I would like to divide the whole component also into three parts:   1. Import, which creates an hierarchical object structure that describes the TestScript (containing a fileparser and a preprocessor)   2. Process, which creates an AST and processes it   3. Export, which takes the results and the descriptions and writes it out Here a few other conditions:   * Not every AST Node represents an object in the object structure (description)   * But each result object is connected to an description object   * Description and Results are hierarchical


Why are most GNU's software written in C

I am a Java developer, and I rarely write GUI program in C. However, I noticed that many GNU's projects, such as PSPP, R, Dia, etc., are written in C, instead of Java or C++. I personally don't mind this, but I am really curious why GNU favors C so much. My understanding is that C is the one that supports the least in object- oriented programming, and today's CS education really emphasizes OOP, as OOP really makes codes more reusable. In this case, why would so many developers choose to develop in C instead of C++ or Java. Does anyone know why GNU's software are so exclusively written in C? Do you think or GNU's software should be written in C++ or Java so that the source code could be more useful to people? Why or why not?