Aggregate Root and Lots of Data Efficiency

It's more of a scenario, but it isn't far fetched at all. Let's say I have an Aggregate Root (AR) Warehouse which it's used to manage product stock. The Product itself is an AR in a different bounded context (BC) but in this BC is represented only by an id. In the Warehouse I can add a new product (must be unique), Ican remove it and i can update stock. Of course, I can communicate the stock for a product and maybe even keep the in/out flow for a product. THe problem is you can easily reach hundreds or thousands of products. So, for any wareohuse action you'll have to load everything even if that action won't use all that info. It's highly inefficient. A solution I could think of is to pretty much 'break' the warehouse AR in specialiazed objects for different actions. But this means we no longer have an AR and we're back to a CRUD like solution. Even more so, the AR was split not becasue the Domain need it, but because the technical details need it. It looks like you can do DDD until a certain point, after that you go CRUD or buy a MUCH BIGGER and expensive server. What do you think? Can we have both DDD and efficiency when lots of data is involved?


Avoid GPL violation by moving library out of process

Assume there is a library that is licensed under GPL. I want to use it is closed source project. I do following:   1. Create small wrapper application around that GPL library that listens to socket, parse messages and call GPL library. Then returns results back.   2. Release it's sources (to comply with GPL)   3. Create client for this wrapper in my main application and don't release sources. I know that this adds huge overhead compared to static/dynamic linking, but I am interested in theoretical way.


Rails engine testing - use dummy app or real parent app?

I'm using Rails engines to break up a big app into smaller pieces. The parent app mostly handles users and authentication. In one of my engine tests I want to log in a user before each test. How should I access this user log in functionality, which exists in the parent app, from the engine? It seems there are two options: 1) Build user authentication into the dummy app. When you run `rails plugin new app_name --mountable` a "dummy app" - just a plain Rails app - is created in your test folder. During tests the engine is mounted on to this dummy app. For feature (integration, acceptance, what-have-you) tests, I thought it would be good to use real objects whenever possible. So I was planning on using a factory to create a real user and then log in that user. To do this with the dummy app, I would need to build that user functionality in. This seems like a pain because if the real parent app changes, I need to change this dummy app as well. 2) Put all my tests in the parent app. This will work fine, I think, but it seems fishy. I feel like I should put my engine tests in the engine.


Recommended Reading for Polishing JavaScript coding style?

I've been coding in JavaScript for a while now and am fairly familiar with some of the more advanced coding features of the language (closures, self- executing functions, etc). So my question is, what advanced books/blogs/or anything else would be recommended to help tighten up my coding style? For example, recently I was coding something similar to:               var x = ['a', 'b', 'c'];     var exists = false;     for(var i = 0; i < x.length; i++){         exists = x[i] === 'b' ? true : exists;     }      But found that the following condensed code would work better:               var y = {'a':'', 'b':'', 'c':''};     var exists = 'b' in y;      Both store the same value in 'exists', but the second is less common, but much cleaner. Any suggestions for where I should go to learn more tricks like this? Edit: I recently found this blog with a lot of good detail on the intricacies of JavaScript: http://javascriptweblog.wordpress.com/


Do you own your tools?

A colleague of mine wrote a post a while ago asking Do you own your tools. It raises an important question. Do you? I answered way down in the comments. As an independent, I do own my tools. Even when I wasn't independent, I had my own (fully licensed) tools that I used for personal development. I don't think buying your own tools are something to puff your chest up about (just because you can buy a $100 pair of basketball sneakers they won't make you as good as Michael Jordan), but it IS an investment in yourself that shouldn't be taken lightly. What do you think good people?


Why hill climbing is called anytime algorithm?

From wikipedia, Anytime algorithm > In computer science an anytime algorithm is an algorithm that can return a > valid solution to a problem even if it's interrupted at any time before it > ends. **The algorithm is expected to find better and better solutions the > more time it keeps running.** Hill climbing > Hill climbing can often produce a better result than other algorithms when > the amount of time available to perform a search is limited, such as with > real-time systems. It is an **anytime algorithm** : it can return a valid > solution even if it's interrupted at any time before it ends. Hill climbing algorithm can stuck into local optima or ridge, after that even if it runs infinite time, the result won't be any better. Then, why hill climbing is called anytime algorithm?


PHP rand function (or not so rand)

I was testing PHP rand function to write on a image. Of course the output shows that it's not so random. The code I used:               <?php      header('Content-Type: image/png');     $lenght = 512;     $im = imagecreatetruecolor($lenght, $lenght);     $blue = imagecolorallocate($im, 0, 255, 255);     for ($y = 0; $y < $lenght; $y++) {         for ($x = 0; $x < $lenght; $x++) {             if (rand(0,1) == 0) {                 imagesetpixel($im, $x, $y, $blue);             }         }     }            imagepng($im);     imagedestroy($im);     ?>      My question is, if I use image width/lenght (variable $lenght in this example) number like 512, 256 or 1024, it is very clear that it's not so random. When I change the variable to 513 for an example, it is so much harder for human eye to detect it. Why is that? What is so special about these numbers? 512: ![512 pixels](http://i.stack.imgur.com/T0qjD.png) 513: ![513 pixels](http://i.stack.imgur.com/vDzXS.png) **Edit: I'm running xampp on Windows to test it.**


How to store a list of Objects that might change in future?

I have set of Objects of the same class which have different values of their attributes. and I need to find the best match from a function under given scenarios out of these objects. In future these objects might increase as well. Quite similar to the way we have Color class in awt. we have some static color objects in the class with diff rgb values. But in my case say, I need to chose the suitable color out of these static ones based on certain criteria. So should I keep them in an arrayList or enum or keep them as static vars as in case of Colors. because I will need to parse through all of them and decide upon the best match. so I need them in some sort of collection. But in future if I need to add another type I will have to modify the class and add another list.add(object) call for this one and then it will violate the open-close principle. How should I go about it ? **EDIT:** To be more precise I have a roughly 7-8 branches of restaurants which wont increase that much..may be by 3-4 in few years and I need a function that will return the nearest Restaurant satisfying few other criteria. and For that I need to parse through all of them to decide which one suits the customer the most.


How to use Open Source Licenses and what do you recommend to me

I have a code that I'd like to share, but I'd like to publish it using an open source license. But I don't know how you have to use that licenses. How do you have to activate an open source license? Just including the text of the license in all files? What else do I have to do? Do I need to buy some right? Include a readme.txt in all the directories? I mean, what do I have to do if I want my code is protected by the legal test of a license? The second question is what it is the better license for this conditions:   * I don't care what people do with my code, educational purposes, to make money, I don't mind whatever they want to do with it.   * But I want people don't delete my name from the code, and If they use my code force them to mention me. If they change my code and someone ask for those modifications, they give the code with the modifications.   * But I don't want to force people to publish the code of they applications, even if they are using my code. What is the best license to that purposes?


FOSS licensing decision: What to read? What factors to consider?

Which reasoning would you follow to choose one license over another? Which literature would you expect someone to read, if he wants to make a meaningful decision about licensing? I specifically don't go too much into detail about my current project, because I am looking to learn how to make this decision correctly without getting a degree in law first.


Questions about software licensing

I've been having a discussion about licensing and open source software. Basically - the other guy is saying that licensing is easy, if you're going to build a product you can use an (any) open source project and make money by selling that code. My issue is that say I create a website or app with a project that uses a GPL license the restrictions aren't so straight forward - correct me if i'm wrong on each of these scenarios: 1 - i create an iPhone app using GPL code and put that app into the appstore - the code must be freely available to people buying that app. 2 - i create a website that my client hosts - they must have access to the code. 3 - i create a website as SaaS that my client "leases" but does not own - though it is hosted on their infrastructure - they must have access to that code Am i right on each of those assumptions? Are there any other issues i should be aware of under any other licensing terms for other licenses?


How can I control Visual Studio's window creation behavior?

I have recently installed Visual Studio 2010. By default it has a nice layout, and when I open files, the tabbed windows for those files appear where I like them to appear: source code on the upper half of the screen, compiler output, test status, trace windows on the bottom half. But, after a period of using it, I fat finger something, and then the window positioning logic goes haywire. One of the tabs gets undocked, and then after I redock it, nothing else operates like it used to operate. So maddening! It opens source code on the bottom, it opens other windows in unpredictable places. I undock and redock the windows where I want them, and the next time I open them, they go to the wrong place again. WTF? Even the "start page" gets moved. This is what it looks like when I start up: ![enter image description here](http://i.stack.imgur.com/8sKDn.png) I know I can do the `devenv /resetsettings` thing to restore to the original, and I have done this (Several times), but really I would like to know:   1. How is this happening? What am I doing to cause this behavior? How can I avoid it?    2. Can I undo it - get it to behave sanely again - without stopping visual studio, and restarting with the /resetsettings switch? What are the magic mouse clicks to make it revert? I know it's challenging to describe UI gestures, but if you have hints, I'd love to hear them. Does anyone else have this problem?


Flowcharting and Method Calls

I am doing out some flow charts and am wondering if I am approaching this correctly. In essence, I have several method calls and I am flowcharting each separately. However, several of these methods make a method call for some info and then continue. See this example: ![enter image description here](http://i.stack.imgur.com/bmqBD.png) I have 3 other methods that also call GetQueue() and I am wondering if I am representing this correctly. The AddQueue() flow visually looks like it is broken. NOTE: Changes made in my flowchart: ![enter image description here](http://i.stack.imgur.com/pWa9Q.png)


How much programming should I know before looking for first job/internship in tech company?

Im in college and just started to learn programming. How much should I atleast know before I start to look for jobs/internship so that they wont laught me out of office. I just started to learn programming and CS and literally don't know anything about it before college.


The development team I'm in has been working on a VERY large project for months now and we recently started to implement a kanban board with agile practices into our process. We have seen MASSIVE improvement in our throughput! Its so exciting! But we have one struggle right now. We have a total ticket count for the project and our supervisor has given us incentive(candy and popcorn boxes) for when we get down to 100 and 50 tickets. It at first felt like a great idea but it feels like new tickets are created just as fast as we can resolve them, and its making the team feel worse about our progress. So heres my question: Should you reward based on overall project completeness or velocity? And if completeness how do you make that feel more reachable?


HTML + CSS or HTML5 + CSS3 or HTML5 + jQuery

I want to be a good UI Developer. I'm confused whether I should learn ( **I need some serious suggestions** ): 1) **HTML + CSS + JavaScript or HTML5 + CSS3 + JavaScript or HTML5 + CSS3 + jQuery** 2) Is it required to learn CSS first before learning CSS3 ??? 3) If the above technologies needs to be prioritize then what would be the order?


Randomly select from list with increased odds

I have a list of entities. Every entity contains a number that holds how many times the entity has been selected. I need to make a function that selects `n` (say 25%) of the entities, randomly. What I want to do is increase the odds for entities that have been selected the least times. Suppose after 5 runs the times the entities have been selected can be anywhere from 0 to 5. But I don't want to have such a spread. I want the times the entities are selected more or less to be equal. How can I write a function that increases the odds for entities that haven't been selected as often as others? One way I could think of is to make a list that has more occurrences of lesser selected entities, increasing the chance the randomizer selects that entity. Any hints, tips, ideas? **EDIT:** Wow. Closed as not being a real question and reopened again. For not being a real question it did get a lot of answers and comments. Thanks for that. I got exactly what i wanted from them. I got some nice ideas to work out and to test.


What's the best way to learn nature-inspired algorithms?

I completed the Machine Learning course (Stanford) and got very interested, also after some research, I decided that I'd like to learn nature-inspired algorithms. I've found some resources like:   * Clever Algorithms: Nature-Inspired Programming Recipes (Book)   * Wyss institute (Website)   * Programming Game AI by Example (Book) The first reference look good and complete with pseudocode (giving me the possibility to implement everything in Ruby, my prefered language), and also gives ruby implementations for every code. But it lacks of exercises to practice, which I think is a key feature. The second is something that inspired me a lot to start studying this area, but they don't have any course or material to study. The third one looks good too, but has only a little amount of exercises, and might be too focused (I do like games, but I also want to study everything else related to nature-inspired algorithms). Also it is focused on C++ (not that it is a hard language, but I don't like its limitation compared to ruby), and I'd prefere something in Ruby or pseudocode (although it is not my main priority). Does anyone know something that also have exercises to complement the theory? Is there anything better to learn, with a particular focus on exercises? (Maybe courses or video lectures).


Is it necessary to follow the standard , take the C standard for that matter?

May be this question is a duplicate and I am a dumb to ask it here, but I searched a bit and none of the titles suggested to answer my question exactly . There are some very experienced folks on SO who always talk about the C standard. People seem to not like non-portable solutions, even if they work for me. Ok, I understand that the standard needs to be followed , but doesn't it put shackles on programmer's creativity? What are the concrete benefits that come from following a standard? Especially since compilers may implement the standard slightly differently.


Tic tac toe class diagram

I'm in a software engineering class and I want to practice some skills on the most basic case possible : tic tac toe. I know this is overkill but I want to do it in "proper" OOP. I designed a class diagram for it but there is one point where I don't clearly see what would be the best design decision. ![enter image description here](http://i.stack.imgur.com/US5Er.jpg) ("Joueur" means "Player", "PlancheDeJeu" means "Game board") Given this diagram, according to the `Expert`, `Low coupling` and `Strong cohesion` design patterns (sorry if those are not the correct english terms, I am translating) the score should be kept by the user class (Joueur). However, since there is no direct relation between Joueur and Système I don't exactly know how the game could display the score in a clean way. In this diagram, Système would have to ask the PlancheDeJeu object about the score and it would itself have to get it from Joueur. This seems wrong. I am trying to think of how to design an intermediary object that would link Joueur and Système but I can't come up with a good idea. What would be the best way to go here ? Thanks !


Use case decomposition for class registration system

I am currently working on refactoring a summer camp registration system to include some new features and will also be using it as the basis for a new after-school class registration system. For this new version of the system, I want to start out by writing use case descriptions for the registration process (and ultimately I plan to document all the use cases). I understand that the purpose of a use case is to accomplish a user's goal, but I'm still not sure how the registration process should be divided into use cases. Here are the options I've been thinking about:   1. One big "Register Student(s) For Classes" use case   2. Divide it into separate use cases: "Enter Student Information", "Select Classes", "Pay for Registrations"   3. Have separate use cases but also have a "Register Student(s) For Classes" use case which "includes" the more granular use cases Another factor to consider is timing: parents may want to enter their students' basic information (name, age, etc.) prior to the time when registration begins, but of course some parents will complete the whole registration process in one sitting. Also, payment won't always immediately follow class selection; in some cases parents will be allowed to complete their payment later (within a 48 hour window). I read some articles about use cases on Alistair Cockburn's website but I'm still confused as to what the guidelines are for dividing up use cases in a case like this. My inclination is to go with option 3 since the system will have a wizard interface that could potentially guide the user through the registration from start to end, accomplishing the "user goal" of registering his/her student(s) for classes, but the "included" use cases could also be initiated on their own. I was also wondering if I should have a separate "Modify Class Selections" use case for the case when the parent logs back into the system later and changes class selections on behalf of the student, or whether that should just be an alternative scenario of the "Select Classes" use case. What would you recommend, and why? What guidelines should be used in general when analyzing use case boundaries, beyond the idea of a "user goal"? * * * **Update:** I found this quote from the first chapter of Alistair Cockburn's book to be helpful: > Depending on the level of view needed at the time, the writer will choose to > describe a multi-sitting or **summary** goal, a single-sitting or **user > goal** , or a part of a user goal, or **subfunction**. Communicating which > of these is being described is so important that my students have come up > with two different gradients to describe them: by height relative to sea > level (above sea level, at sea level, underwater), and by color (white, > blue, indigo). It seems to me that "Register Student(s)" is a summary level goal, since it could potentially take multiple sittings to complete. The line is blurred in this case, but I think this idea of a summary use case suggests that my approach #3 above is a reasonable one.


I'm writing a small program that I want to be able to link with other programs. I also intend to run it from a command line interface, and maybe later with a GUI interface. How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library? Distribute it as a library and   * Dynamically link for GUI and command line interfaces   * Statically link for a stand alone binary


Refactoring Tomcat webapp deployments

**Background** We have several webapps running on Tomcat 7.0.x (on Linux). For historical reasons, we have populated the "Common" lib (i.e. $CATALINA_HOME/lib) with many application jars. These jars include Spring, Jackson, and our own persistence-layer jars. As we deploy new persistence-layer jars, we are embroiled in a classpath hell: some jars are OK in ~/webapps/foo/WEB-INF/lib, but some must be excluded and placed in Common. Recent adventures show that some may have to be in _both places_. Our local (Windows) build is similarly messy: we have one folder filled with jars. We build with Eclipse (not Gradle, Ant, etc) and do not have an explicit list of jars used by the web applications. The Linux build does use Ant, but semi-selectively globs jars into the WAR files. **Question** I would like to white-board a strategy on how to extricate ourselves from this predicament. One approach is listed below, but I would appreciate any refinements, or alternative approaches. The goal is to correct the deploy process, not the local build. **Strategy** On local machine, use Gradle to compile each web application:   * add compile-time dependencies until compilation is OK   * locate Gradle's local cache (or observe output) to find transitive run-time dependencies   * add all jars to ~/WEB-INF/lib for the web app, with explicit references in the formal Ant build   * deploy into a fresh, pristine Tomcat install   * observe startup logs for any "ClassNotFound" exceptions, both for 3rd-party libraries and our application libraries   * add these libraries to the formal Ant build   * perform regression QA tests on application and monitor for "ClassNotFound"


LuaJit FFI and hiding C implementation details

I would like to extend an application using LuaJit FFI. Having seen http://luajit.org/ext_ffi_tutorial.html this is surprisingly easy when comparing this to the Lua C API. So far so good. However I do not plainly want to wrap C functions but provide a higher level API to users writing scripts for the application. Especially I do not want users to be able to access "primitives", i.e. the `ffi.*` namespace. Is this possible or will that ffi namespace be available to user's Lua scripts? On the issue of Sandboxing Lua I found http://lua-users.org/wiki/SandBoxes which is not talking about FFI though. Furthermore, the plan I have described above is assuming that the introduction of abstraction layers happens on the lua side of code. Is this an advisable approach or would you rather abstract functionality on the statically compiled code (on the C-side)?


Getting related foreign keys from parent entities

I'm thinking about a design issue which affects my project's data base. Supposing there are three diferent tables:   * CLIENT    * ORDER    * PACKING_SLIP * * * Each **order** has its **client** and different **packing slips**. So there are some foreign keys which are compulsory, there would be _clientId_ for the `ORDER` and _orderId_ for the `PACKING_SLIP` table. That makes full sense.            ![First diagram](http://i.stack.imgur.com/DLSEq.png) Now suppose in my logic I want to have access to the client from the packing slip. As I'm using an ORM tool as Hibernate, that involves firstly accessing the order from the packing slip and after getting the client from it. If I want to have access to the client directly, I should add the _clientId_ foreign key also to the `PACKING SLIP` table.                                  ![Second diagram](http://i.stack.imgur.com/7jwu0.png) My question is, is that a correct design if there's a possibility to get the client joining the `ORDER` table? Isn't it a bit redundant? I think it's a control problem and the data base part shouldn't take care about it...


Multivariable decisions

I am running into a situation where my program can have different outcomes depending on the state of some variables. 4 variables are involved and they can all have different ( 3 to 4 different states). All the possible combinations are leading me to about 48 different cases which would be resolved using a 4 level deep nested if/else structure. So, I have a couple of questions,   1. Is there a better technique to draw logic or decision tables or some other structure so that you can model a decision tree for this many outcomes? When a decision is dependent on only 2 variables you can easily model this on a spreadsheet which is two dimensional by its nature but how do you deal with a case like the one I mentioned?   2. Other than a 4 level deep nested if/else structure is there a better programming technique to deal with this?


What techniques/methodologies do you use to organize your own open source projects, and why?

Aside from using a specific tool such as JIRA or Bugzilla, what techniques or development methodologies do you use to keep your OSS development efforts organized? and more importantly, how do you prioritize which features to deliver when there really isn't any paying clients that decide which features are the most important to deliver?


HDD Failure Paranoia

HDD Failure Paranoia I tend to make small programs for myself. Whenever I make an application I use a database application like MS Access or MySQL. I can CRUD my data as I want. No problem in finishing a task. The problem is when I try exploring more into File IO. I have heard of HDD crashes due to high read/write operations. I used to think that these happened only on server machines. But then I came to know that it happens on desktop machines too! So I now I have this huge mental blockage. Whenever I try converting my former software into ones with raw FILE IO, I lose the "mental drive/motivation" and freeze. I get thoughts like "OMG this task will cause this many reads/writes to the disk". I fear for loosing my hard disk. My goodness! It has happened so many times that I wish that the computer engineers had redesigned the internals of the computer to fix the problem and so I curse them a lot. A lot of my time gets wasted remotivating myself and the projects never get completed. Ya, ya, I know that behind the scenes the database applications use raw File IO to do their work! But who thinks of that when using them. All you are mostly thinking of is SQL and the resulting table in the resultset/recodset. The database applications are like a black box to raw File IO. Does anyone else think the same? Are my fears valid? What should I do? Any views/ consolations? Help! This makes me mad and unproductive!


Should I persist notification before or after publishing it through Redis pub/sub?

I'm implementing a mechanism to notify a group of users about newly inserted blog comments. The architecture uses the Redis Pub/Sub mechanism. By definition, the pub/sub mechanism aims to propagate message to the right subscribers, without storing/persisting anything. Although blog comments are obviously persisted in DB, I also expect all notifications to be sent to be persisted in order to be retrieved at any time by an offline user that gets logged again. Of course, Redis could have persistent messages, but the cost for that is pretty high. I use a distinct main database, let's take for the example MySql. Currently, the workflow is:   1. A blog comment posted by a user is handled by my backend and firstly stored in DB.   2. An event is raised, let's call it "CommentedBlogEvent", that triggers a worker aiming to detect all the targeted user of the comment.   3. Assuming that 10 users are target of the comment, I insert 10 "notification rows" in my database associating the commentId and the targeted userId, each specific to a user since it would have a flag read/unread.   4. Then, once all notifications have been persisted, I use Redis Pub/Sub to trigger subscribers aiming to push results to the concerned online clients (through WebSockets for instance). **The "issue" is that the process could be slow because of the step 3.** Would it be tolerated to make the step 4 before the step 3, meaning before persisting it in DB, since a potential data loss isn't dramatic in my case (non-financial data etc)?   Advantage: Client gets result more quickly.   Drawback: User could receive a notification that failed to be stored in background, leading to a missing notification when user refreshes the page. What is the best way to handle this case, while keeping my main database as the notifications store?


how do you cope with long hours of coding?

I am just a high-school student but for a while now I have been coding for weeks (from early in the morning to late at night). I really enjoy it, however it can be really monotone. I usually listen to some webradios but they take my attention from coding sometimes. How do you cope with long hours of coding? How often do you take breaks how do you spend them? Do you have any kind of further advice?


Can PHP handle mouse events?

I'm a newbie in php and i want to know if php can handle mouse events such as upon mouseCicked, mouseDoubleClicked, mouseMoved, mouseHovered etc.. And can events like button click , like displaying alert after clicking the submit button If yes, how can it be done ? I know that this can be done in Javascript               <script>         window.onbeforeunload = "Are you sure you want to leave?";     <script/>      Are there any other ways to do it ? Thank You !


Should we live by using Suhosin with PHP?

A lot of my security experienced friends have told me that I need to code my web applications for working under the Suhosin PHP patch, Suhosin being _"an advanced protection system for PHP installations [...] designed to protect servers and users from known and unknown flaws in PHP applications"_. Sense stating that feat, I have had to rewrite quite a bit of of my functions and classes. Is this the new standard of making secure web applications so that it is harder to exploit and compromise? Is Suhosin now a _common_ requirement for web development in PHP?


What are the proper uses of the various "Sign-in" terminologies?

What are the preferred use cases for the following sets of terms:   1. Log in / Log out   2. Log on / Log off   3. Sign in / Sign out   4. Sign on / Sign off From what I can guess, "Logging in" should be used for a long-lived session (like a website), whereas "Sign in" should be for something that you will be attending to (like IM or a financial transaction). I'm a little fuzzy here...


Efficient way of evaluating an array of strings then add to an array in Ruby

I am looking for an efficient way of evaluating an array of strings against a series of rules and then adding them to another array. For example I have an array of strings:   1. something   2. a   3. 1234   4. #gohere I want to iterate through all the items in the array and evaluate them based on a series of rules. For example:   * Strings greater that 1 in length   * Strings that don't start with the # character I was thinking of either:   1. Nested loop of if statements evaluating the string for each rule and if they all pass then add to another array   2. Evaluating the string against rule 1 then adding to the array then performing another evaluation - I have discounted this since it requires lots of array read/write operations to evaluate the complete ruleset. Please note that I have kept the number of rules to two for brevity however I could be needing up to 10 rules. Additionally, I do not control the original array since the function I am calling returns an array of strings. I know I may have answered my own question with the nested loop however I wondered if anyone had any ideas for optimizing this type of situation. Also, I know I asked this question in the reference of Ruby but any pseudo- code would suffice.


What do you think of an interpreter written in Java?

I am currently working on the implementation of a new programming language, for fun. I realize that most languages never become popular, but I still want the language to have a high-quality implementation. The language is loosely lisp-like. It supports closures, first-class continuations, a homoiconic syntax, first-class functions, etc. In addition, I want my language to be able to have access to already established library code (specifically the Java Standard library, etc). Dynamically compiling to JVM byte-code is essentially out of the question, because of the difficulty of implementing the stated feature set (excluding first-class functions) using a virtual machine that is not designed to support it. On the other-hand, compiling to C/C++ or some other lower-level language will lead to an unwanted degree of platform-dependence and/or reduce/remove the ability to use the Java standard library via programs written in my language. My (largely-completed) approach to the implementation is to implement a custom p-code interpreter in Java. The high-level language simply compiles its code on-the-fly to essentially an array of instructions for this custom virtual machine. Each instruction is an object that implements a common interface. When executed, the instructions manipulate a stack-machine. Unfortunately, executing each instruction requires a virtual method call; whereas, the normal implementation of such interpreters does not use object based instructions. However, current micro-benchmarks and guess-based-estimates indicate that the completed implementation should match the speed of Python, given equivalent programs. **So do you think this method of implementation is crazy or amateurish, given the language's design goals?** **What would you do differently?**


Are there any tools for testing drag & drop Windows desktop applications?

I need to develop a Windows desktop application (win32 API) which will use drag & drop extensively in many formats, including my own. I need to test it, for example, with CF_TEXT dragging, CF_RTF, CF_DIB, CF_METAFILEPICT, and many others. The tool needs to have the following features:   1. Displaying the content of DataObject dragged into it with all available format viewers.   2. Allows preparation of a few samples of different clipboard formats together in a single DataObject, ready for dragging into my app.   3. Allows including my own format names into the formats list of the testing tool.


Company internal Android Market

i want to establish Android in our company. Since our company doesn't want our future internal Android Apps distributet to the Google Android Market i would need to setup an internal market. But i can't find any resources. Maybe someone here knows more!


Publishing VS2010 Web Solution to WordPress

I am wondering if it's possible to publish a website that I have created onto WordPress? If so, how? The site was created using VS2010. I've done some searching online, and all I've came up with are tutorials on WordPress on how to publish your Visual Studio site onto other things not related to WordPress. Thank you


How do you deal with people who ask you to fix their computer?

Because I'm a programmer, people constantly ask me to fix their computer. How do you handle this situation? Do you make exceptions for relatives, friends and coworkers? Do you charge people for it?


What server-side language(s) should be used for user-created information sites such as Facebook, SE, Blogs, etc.?


How to restrict the violation of an N-Tier Architecture

Recently we fitted a 4-Tier Architecture in our project composed by the following four main layers :   * User Interface Layer.   * Data Access Layer.   * Domain Layer.   * Business Layer. All the layers fulfill their usual roles in 4-Tier Architecture and interact which each one in the usual way. We use SVN to maintain our CVS. My problem is that we have many inexperienced programmers developing in a well formed architecture, and we have to be checking all the time the code to find violations of the architecture. For example:   * Sometimes include access to database in the User Interface Layer and not in the Business Layer which is where interact with the Data Access layer to read or save data in the database. Problems like the above occurs all the time. My question is: How to check the code before the programmers can submit his new changes to the repository and report violations of the architecture? How to avoid doing this manually?


How can I share a managed DBConnection across various objects?

I am implementing what I thought was a simple object wrapper around a database where one object "PartRecord" represents one row of a database table. I want a client to be able to request a given record and to receive an object that contains the data. The data read and exposed properties are all a piece of cake, but I am trying to share the MySqlConnection object in a coherent way. My initial naive implementation was to keep a private MySqlConnection object in a VB module and to have a functions that my classes can call. This would effectively be a singleton that any of my classes could share.               Private MySqlCn as MySqlConnection          Friend Function GetMySqlConnection() as MySqlConnection        If IsNothing(MySqlCn) then  MySqlCn = New MySqlConnection(cnstring)        if MySqlCn.State = ConnectionState.Closed then MySqlConnection.Open(cnstring)        Return MySqlCn     End Function          Friend Sub CloseMySqlConnection()        If Not IsNothing(MySqlCn) AndAlso (Not MySqlCn.State = ConnectionState.Closed) Then  MySqlCn.Close     End Function      With this method you can generally ensure that the objects will share a connection and that it will be open whenever the database is available, but you cannot guarantee that the connection gets closed until the program ends. Some alternatives that I have tried:   1. close connection after every read               'in PartRecord constructor:     Using MySqlCn as MySqlConnection = GetMySqlConnection       'read data     End Using     'this causes an open and close for every object you instantiate     'obviously bad        2. just leave it open              'in constructor:     Dim MySqlCn as MySqlConnection = GetMySqlConnection     'read data     'no close or dispose, open for the next guy     'we are sharing an open connection, but     'the connection won't really close until the program ends.     'I think it will close then, but I was a lot more certain of it     'in the COM days when I could wrap it in a class and     'close it in the Terminate event when the reference count hit zero        3. quit having public constructors and have a object factory that implements IDisposable to manage the connection              'maybe not as nice for the client code     'but does force a sharing of connections     'and the client can call PartFactory.Close or PartFactory.Dispose when they are done     'the PartFactory replaces the singleton     'even though you could have more than one if you wanted        4. your better idea . . . **I would like to know if I can keep my preferred style of public object constructors for a given record, but still manage the shared connection in a responsible way.** I think this might be impossible since the standalone publicly creatable objects do not know when the client is ever done. I think I must leak the "we are connecting to a database y'know" abstraction to the client or else cause open connections or unnecessary network traffic. Also, the documentation tells you that IDisposable is usually used for unmanaged things (files, handles, etc). Is is appropriate/necessary for holding a managed object like a .NET DBConnection object? I like that the client would have the Using syntax and that I am signalling that it needs closed in a standard way, but is the deterministic close that I am trying to get necessary and worth my effort in a garbage collected world? I am not comfortable saying "well the connection will close eventually when no one wants it" since this component will be eventually be used by many different clients in the organization. What if they crash, or we use it in a long- running server process? If it matters, this is the first of several DB wrapper classes. Whatever scheme I use here, I want to maintain across the entire component.


open source social network allowing advertising

I want to build up a social network, targeted to a specific interest. I want to generate revenues in form of ads. I first thought of building it from scratch, which will take a lot of time (even if it's something simple), then i remembered there are open source options like Diaspora or Friendica. I don't know if there are others... My question is, with these previously mentioned projects or any other, ¿is it possible to legally generate revenues? Diaspora license is: AGPLv3,[3][4] some parts dual-licensed under MIT License[5] as well Friendica: AGPL ¡Thank you!


Learning but then forgetting

I am teaching myself to program in C and have been for a few months. I recently took a one month break and came back a week ago, and it's all gone. I had to look up some things that I really put effort into understanding (see: pointers) and some others just stuck with me. Now learning about `malloc` and dynamically allocated memory is also getting a bit tough. What do you suggest for keeping it all retained? Will it just come with time and experience?


Using JDBC to asynchronously read large Oracle table

What strategies can be used to read every row in a large **Oracle** table, **only once** , but as fast as possible with JDBC & Java ? Consider that each row has non-trivial amounts of data (30 columns, including large text in some columns). Some strategies I can think of are:   * Single thread and read table. (Too slow, but listed for clarity)   * Read the id's into ConcurrentLinkedQueue, use threads to consume queue and query by id in batches.   * Read id's into a JMS queue, use workers to consume queue and query by id in batches. What other strategies could be used ? _For the purpose of this question assume processing of rows to be free._


online quiz app android

I'm interested in working on a project. The project involves a test taking app with 2 modules where there is one quizzer and multiple test takers. I want to make a web application which also has an android app for the same. How should i go along with making this project so that there are no issues as some user can be on the web app and some on the android app? How can i do it so that i don't have to write separate code for the web app and the android app? What should be my approach because i have never made an internet based android app? ( i only have some basic android programming experience, and i'm willing to learn more) but i have a fair experience with developing with jsp/servlets and frameworks. UPDATE: I do not want detailed answers. Just point me in the right direction.


Why should main() be short?

I've been programming for over 9 years, and according to the advice of my first programming teacher, I always keep my `main()` function extremely short. At first I had no idea why. I just obeyed without understanding, much to the delight of my professors. After gaining experience, I realized that if I designed my code correctly, having a short `main()` function just sortof happened. Writing modularized code and following the single responsibility principle allowed my code to be designed in "bunches", and `main()` served as nothing more than a catalyst to get the program running. Fast forward to a few weeks ago, I was looking at Python's souce code, and I found the `main()` function:               /* Minimal main program -- everything is loaded from the library */          ...          int     main(int argc, char **argv)     {         ...         return Py_Main(argc, argv);     }      Yay python. Short `main()` function == Good code. Programming teachers were right. Wanting to look deeper, I took a look at Py_Main. In its entirety, it is defined as follows:               /* Main program */          int     Py_Main(int argc, char **argv)     {         int c;         int sts;         char *command = NULL;         char *filename = NULL;         char *module = NULL;         FILE *fp = stdin;         char *p;         int unbuffered = 0;         int skipfirstline = 0;         int stdin_is_interactive = 0;         int help = 0;         int version = 0;         int saw_unbuffered_flag = 0;         PyCompilerFlags cf;              cf.cf_flags = 0;              orig_argc = argc;           /* For Py_GetArgcArgv() */         orig_argv = argv;          #ifdef RISCOS         Py_RISCOSWimpFlag = 0;     #endif              PySys_ResetWarnOptions();              while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {             if (c == 'c') {                 /* -c is the last option; following arguments                    that look like options are left for the                    command to interpret. */                 command = (char *)malloc(strlen(_PyOS_optarg) + 2);                 if (command == NULL)                     Py_FatalError(                        "not enough memory to copy -c argument");                 strcpy(command, _PyOS_optarg);                 strcat(command, "\n");                 break;             }                  if (c == 'm') {                 /* -m is the last option; following arguments                    that look like options are left for the                    module to interpret. */                 module = (char *)malloc(strlen(_PyOS_optarg) + 2);                 if (module == NULL)                     Py_FatalError(                        "not enough memory to copy -m argument");                 strcpy(module, _PyOS_optarg);                 break;             }                  switch (c) {             case 'b':                 Py_BytesWarningFlag++;                 break;                  case 'd':                 Py_DebugFlag++;                 break;                  case '3':                 Py_Py3kWarningFlag++;                 if (!Py_DivisionWarningFlag)                     Py_DivisionWarningFlag = 1;                 break;                  case 'Q':                 if (strcmp(_PyOS_optarg, "old") == 0) {                     Py_DivisionWarningFlag = 0;                     break;                 }                 if (strcmp(_PyOS_optarg, "warn") == 0) {                     Py_DivisionWarningFlag = 1;                     break;                 }                 if (strcmp(_PyOS_optarg, "warnall") == 0) {                     Py_DivisionWarningFlag = 2;                     break;                 }                 if (strcmp(_PyOS_optarg, "new") == 0) {                     /* This only affects __main__ */                     cf.cf_flags |= CO_FUTURE_DIVISION;                     /* And this tells the eval loop to treat                        BINARY_DIVIDE as BINARY_TRUE_DIVIDE */                     _Py_QnewFlag = 1;                     break;                 }                 fprintf(stderr,                     "-Q option should be `-Qold', "                     "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");                 return usage(2, argv[0]);                 /* NOTREACHED */                  case 'i':                 Py_InspectFlag++;                 Py_InteractiveFlag++;                 break;                  /* case 'J': reserved for Jython */                  case 'O':                 Py_OptimizeFlag++;                 break;                  case 'B':                 Py_DontWriteBytecodeFlag++;                 break;                  case 's':                 Py_NoUserSiteDirectory++;                 break;                  case 'S':                 Py_NoSiteFlag++;                 break;                  case 'E':                 Py_IgnoreEnvironmentFlag++;                 break;                  case 't':                 Py_TabcheckFlag++;                 break;                  case 'u':                 unbuffered++;                 saw_unbuffered_flag = 1;                 break;                  case 'v':                 Py_VerboseFlag++;                 break;          #ifdef RISCOS             case 'w':                 Py_RISCOSWimpFlag = 1;                 break;     #endif                  case 'x':                 skipfirstline = 1;                 break;                  /* case 'X': reserved for implementation-specific arguments */                  case 'U':                 Py_UnicodeFlag++;                 break;             case 'h':             case '?':                 help++;                 break;             case 'V':                 version++;                 break;                  case 'W':                 PySys_AddWarnOption(_PyOS_optarg);                 break;                  /* This space reserved for other options */                  default:                 return usage(2, argv[0]);                 /*NOTREACHED*/                  }         }              if (help)             return usage(0, argv[0]);              if (version) {             fprintf(stderr, "Python %s\n", PY_VERSION);             return 0;         }              if (Py_Py3kWarningFlag && !Py_TabcheckFlag)             /* -3 implies -t (but not -tt) */             Py_TabcheckFlag = 1;              if (!Py_InspectFlag &&             (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')             Py_InspectFlag = 1;         if (!saw_unbuffered_flag &&             (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')             unbuffered = 1;              if (!Py_NoUserSiteDirectory &&             (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')             Py_NoUserSiteDirectory = 1;              if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {             char *buf, *warning;                  buf = (char *)malloc(strlen(p) + 1);             if (buf == NULL)                 Py_FatalError(                    "not enough memory to copy PYTHONWARNINGS");             strcpy(buf, p);             for (warning = strtok(buf, ",");                  warning != NULL;                  warning = strtok(NULL, ","))                 PySys_AddWarnOption(warning);             free(buf);         }              if (command == NULL && module == NULL && _PyOS_optind < argc &&             strcmp(argv[_PyOS_optind], "-") != 0)         {     #ifdef __VMS             filename = decc$translate_vms(argv[_PyOS_optind]);             if (filename == (char *)0 || filename == (char *)-1)                 filename = argv[_PyOS_optind];          #else             filename = argv[_PyOS_optind];     #endif         }              stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);              if (unbuffered) {     #if defined(MS_WINDOWS) || defined(__CYGWIN__)             _setmode(fileno(stdin), O_BINARY);             _setmode(fileno(stdout), O_BINARY);     #endif     #ifdef HAVE_SETVBUF             setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);             setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);             setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);     #else /* !HAVE_SETVBUF */             setbuf(stdin,  (char *)NULL);             setbuf(stdout, (char *)NULL);             setbuf(stderr, (char *)NULL);     #endif /* !HAVE_SETVBUF */         }         else if (Py_InteractiveFlag) {     #ifdef MS_WINDOWS             /* Doesn't have to have line-buffered -- use unbuffered */             /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */             setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);     #else /* !MS_WINDOWS */     #ifdef HAVE_SETVBUF             setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);             setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);     #endif /* HAVE_SETVBUF */     #endif /* !MS_WINDOWS */             /* Leave stderr alone - it should be unbuffered anyway. */         }     #ifdef __VMS         else {             setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);         }     #endif /* __VMS */          #ifdef __APPLE__         /* On MacOS X, when the Python interpreter is embedded in an            application bundle, it gets executed by a bootstrapping script            that does os.execve() with an argv[0] that's different from the            actual Python executable. This is needed to keep the Finder happy,            or rather, to work around Apple's overly strict requirements of            the process name. However, we still need a usable sys.executable,            so the actual executable path is passed in an environment variable.            See Lib/plat-mac/bundlebuiler.py for details about the bootstrap            script. */         if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')             Py_SetProgramName(p);         else             Py_SetProgramName(argv[0]);     #else         Py_SetProgramName(argv[0]);     #endif         Py_Initialize();              if (Py_VerboseFlag ||             (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {             fprintf(stderr, "Python %s on %s\n",                 Py_GetVersion(), Py_GetPlatform());             if (!Py_NoSiteFlag)                 fprintf(stderr, "%s\n", COPYRIGHT);         }              if (command != NULL) {             /* Backup _PyOS_optind and force sys.argv[0] = '-c' */             _PyOS_optind--;             argv[_PyOS_optind] = "-c";         }              if (module != NULL) {             /* Backup _PyOS_optind and force sys.argv[0] = '-c'                so that PySys_SetArgv correctly sets sys.path[0] to ''                rather than looking for a file called "-m". See                tracker issue #8202 for details. */             _PyOS_optind--;             argv[_PyOS_optind] = "-c";         }              PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);              if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&             isatty(fileno(stdin))) {             PyObject *v;             v = PyImport_ImportModule("readline");             if (v == NULL)                 PyErr_Clear();             else                 Py_DECREF(v);         }              if (command) {             sts = PyRun_SimpleStringFlags(command, &cf) != 0;             free(command);         } else if (module) {             sts = RunModule(module, 1);             free(module);         }         else {                  if (filename == NULL && stdin_is_interactive) {                 Py_InspectFlag = 0; /* do exit on SystemExit */                 RunStartupFile(&cf);             }             /* XXX */                  sts = -1;               /* keep track of whether we've already run __main__ */                  if (filename != NULL) {                 sts = RunMainFromImporter(filename);             }                  if (sts==-1 && filename!=NULL) {                 if ((fp = fopen(filename, "r")) == NULL) {                     fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",                         argv[0], filename, errno, strerror(errno));                          return 2;                 }                 else if (skipfirstline) {                     int ch;                     /* Push back first newline so line numbers                        remain the same */                     while ((ch = getc(fp)) != EOF) {                         if (ch == '\n') {                             (void)ungetc(ch, fp);                             break;                         }                     }                 }                 {                     /* XXX: does this work on Win/Win64? (see posix_fstat) */                     struct stat sb;                     if (fstat(fileno(fp), &sb) == 0 &&                         S_ISDIR(sb.st_mode)) {                         fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);                         fclose(fp);                         return 1;                     }                 }             }                  if (sts==-1) {                 /* call pending calls like signal handlers (SIGINT) */                 if (Py_MakePendingCalls() == -1) {                     PyErr_Print();                     sts = 1;                 } else {                     sts = PyRun_AnyFileExFlags(                         fp,                         filename == NULL ? "<stdin>" : filename,                         filename != NULL, &cf) != 0;                 }             }              }              /* Check this environment variable at the end, to give programs the          * opportunity to set it from Python.          */         if (!Py_InspectFlag &&             (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')         {             Py_InspectFlag = 1;         }              if (Py_InspectFlag && stdin_is_interactive &&             (filename != NULL || command != NULL || module != NULL)) {             Py_InspectFlag = 0;             /* XXX */             sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;         }              Py_Finalize();     #ifdef RISCOS         if (Py_RISCOSWimpFlag)             fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */     #endif          #ifdef __INSURE__         /* Insure++ is a memory analysis tool that aids in discovering          * memory leaks and other memory problems.  On Python exit, the          * interned string dictionary is flagged as being in use at exit          * (which it is).  Under normal circumstances, this is fine because          * the memory will be automatically reclaimed by the system.  Under          * memory debugging, it's a huge source of useless noise, so we          * trade off slower shutdown for less distraction in the memory          * reports.  -baw          */         _Py_ReleaseInternedStrings();     #endif /* __INSURE__ */              return sts;     }      Good God Almighty...it is big enough to sink the Titanic. It seems as though Python did the "Intro to Programming 101" trick and just moved all of `main()`'s code to a different function called it something very similar to "main". Here's my question: Is this code terribly written, or are there other reasons to have a short main function? As it stands right now, I see absolutely no difference between doing this and just moving the code in `Py_Main()` back into `main()`. Am I wrong in thinking this?


Term for Production Rollback

The firm I work at keeps a copy of the compiled source code on production. So basically on our Production server, we have two folders:               ProductionServer\SourceCode\          ProductionServer\SourceCodeRollback\      The Rollback folder always contains one version older code. This is done so that on deployment nights, if something is wrong with the new code, the deployer(who is not familiar with source control software) has the older version to revert back to. My question is: Is there an official computer science term/nomenclature for the Rollback folder? Or is "Rollback" itself the official term?


How do I approach this PHP/MYSQL query?

I have a reservation system that I have coded and my final task is to allow the user to enter a set of dates and then show them all available options. The reservation table is set up with `unit_id`, `check_in` and `check_out`. There are twelve different unit numbers. So I have to somehow iterate through them and find the units that have no taken dates during the date range the user has put in. Just having some trouble conceptualizing what needs to happen. Pseudo code               $units = array (all the units);          foreach($units as $key = $value){              Run a query searching through all reservations for that unit,          if the unit is available, add to our $available_units array for the view later          }      Checking availability has me stumped too though. What is the most efficient way to use the customers available date range and compare to the date ranges in the db?


Sort algorithms that work on large amount of data

I am looking for sorting algorithms that can work on a large amount of data, i.e. that can work even when the whole data set cannot be held in main memory at once. The only candidate that I have found up to now is merge sort: you can implement the algorithm in such a way that it scans your data set at each merge without holding all the data in main memory at once. The variation of merge sort I have in mind is described in this article in section **Use with tape drives**. I think this is a good solution (with complexity O(n x log(n)) but I am curious to know if there are other (possibly faster) sorting algorithms that can work on large data sets that do not fit in main memory. **EDIT** Here are some more details, as required by the answers:   * The data needs to be sorted periodically, e.g. once in a month. I do not need to insert a few records and have the data sorted incrementally.   * My example text file is about 1 GB UTF-8 text, but I wanted to solve the problem in general, even if the file were, say, 20 GB.   * It is not in a database and, due to other constraints, it cannot be.   * The data is dumped by others as a text file, I have my own code to read this text file.   * The format of the data is a text file: new line characters are record separators. One possible improvement I had in mind was to split the file into files that are small enough to be sorted in memory, and finally merge all these files using the algorithm I have described above.


How would I use a browser as a GUI for Emacs apps?

I've started using Emacs, and love it. Naturally, I'm thinking about ways of extending it. I' m particularly fascinated by the thought of creating browser based GUIs for some stuff I would otherwise do in emacs, particularly reviewing fairly static data. An example: I have a bunch of txt files (created and edited in Emacs) containing quotes and passages from my favorite books. It would be cool to present them in a more visually striking/engaging manner. For example with unique color schemes and typefaces for different authors, and several columns of text to use more screen real estate (like in Stanza, the .epub reader). Are there simpler ways of rendering HTML derived from plain text files that are open in Emacs than browsers?


Development Approach: User Interface In or Domain Model Out?

While I've never delivered anything using Smalltalk, my brief time playing with it has definitely left its mark. The only way to describe the experience is MVC the way it was meant to be. Essentially, all the heavy lifting for your application is done in the business objects (or domain model if you are so inclined). The standard controls are bound to the business objects in some way. For example, a text box is mapped to an object's field (the field itself is an object so it's easy to do). A button would mapped to a method. This is all done with a very simple and natural API. We don't have to think about binding objects, etc. It just works. Yet, in many newer languages and APIs you are forced to think from the outside in. First with C++ and MFC, and now with C# and WPF, Microsoft has gotten it's developer world hooked on GUI builders where you build your application by implementing event handlers. Java Swing development isn't so different, only you are writing the code to instantiate the controls on the form yourself. For some projects, there may never even be a domain model--just event handlers. I've been in and around this model for most of my carreer. Each way forces you to think differently. With the Smalltalk approach, your domain is smart while your GUI is dumb. With the default VisualStudio approach, your GUI is smart while your domain model (if it exists) is rather anemic. Many developers that I work with see value in the Smalltalk approach, and try to shoehorn that approach into the VisualStudio environment. WPF has _some_ dynamic binding features that makes it possible; but there are limitations. Inevitably some code that belongs in the domain model ends up in the GUI classes. So, which way do you design/develop your code? Why?   * GUI first. User interaction is paramount.   * Domain first. I need to make sure the system is correct before we put a UI on it. There's pros and cons for either approach. Domain model fits in there with crystal cathedrals and pie in the sky. GUI fits in there with quick and dirty (sometimes really dirty). And for an added bonus: How do you make sure the code is maintainable?


Where can I find interesting project to work on?

If I want to learn a new programming language, I cannot master it without digging it deeply. Maybe a project would be good, but I am lacking idea for them. Where can I find projects to work on, maybe some open-source project?


Is context inheritance, as shown by Head First Design Patterns' Duck example, irrelevant to strategy pattern?

In Head First Design Patterns it teaches the strategy pattern by using a Duck example where different subclasses of Duck can be assigned a particular behavior at runtime. From my understanding the purpose of the strategy pattern is to change **a single** object's behavior at runtime, yet they are using inheritance of Duck to change the behavior of various types of Duck. ![Strategy Pattern](http://i.stack.imgur.com/EIsOf.png) ## Relevance? **Is context inheritance of Duck irrelevant to the strategy pattern or is varying Duck types and also varying their behaviors a good reason to employ the strategy pattern?** Do situations where you need to vary both constitute a good reason to use strategy pattern? Why would they include this as the strategy pattern example? ## A Simpler Example Could I further simplify this example by just having a Duck class (no derived classes)? Then when implementing one duck object it can be assigned different behaviors based on certain circumstances that aren't dependent on its own object type. For example: FlyBehavior changes based on the weather or QuackBehavior changes based on the time of day or how hungry a duck is. I realize this would be solving a different problem than from the one in the book, but what I am looking for is a relevant strategy pattern example to fall back on. Would my example above constitute the strategy pattern as well? ## Edit: I was successful in finding 2 simpler strategy pattern examples that adhere more strictly to being just strategy patterns without context inheritance: Hunter.java and solver.py.


What would be the fastest way of storing or calculating legal move sets for chess pieces?

For example if a move is attempted I could just loop through a list of legal moves and compare the x,y but I have to write logic to calculate those at least every time the piece is moved. Or, I can store in an array [,] and then check if x and y are not 0 then it is a legal move and then I save the data like this [0][1][0][0] etc etc for each row where 1 is a legal move, but I still have to populate it. I wonder what the fastest way to store and read a legal move on a piece object for calculation. I could use matrix math as well I suppose but I don't know. **Basically I want to persist the rules for a given piece so I can assign a piece object a little template of all it's possible moves considering it is starting from it's current location** , which should be just one table of data. But is it faster to loop or write LINQ queries or store arrays and matrices?               public class Move     {         public int x;         public int y;     }          public class ChessPiece : Move     {             private List<Move> possibleMoves { get; set; }              public bool LegalMove(int x, int y){           foreach(var p in possibleMoves)           {              if(p.x == x && p.y == y)              {  return true;  }              }         }     }      Anyone know?


Subsumption architecture vs. perceptual control theory

I'm a new person to AI field and I have to research and compare two different architectures for a thesis I'm writing. Before you scream (homework thread), I've been reading on these two topics only to find that I'm confusing myself more.. let me first start with stating briefly what I know so far. **Subsumption** is based on the fact that targets of a system are different in sophistication, thus that requires them to be added as **_layers_** , each layer can suppress (modify) the command of the layers below it, and there are inhibitors to stop signals from execution lets say. **PCT** stresses on the fact that there are nodes to handle environmental changes ( ** _negative feedback_** ), so the inputs coming from an environment go through a comparator node and then an action is generated by that node, HPCT or (Hierarchical PCT) is based on nesting these cycles inside each other so a small cycle to avoid crashing would be nested in a more sophisticated cycle that targets a certain location for example. My questions, am I getting this the right way? am I missing any critical understanding about these two models? also any idea where I can find simplified explanations for each theory (so far been struggling trying to understand the papers from Google scholar). * * * **Edit:**   * The acceptable result would be to compare and contrast subsumption with PCT as alternative control structures in behaviour-based robotics.   * The experiments will be done on Mindstorm NXT 2.0 robot and the implementation will be done using PureData.   * I'm not seeking complex behavior, only several models that will demonstrate capabilities of PCT and Subsumption and come up with weaknesses and strengths about each approach.   * As for the other points 'rwong' mentioned, I don't believe they're part of my research scope. _**my main target here is to get he concepts fully understood as this is my critical phase to implement a fully correct solution that would allow the comparison_**


Entity framework and Eager loading and enterprise application with DDD aproach

We are trying to create an ASP.NET MVC 4 application using entity framework with domain driven development style pattern approach. As you can see in our part of domain layer, we have a complex design. We need to load entity with lazy as well as eager methods. Unfortunately we have big problem with these methods in entity framework. As we understand, for eager loading in EF we have to use the `Include` method and give string of properties and properties of properties etc. (In Hibernate and java we could use annotation top of member to load eagerly and it was so much easier than this approach). But the horrible problem is that we have inheritance structures and heavy polymorphism, in these states we don’t have that’s string we should given to include because we don’t know which derived class of class is selected to understand which properties should include. ![Our model](http://i.stack.imgur.com/b5OCM.png) For example as you can see a result has a collection of items and then decides to add some group to this collection and each of those groups have some groups and fields (like the composition pattern). Now imagine we want to load a result is like the one talked above. When I want to write a string of given include I don’t know what items of this result are groups. Because we can’t predict these items are groups and so these groups have collection of items which should load.               this.Items = new List<Item>                  {                     new Group(                         a,                         new List<Item>                         {                              new Field(b),                             new Field(c),                             new Field(d),      At last we have a critical question: is entity framework designed for Enterprise Applications with a complex domain and DDD approach? If not, how we follow the approach of Martin Fowler and Eric Evans in software engineering and enterprise application in C#?


Better way to train new hires

The team I currently am part of experiences fairly high turnover, with members typically moving to different projects within the same company. Currently our "training" for new members is to pair them with a primary contact (usually the most recent person to complete their training) who will provide them with hands-on experience and will ask more senior developers if the newer hire ask something the mentor doesn't know. It provides a chance for the new hire to get involved quickly, and challenges the mentor to improve his/her understanding of the system also. However, as you can imagine, this style of training is very time consuming, and doesn't provide a very good knowledge transfer (misconceptions propagate, gaps expand). I've been tasked with generating documentation and training materials for our future new hires. I already do technical writing occasionally, but it's for the end user and is highly specific with lots of screenshots and consumes a large amount of time to complete. Creating the new documentation for new hires is considered low priority and I've only currently got ~40 hours to work on it. Documenting the system the current way I write technical documentation would barely scratch the surface in 40 hours. Especially considering I have to document not only about the code base, but also about deployments and support. How can I quickly write documentation to get new hires up to date as quickly as possible without investing significant time in writing the documentation? **Additional Information:**   We currently have both a wiki, and some training documentation, however both are kind of sparse.


How to inform a colleague of .NET and C# coding guidelines without offending him?

I have a good colleague at work that I work often and he is pretty smart. He is not a .NET programmer but now is coding for a long time too, mainly C++, Python, etc. I see that he is using Python like guidelines in naming, etc, and in shared code, it looks non-uniform to have things like: getEffectById, etc and many other Python names, etc. How do you guys think I should tell this to him so he isn't offended or think I am looking down on his code or skills, because I don't.


Why should I choose Java, Flash, or HTML5 for an online game with server communication

I'm starting to design a game that is going to have the following characteristics, and I'm trying to decide how I should program it. I'll also give a bit of my experience after, to help make the decision a bit better.   1. The game should be able to support both Facebook integration, and a stand alone version.   2. I don't want to do it right away, but I am thinking it would be a good idea to port this to Android/ iPhone at some point in time.   3. The game will involve communication with a server. The method of communication is still opened, but I imagine most of it will be over HTTPS. I'm suspecting most of the work is going to be done on the server at this point in time, and that the client is mainly going to show the results of the previous frame, and select what to do for the next frame.   4. I suspect that at some point in time, I'm going to want to put in animations and the like, but this is not critical for the beginning of the game.   5. The game is essentially an online board game, complete with cards, a board, etc. I'm currently looking at Flash, HTML 5, and a Java applet. Some random pieces of information.   1. I have access to Adobe Flash, actually the whole Design Premium, CS5.   2. I have some experience with programming Android apps.   3. I have done work with HTML, but it has been quite a while. I've only done a little bit of Javascript, but I don't recall it being particularly hard.   4. I routinely program in C, C++, Matlab, and Android (Java). I fairly often program in Python, Perl, Shell, and I have programmed before in Basic, HTML, Javascript.


Is it bad practice to run Node.js and apache in parallel?

I have an idea in mind and would like to know if that's the way to go for my end application. Think of my application as a social networking system in which I want to implement chat functionality. For that, I'd like to push data from the server to the client. I have heard I could use Node.js for that. In the meanwhile, I want a 'regular' system for posting status updates and such, for which I'd like to use PHP and an apache server. The only way I can think of is having Node.js and apache running parallel. But is that the way to go here? I'd think there would be a somewhat neater solution for this.


How are OOP "objects" and "classes" organized in memory in terms of assembly language?

How are objects organized in memory? For instance, I know that a function is a piece of code in memory, that expects parameters via the stack and/or the registers and handles it's own stack frame. But objects are a much more complicated structure. How are they organized? Does each object have "links" to methods and passes address to itself to that method? It would be great to see a good explanation of this topic. UPD. I made the question more exact, and I'm mainly interested in statically typing languages.


How would I design an interface such that it's clear which properties may change their value, and which will remain constant?

I am having a design issue regarding .NET properties.               interface IX     {         Guid Id { get; }         bool IsInvalidated { get; }         void Invalidate();     }      **Problem:** This interface has two read-only properties, `Id` and `IsInvalidated`. The fact that they are read-only, however, is by itself no guarantee that their values will remain constant. Let's say that it were my intention to make it very clear that…   * `Id` represents a constant value (which may therefore be safely cached), while    * `IsInvalidated` might change its value during the lifetime of an `IX` object (and so shouldn't be cached). How could I modify `interface IX` to make that contract sufficiently explicit? **My own three attempts at a solution:**   1. The interface is already well-designed. The presence of a method called `Invalidate()` allows a programmer to infer that the value of the similarly-named property `IsInvalidated` might be affected by it. This argument holds only in cases where the method and property are similarly named.   2. Augment this interface with an event `IsInvalidatedChanged`:              bool IsInvalidated { get; }     event EventHandler IsInvalidatedChanged;      The presence of a `…Changed` event for `IsInvalidated` states that this property may change its value, and the absence of a similar event for `Id` is a promise that that property will not change its value. I like this solution, but it's a lot of additional stuff that may not get used at all.   3. Replace the property `IsInvalidated` with a method `IsInvalidated()`:              bool IsInvalidated();      This might be too subtle a change. It's supposed to be a hint that a value is computed freshly each time -- which wouldn't be necessary if it was a constant. The MSDN topic "Choosing Between Properties and Methods" has this to say about it: > _Do use a method, rather than a property, in the following situations. […] > The operation returns a different result each time it is called, even if the > parameters do not change._ **What kind of answers do I expect?**   * I am most interested in entirely different solutions to the problem, along with an explanation how they beat my above attempts.   * If my attempts are logically flawed or have significant disadvantages not yet mentioned, such that only one solution (or none) remains, I would like to hear about where I went wrong. If the flaws are minor, and more than one solution remains after taking it into consideration, please comment.   * At the very least, I would like some feedback on which is your preferred solution, and for what reason(s).


How to simulate events that cause exceptions to test try/catch blocks?

I understand how exceptions work and how to catch and handle them in C# but how can I simulate events that may cause an exception to ensure that it is caught correctly? For example, is it possible to run an application in a kind of test bed where it's possible to simulate network problems, database problems, etc? Exceptions by their nature seem hard to reproduce thus making it hard to ensure your code can cope with them. Although I mainly develop using C#/.NET/Visual Studio, answers or resources relating to other languages could be useful.


Pass ID or Object?

When providing a business logic method to get a domain entity, should the parameter accept an object or an ID? For example, should we do this:               public Foo GetItem(int id) {}      or this:               public Foo GetItem(Foo foo) {}      I believe in passing objects around, in their entirety, but what about this case where we're getting an object and we only know the ID? Should the caller create an empty Foo and set the ID, or should it just pass the ID to the method? Since the incoming Foo will be empty, except for the ID, I don't see the benefit of the caller having to create a Foo and set its ID when it could just send the ID to the GetItem() method.


Is there a way to compare and record changes to code without VCS?

I'm working for a client that has no version control system in place. I want to record changes to code without having to add all changes to a spreadsheet. I'm restricted to using Notepad++ so would a plugin or macro for this be another option?


Have you ever dealt with writing a spec late in the development lifecycle?

We have an existing code base which has been developed to meet the needs of most of our clients, which has accumulated features and bug fixes as they were needed and as projects developed universally useful features. Right now, we're running into the problem that there's no real documentation for its capabilities outside of the code itself, and on larger jobs it can mean that it's difficult to determine what should be included in the scope of work. How would you approach writing a defined spec for an existing application or framework?


Why has the PowerCollections C# library recently declined in popularity?

I just looked at the statistics for the PowerCollections C# library and noticed a sharp decrease in quantity of downloads. What may be the cause? Is there something better I should be using?


Representing a deck of cards in C (not C++)

So far my best ideas have been as fallows A) Represent a "card" in one structure and have a "deck" in another a deck being an array of 52 cards and a card being 2 chars one for and rank one for suit. B) The second seems like it might be easier to manage but less obvious in code. Creating an array of ints each with a different value ranging from 1-52. Then crating a conversion function that would translate the value to a card structure that would have a string for the suit and a string for the rank. The value of zero could indicate a card that has not been "dealt". Just trying to find a better way of doing this.


Is there a name for the number of values a variable can take?

For example, a bit or a boolean can be either 0 or 1 so the number 2 is associated with it. Similarly, for a byte which is 8 bits, the maximum number of different assignments would be 2^8. Is there a name for this number? When we pass everything through our system that has ECMAScript, Java and MySQL, then a boolean does not have only two possible assignments. For instance, a false boolean gets saved as a 0 and the boxed value could be null so a boolean suddenly can get true, false, 0, 1, null or even undefined or `<missing>`. I think it could get problematic in tests to guarantee that the values are not inconsistent. For instance, a value `boolean locked` could become `null` and then when a script or a layout template evaluates it then it will evaluate to `false` somewhere if the real value was `null` and similar problems. So why don't we always assert that a boolean has the same number of possible values (2 values) and similarly for other types? There is a mathematical term named "arity" that is something similar but not exactly, and statistics and probability theory also has the concept of "event space" that would be almost exactly what I mean. For instance, the event space for a boolean would be the set `{0,1}` which has cardinality 2 and that cardinality doesn't get preserved throughout the system, especially when data is passed as polyglots and/or serialized (json, jsonp, xml, yaml).


Setting Up a Development Environment

I am part of an organization that is formalizing their software development processes/capabilities/etc. While the organization is not traditionally a software organization, they want to do this right and provide the developers who work in the organization (which includes me) a solid set of tools in which to work from. In particular, we are looking at standing up: source control, bug tracking software, documentation tools (for the developers - not for end-users), and, in general, project management software (continuous integration, project tracking, code review, software push). Some of the high-level requirements are:   * Free is better. While we will consider purchasing tools, there is so much support in the FOSS community for development tools, I want to look there first.   * Integration across systems. (For example, the bug tracking software should be able to link back to the source control.)   * Easy to Import To and Export From. I do not want lock-in.   * (Relatively) Easy to learn. At this point, here is what I am looking at so far as my recommendations:   1. Source Control - Mercurial or Git \- I am personally leaning more towards Mercurial based on my research and the fact that Mercurial appears to be easier to setup in our environment.   2. Bug Tracking - I'm at a loss here. I have used Bugzilla in the past, but, it makes me cringe when I use it.   3. Documentation - MediaWiki, Screwturn Wiki, Atlassian (of course, this costs money so that is not ideal) I am looking for other suggestions of productivity tools/development tools that you have used. Please remember that we are a small organization, so I don't want to go over the top, but I do want to give developers good tools to use.


Managing Maven dependencies between multiple components with multiple teams making changes

In a situation where there are multiple teams making changes to some Maven projects with dependencies between them (otherwise unrelated projects i.e. no super POM or anything like that), with each team working in a separate working branch on all of these projects and merging them back to trunk only after a story is complete and tested, how should one handle the dependencies between snapshot builds that each team produces? Note that any of the teams could be making changes in any of the projects: they work on different pieces of functionality of the same system, and the projects are more like different layers. Before the split into multiple teams, artifacts were deployed to a central Nexus repository. Of course, it would be possible to set up separate Nexus repositories for each team, and an additional one for trunk, but I'm hoping there would be a better way to deal with this.


Assembly & The Programming Field

As it were, I do enjoy programming in assembly. I know that as a rule, assembly is platform specific so 'x' assembly will not help me if I had to work with 'y' machines. That said, how common are (at least competent) assembly programmers and how in demand are they?


Predicting the output of PHP's rand()

I've read in numerous sources that the output of PHP's rand() is predictable as its a PRNG, and I mostly accept that as fact simply because I've seen it in so many places. I'm interested in a proof-of-concept: how would I go about predicting the output of rand()? From reading this article I understand that the random number is a number returned from a list starting at a pointer (the seed) -- but I can't imagine how this is predictable. Could someone reasonably figure out what random # was generated via rand() at a given moment in time within a few thousand guesses? or even 10,000 guesses? How? This is coming up because I saw a auth library which uses rand() to produce a token for users who have lost passwords, and I assumed this was a potential security hole. I've since replaced the method with hashing a mixture of `openssl_random_pseudo_bytes()`, the orignal hashed password, and microtime. After doing this I realized that if I were on the outside looking in, I'd have no idea how to guess the token even knowing it was a md5 of rand().


Can a developer get a discount for Microsoft products?

If I would start to focus on the .NET platform and be self-employed, then I probably would like to have some Windows 7, Windows Server 2008, Visual Studio 2010 licenses just for the development environment and for testing, and then a few licenses for the production environment (a Windows Server 2008 Web) and added to that upgrades when new versions is available. This will end up in a quite big amount of money. Is there any kind of bundle discount that I can get from Microsoft in such a case? And what is the requirement to be able to get that discount?


Bug cleanups in the middle of a project

In my current company, in all software projects I've been in, there's usually a phase at the end of a project that eats some good amount of time and is dedicated to polishing new features so that they're ready for launch. In Steve McConnell's book "Software project survival guide", he advocates doing that after each major milestone that's completed on a project (and possibly launching at that point too). Let's say that we don't want to launch after completing major milestones, because our product needs to be launched in a more coherent state. Have any of you had a positive experience with serious bug cleaning efforts done a couple of times during the project lifespan, as opposed to doing that before launch?


Why isn't rich code formatting more common?

I was reading _Code Complete_ and in the chapter on layout and style, he was predicting that code editors would use some sort of rich text formatting. That means, instead of code looking like this               Procedure ResolveCollisions     { Performs a posteriori collision resolution through spatial partitioning algoritm }     (       CurrentMap : SpriteContext,       PotentialColliders: SpriteList     )     var Collider  : Sprite,          Collidee  : Sprite,          Collision : SpriteCollision     begin       DoStuff();     end.      it could look something like this: # Procedure `ResolveCollisions` _Performs a posteriori collision resolution through spatial partitioning algorithm_ **Parameters**   * `CurrentMap : SpriteContext`   * `PotentialColliders : SpriteList` **Local Variables**   * `Collider : Sprite`   * `Collidee : Sprite`   * `Collision : SpriteCollision`                   DoStuff();      * * * I've seen syntax coloring and highlighting and even parentheses coloring, but nothing that looked like this in actual code. I was wondering if this sort of thing actually ever existed, or perhaps if it was decided that it didn't have enough benefit or that it was an entirely bad idea. Have any of you seen richly-formatted code like this before, or know if the idea was ever considered and eventually rejected?