title: Object-Oriented design and proper Java architecture for my program

text: This is the very first time that I think I want to create a program which really uses OOP principles and I want to do it in the most effective and efficient way. First of all we are given this (great) riddle : > 100 prisoners are imprisoned in solitary cells. Each cell is windowless and > soundproof. There's a central living room with one light bulb; the bulb is > initially off. No prisoner can see the light bulb from his or her own cell. > Each day, the warden picks a prisoner equally at random, and that prisoner > visits the central living room; at the end of the day the prisoner is > returned to his cell. While in the living room, the prisoner can toggle the > bulb if he or she wishes. Also, the prisoner has the option of asserting the > claim that all 100 prisoners have been to the living room. If this assertion > is false (that is, some prisoners still haven't been to the living room), > all 100 prisoners will be shot for their stupidity. However, if it is indeed > true, all prisoners are set free and inducted into MENSA, since the world > can always use more smart people. Thus, the assertion should only be made if > the prisoner is 100% certain of its validity. > > Before this whole procedure begins, the prisoners are allowed to get > together in the courtyard to discuss a plan. What is the optimal plan they > can agree on, so that eventually, someone will make a correct assertion? So I've got a solution and I want to create a program to run it. I want my program to be as modular as possible, meaning that if I find a better solution, I don't to have to rewrite all of my code. I think OOP is really suited for this. Here's what I've done so far:   * A **Main** class : where I just run several games to test solutions   * A **Game** class : which just runs one 'attempt'. It has a 'jail' (which is just an array of prisoners), a day counter and other useful stuffs.   * And a **Prisoner** class : which just represent one single prisoner. After thinking this through, the only things that one prisoner can do are _changing the light where they're picked_ and _stating (or not) that everyone has come in the room_. In the solution I've come up with, I have two types on Prisoner. What I've done is that I just implemented my Prisoner class with the most classic type of Prisoner and created a subclass which simply overrides methods from the Prisoner class. Right now, I see two possible improvements if I want to reuse my code :   * make the **Prisoner** class a Java interface, so that when I want to create a new type, I'd just have to implement a Prisoner. But the main issue is that I mostly have 'typical prisoners', a lot of people having the same pattern. Do I just create a implementation 'Classic_Prisoner' ?   * creating a **Behaviour** class which handles what behaviour one Prisoner have given a single situation. But isn't just the same problem ? I mean I would also have to create one Behaviour subclass for each type of Prisoner I'm considering. What to do to have the cleanest code there and be able to reuse it when the time comes?


title: Which algorithms do I need to look into?

text: First things first: I need to apologize in advance about the bad choice of title for this question, but I really couldn't come up with something meaningful. I'm actually looking for suggestions as to what this kind of problem in called, so that I can do some research on my own. I will gladly change the title once the suggestions will start to come in. It's not even a real problem, it's just an exercise I made up in order to explore algorithms I have never had the chance to deal with. Let's say we want to write a program that will help us to optimize the logistics of an arbitrary number of music bands that have to perform one after the other on the same stage during the same night. Here's the problem: the bands share players, meaning that any given player can play in more than one band. Were the bands all made of different players, we wouldn't need a program at all, but since all the musicians know each other, they will form many bands with different combinations of them. What we want to do is to arrange all the bands in such a way that groups that share the greatest number of members will "cluster" together and play one after the other, so that we can minimize the number of musicians involved with each change of band. In other words, the largest number possible of musicians should be already on stage each time a band finishes its set and the next one comes on stage. Is this just another form of the famous staff rostering / scheduling problem? Or is it simpler? I admittedly haven't yet though hard about how one might solve it, it's just a problem that I thought of today. If I had to take a stab at it, it looks like the problem boils down to figuring out which bands have the most members in common, and sort them accordingly. But how is this called in CS parlance? And, is that all there is to it? Arranging bands by the number of musicians is the only requirement we have. I sense that, if we had to take into account other kinds of constraints like, say, one particular band would really prefer playing at the beginning and another right in the middle, this might turn into a full-fledged scheduling problem. In its simplest form, though, this appears to be a simple problem but, like I said, I don't know the name of the family of algorithms that would enable me determine which bands have the most musicians in common.


title: What open source licenses allow for combining code that compiles into a single assembly?

text: I'm trying to make a library that will be used by other developers. I want to obey the "don't re-invent the wheel" principle and and I also want to make the deployment a matter of dropping a single .dll into the bin folder. So far, I've chosen an dual MIT/MS-PL license. Is there anything stopping me from compiling other MSPL/MIT licensed code directly into the same assembly as my own? Am I worried about nothing? If this is a legit concern, should I go add a licence/copyright header to each file before I add other code to my code base, since there won't be a nice tidy assembly to delineate where the code came from? Also, I will add the header for you so you can get to writing the answer faster: "You are not a lawyer, you are not giving legal advice, I should fork over my hard earned money to a profession I detest to resolve questions like this instead of asking for free advice"


title: Logical progressions through the job market

text: I'm 5 years out of a unrecognised university where I did Software Engineering. First job was VB.NET, one job was Python, Linux and Web development. I feel cast as a web developer. I'd love a role doing C but no one is interested in juniors if the applicant hasn't got 3 years of C development experience already. I've done some C and a drop of open source coding but I'll never have the confidence to convince someone I know absolutely what I'm doing. Do I just spend more and more time letting life pass me by as I sit in my room on a friday night writing a C problem "for the sake of learning more C" Basically I'm just not sure I want to continue my career if it's going to involve nothing but high level, machine abstracted, business logic and as interested as I am in low level development and enjoy reading books by Taunembaum I struggle to see how I can make the jump and I just feel life would be easier if I got a job in a cafe in Amsterdam rolling spliffs for customers. My ideal job, being a paid member of the Fedora development team seems so far away, without anyone to pay me to learn the skills to get there, and the only way would be to literally spend weeks and weeks of my life contributing code without recognition for free and without any guarentees at the end. Not that I've contributed anything at all so far. Are there any career paths that are logically set out so that jumping between roles is "correctly" incremental and where hard work and learning does eventually lead to the kind of places I might want to go? [ and also getting paid at the same time? ]


title: Android Application(Client) and Server(C#.Net) Communication

text: I am confused which approach to choose - Poll (which waste battery), GCM or any other approach which suits best? **Scenario is:** my client is **Android** and server is **C#.Net**. Server sends Invitation to client. Server can choose whom to send (Regionwise, Particular, To All). Client can accept or reject the invitation.which sends result back to server


title: Efficient algorithm for Virtual Machine(VM) Consolidation in Cloud

text: **_PROBLEM:_**   We have **N** physical machines(PMs) each with ram **R** i, cpu **C** i and a set of currently scheduled VMs each with ram requirement **r** i and **c** i respectively   Moving(Migrating) any VM from one PM to other has a cost associated which depends on its ram **r** i. A PM with no VMs is shut down to save power.   Our target is to minimize the weighted sum of (N,migration cost) by migrating some VMs i.e. minimize the number of working PMs as well as not to degrade the service level due to excessive migrations.   **_My Approach:_**   Brute Force approach is choosing the minimum loaded PM and try to fit its VMs to other PMs by First Fit Decreasing algorithm or we can select the victim PMs and target PMs based on their loading level and shut down victims if possible by moving their VMs to targets.   I tried this Greedy approach on the Data of _Baadal_ (IIT-D cloud) but It isn't giving promising results.   I have also tried to study the Ant colony optimization for dynamic VM consolidating but was unable to understand very much. I used the links.   http://dumas.ccsd.cnrs.fr/docs/00/72/52/15/PDF/Esnault.pdf http://hal.archives-ouvertes.fr/docs/00/72/38/56/PDF/RR-8032.pdf Would anyone please clarify the solution or suggest any new approach/resources for better performance.   I am basically searching for the algorithms not the physical optimizations and I also know that many commercial organizations have provided these solution but I just wanted to know more the underlying algorithms.   Thanks in advance.


title: Splitting big request in multiple small ajax requests

text: I am unsure regarding the scalability of the following model. I have little experience with large systems, big number of requests and so on but I'm trying to build some features considering scalability first. In my scenario there is a **user** page which contains data for:   1. User's details (name, location, workplace ...)   2. User's activity (blog posts, comments...)   3. User statistics (rating, number of friends...) In order to show all this on the same page, for a request there will be at least 3 different database queries on the back-end. In some cases, I imagine that those queries will be running quite a wile, therefore the user experience may suffer while waiting between requests. This is why I decided to run only step 1 (User's details) as a normal request. After the response is received, two ajax requests are sent for steps 2 and 3. When those responses are received, I only place the data in the destined wrappers. For me at least this makes more sense. However there are 3 requests instead of one for every user page view. Will this affect the system on the long term? I'm assuming that this kind of approach requires more resources but is this trade of UX for resources a good dial or should I stick to one plain big request?


title: What will be correct answer to "why is NoSQL faster than SQL" on interview?

text: It's just nonsense for me personally. I can't see any performance boost by using NoSQL instead of SQL. Maybe SQL over NoSQL, yes but not in that way. I think that if I answer "I have no idea" or something like that it will be bad answer because this doesn't really look like a fake-question, it's a serious question on interview but how should be looking correct answer on this question? Or am I missing something about NoSQL?


title: What is the best way to work with mailing lists?

text: Many open source project have mailing lists a preferred way of communication. If i just sign to the mailing list via my g-mail account i will see ~100 messages per day that are not threaded but just a plain list. What is the preferred way to work with mailing lists so i can see a tree-view of threads and replys?


title: Version Control Options for Shared Network Folder

text: The company I work for has no version control. It will never have version control, so a server-based solution is out of the question. Also, our network is extremely slow. Often, it takes a few seconds to save a small file. I work with a small team. Are there any version control options for a shared network folder? I'm looking for something where I can go to work, do a pull, work off my C: drive all day, then push at the end of the day. Basically the same thing as GitHub, except with a network drive, I guess.


title: Emulate enviroment locally or accept use of a dev enviroment

text: I'm at a new job and I _really_ want to set up my VM to be able to emulate some or all of the enviroment locally. I'm told it's not possible, but I hate to accept that. To give some context, I'm very new to a poject that is many years old, but semi-recently (about a year) inherrited by an entirely new team that still doesn't fully understand the codebase the inherrited. The code is huge with dozens of maven projects, and is written with the intent that parts will run on different servers, including logic to sync DB's of versions on either side of a firewall. Currently the team copy their code to a dev enviroment, runs it, and looks at log files for integration testing. Everyone shares the same dev enviroment and communicate to avoid collisions, on a dozen large team. This just feels like an inefficent pain. I've been told the enviroment is too complex to emulate. When I ask about just emulating the GUI/frontend half I'm told that it's too hard to get to integrate with tomcat and others have tried and failed. No one can quite explain 'why' they failed though, and it sounds like they didn't try alternate approches to make it happen. So...should I rock the boat? It seems insanly inefficent the way they are doing things, especially with so huge a team. If I _could_ create an easy way of emulating on local machines and show others to do it I think it would be a major gain. However, if others are right and I fail I've wasted my time by thinking I was smarter then others, not to mention looked pretty incompetent on my first month on the job by getting nothing done except prooving what others told me. Is the gain of being able to run in debuggers and test locally worth the fighting for?


title: High-level strategy for distinguishing a regular string from invalid JSON (ie. JSON-like string detection)

text: **Disclaimer On Absence of Code:** I have no code to post because I haven't started writing; was looking for more theoretical guidance as I doubt I'll have trouble coding it but am pretty befuddled on what approach(es) would yield best results. I'm not _seeking_ any code, either, though; just direction. **Dilemma** I'm toying with adding a "magic method"-style feature to a UI I'm building for a client, and it would require intelligently detecting whether or not a string was meant to be JSON as against a simple string. I had considered these general ideas:   1. Look for a sort of arbitrarily-determined acceptable ratio of the frequency of JSON-like syntax (ie. regex to find strings separated by colons; look for colons between curly-braces, etc.) to the number of quote-encapsulated strings + `null`s, `bool`s and `int`s/`float`s. But the smaller the data set, the more fickle this would get   2. look for key identifiers like opening and closing curly braces... not sure if there even _are_ more easy identifiers, and this doesn't appeal anyway because it's so prescriptive about the kinds of mistakes it could find   3. try incrementally parsing chunks, as those between curly braces, and seeing what proportion of these fractional statements turn out to be valid JSON; this seems like it would suffer less than (1) from smaller datasets, but would probably be much more processing-intensive, and very susceptible to a missing or inverted brace Just curious if the computational folks or algorithm pros out there had any approaches in mind that my semantics-oriented brain might have missed. PS: It occurs to me that natural language processing, about which I am totally ignorant, might be a cool approach; but, _if_ NLP is a good strategy here, it sort of doesn't matter because I have zero experience with it and don't have time to learn & then implement/ this feature isn't worth it to the client.


title: License change of original source from Apache 2.0 to LGPL

text: About a year or so ago, I forked a project licensed under Apache 2.0 and made extensive changes and additions to the code, a good portion of which I contributed back freely to the community. Recently, the code moderator changed the licensing to LGPLv3, and I wanted to find out if I was correct in my belief that this licensing change does not apply to the code I checked out more than a year ago, specifically not forcing me to comply to LGPL and leaving me free to do as I wish under Apache 2.0 as long as I do not "taint" my fork with new code from the original project that was written under the new licensing scheme. Or am I mistaken?


title: Why don't compilers inline everything?

text: Sometimes compilers inline function calls. That means that they move the code of the called function into the calling function. This makes things slightly faster because there's no need to push and pop stuff on and off the call stack. So my question is, why don't compilers inline everything? I assume it would make the executable notably faster. The only reason I can think of is a significantly larger executable, but does it really matter these days with hundreds of GB of memory? Isn't the improved performance worth it? Is there any other reason why compilers don't just inline all function calls?


title: Are short abbreviated method/function names that don't use full words bad practice or a matter of style?

text: Is there nowadays any case for brevity over clarity with method names? Tonight I came across the Python method `repr()` which seems like a bad name for a method to me. It's not an English word. It apparently is an abbreviation of 'representation' and even if you can deduce that, it still doesn't tell you what the method does. A good method name is subjective to a certain degree, but I had assumed that modern best practices agreed that names should be at least full words and descriptive enough to reveal enough about the method that you would easily find one when looking for it. Method names made from words help let your code read like English. `repr()` seems to have no advantages as a name other than being short and IDE auto-complete makes this a non-issue. An additional reason given in an answer is that python names are brief so that you can do many things on one line. Surely the better way is to just extract the many things to their own function, and repeat until lines are not too long. Are these just a hangover from the unix way of doing things? Commands with names like `ls`, `rm`, `ps` and `du` (if you could call those names) were hard to find and hard to remember. I know that the everyday usage of commands such as these is different than methods in code so the matter of whether those are bad names is a different matter.


title: What is meant by a primitive data type?

text: My understanding of a primitive datatype is that > It is a datatype provided by a language implicitly (Others are user defined > classes) So different languages have different sets of datatypes which are considered primitive for that particular language. Is that right? And what is the difference between a "basic datatype" and "built-in datatype". Wikipedia says a primitive datatype is either of the two. **PS - Why is "string" type considered as a primitive type in SNOBOL4 and not in Java ?**


title: Is the popularity of Objective-C challenging C++?

text: According to TIOBE programming language popularity index for March 2012, Objective-C is now almost as popular as C++. I'm a bit astonished by this fact. I would have expected C++ to be still head and shoulders above Objective-C in popularity, or am I mistaken and the TIOBE popularity index seems correct? Or do the companies like Apple pay them to create hype around their products?


title: Question about a package in R

text: So I have this command ran to set up the exercise:               require('ggplot2')          load(url('http://www.stolaf.edu/people/olaf/cs125/hw8.RData'))       And it gives a new operator `draw()`, so when I run `draw(p0x,p0y)`, it gives me a sketch as a graph. My question is when I run `draw(p2x,p2y)`, it gives me 4 same sketches as a graph, only that the one on the upper right corner is shifted to the left. My job is to move that part of the drawing to the right, so that the four sketches are symmetrically placed. But the problem is I don't quite understand `p0x,p0y,p2x,p2y` and I don't know how to do it. I was told a single line can solve the problem.


title: Drawing controls and sub controls unaware of their location in parent

text: Applications and operating systems have a ton of windows and controls, sub windows and sub controls. I've noticed its common to have sub controls have their coordinate systems reset to start at 0 making drawing much easier. However I'm not sure how that is done and how I'd be able to do that. I'm going to be creating an application that does a lot of 2d drawing and includes things like my own implemented scrollbars and lots of controls that have sub controls. I want the coordinate system of sub controls to reset to 0 and I want the controls to have minimal knowledge of their location within parent controls, and parent parent controls, ect. The only thing I can think of is to pass in transform coordinates and have each sub control when drawing add the x and y transform coordinates to their objects being drawn so it gets transformed to the correct location. That quickly gets very tiring when I know there are better ways. I'm not sure what I'll be using, weather it will be GDI+, OpenGL, or Direct2D. I'm just looking for general information on how this done so sub controls can draw at x and y 0 and it pops up at whatever location the actual control is located at.


title: Names for generic classes - how to avoid naming them just "object"? Use synonyms?

text: When programming, I often end up naming some generic class (think of an abstract base class for stuff you manage in your project) something like `FooObject`, `FooComponent` or `FooItem` (where `Foo` is an abreviation of project name). The problem is, that these names are used so often, they become meaningless - I mean, when I'm talking about an "object", no-one knows whether I mean "a subclass of `FooObject`", or an ordinary object. I think that a good list of synonyms for "object", "component", "callback", "handler", "action" and so on would help, because we could just redefine these world on a per-project basis. You could even make up some totally nonsense word and define your meaning in documentation. I think it would be clearer than naming stuff "objects". Here's what I mean by "nonsense" (taken from Alice in Wonderland): > Twas brillig, and the slithy toves > > Did gyre and gimble in the wabe: > > All mimsy were the borogoves, > > And the mome raths outgrabe. Maybe you can have some nice words you use in such cases? How do you deal with similar situations in your projects? [ Related: How to avoid general names for abstract classes? ]


title: Do story points have a direct relation with task estimates?

text: In my current team, where we run multiple scrums, the Story points are usually based on the effort required to complete the User Story. For example if an User Story has 2 tasks, both needing 5 days each, they the Story is assigned 10 points. So 1 day of effort is considered to be one Story point. Is this practice a good one?


title: Is it a good practice to have Epics under User Stories?

text: In my current team there is a practice of putting Epics under User Stories and sometimes even User Stories or Epics under Tasks! When questioned, the usual reply is: **"if it is not a good practice then the project management tool would not have allowed doing so!"** (IBM Rational Team Concert, for one does not prevent such practice.) What do the experts here think about this?


title: Should you promise to deliver a feature that you aren't sure if its implementable?

text: In an article from HN, I came across the following advice: > Always tell your customer/user "yes", even if you're not sure. 90% of the > time, you'll find a way to do it. 10% of the time, you'll go back and > apologize. Small price to pay for major personal growth But I've always thought that one should do a feasibility analysis _before_ making any kind of promises to a customer/user, so that they aren't misled at any point. At what circumstances, then, should the above advice applicable?


title: Writing functional tests for a legacy project

text: I am trying to add a couple of tests to a legacy C project. The project basically consists of a command line tool that prints something to stdout every time an event happens. Now, since writing unit tests would be pretty hard given the fact that the modules are pretty tight coupled, I am trying to write some functional tests in order to validate the current behaviour and then I'll go on splitting the modules so I can unit test them. Does it make sense to have the testing framework something like a few Python scripts (keep in mind that the project is pure C) that handles all the functional tests? Basically, Python should call my command line tool, fake its input and expect a valid output.


title: Scheme vs Common Lisp: Which characteristics made a difference in your project?

text: There are no shortage of vague "Scheme vs Common Lisp" questions on both StackOverflow and on this site, so I want to make this one more focused. The question is for people who have coded in both languages: ### While coding in Scheme, what specific elements of your Common Lisp coding experience did you miss most? Or, inversely, while coding in Common Lisp, what did you miss from coding in Scheme? I don't necessarily mean just language features. The following are all valid things to miss, as far as the question is concerned:   * Specific libraries.    * Specific features of development environments like SLIME, DrRacket, etc.    * Features of particular implementations, like Gambit's ability to write blocks of C code directly into your Scheme source.    * And of course, language features.  Examples of the sort of answers I'm hoping for:   * "I was trying to implement X in Common Lisp, and if I had Scheme's first-class continuations, I totally would've just done Y, but instead I had to do Z, which was more of a pain."    * "Scripting the build process in my Scheme project got increasingly painful as my source tree grew and I linked in more and more C libraries. For my next project, I moved back to Common Lisp."    * "I have a large existing C++ codebase, and for me, being able to embed C++ calls directly in my Gambit Scheme code was totally worth any shortcomings that Scheme may have vs Common Lisp, even including lack of SWIG support."  So, I'm hoping for war stories, rather than general sentiments like "Scheme is a simpler language" etc.


title: share button in custom listview doesn't work

text: I'm following share a text with button in custom listview but it doesn't work . this is code for `OnClick` in `ListViewAdapter.java` :               OnClickListener clickListener = new OnClickListener() {                      @Override                 public void onClick(View v) {                     try{                         Context context = v.getContext();                         String ab = (String) holder.tvComment.getText();                         holder.tvComment.setText(ab);                              Toast.makeText(context, ab, Toast.LENGTH_LONG).show();                         Intent sendIntent = new Intent();                         sendIntent.setAction(Intent.ACTION_SEND);                              sendIntent.putExtra(Intent.EXTRA_TEXT, ab);                         sendIntent.setType("text/plain");                                   context.startActivity(sendIntent);                          }                     catch (Exception e){                     Log.w("Share Data", "Error!");                     }                      }             };                       holder.sharebtn.setOnClickListener(clickListener);


title: What is more efficient, a single square root or multiple divisions?

text: Say I make a program that calculates all possible (integral) factors of a certain number that has been input.   Is it theoretically more efficient to check with all integers up to the square root of the number or till half of the number.   Calculating the square root will take more time and power but will result in fewer divisions and vice-versa for the other option.


title: Is it important for a solution to be an efficient one?

text: I solve many problems, mostly from Top Coder. I will get answers for many, but most times I end up with an inefficient solution. In real-world implementations - does it really matter that a solution to the problem is efficient? If so how I can improve it?


title: Should an IT consultant charge for time spent on planning?

text: If you do consulting/freelancing as a software developer, should you charge your client on time spent on planning? By planning I mean long phone calls, on-site meetings, etc.


title: How to sync calendars events programmatically?

text: I'd like to hear some ideas how to sync calendar events. Say I have two calendars having fields (id, title, start, end, updated, location and description). I'm struggling with starting point. Its easy if all events are new and not overlapping with each other. But say I already have events on calendars, some are supposedly same events, some are separate events, some maybe same events, but their attributes have changed, like location, title, start and end time. How would you actually make sync between calendars with reasonable smart functionality?


title: What's the best way to inject science into everyday programming?

text: I work better when I have some firm foundations. This helps me to solve everyday problems better, because I can generalize them. The thing I find in programming is so many things are black boxes. Logic is scientific, but commands are not. A command in a language is just "something that does something". It is very hard to work out what its logic is, without understanding the underlying hardware. I learned brainfuck for a little bit, and enjoyed it very much, but it still has commands. These commands are packages of functionality that cannot really be understood without understanding all the lower levels of logic, unfortunately. What I would like to know is if there are any mathematical or logic principles that help with being able to generalise programming problems?


title: "Mentor" a senior programmer or colleague without insulting

text: I don't have great social skills. Like many programmers I know, social skills are something that is worked on and developed over time because it's not a natural and 'inborn' trait. When a computer is doing something wrong, you can tell it so and 'fix' it so it'll work correctly the next time. It won't complain. It won't feel insulted. In fact, I tend to think it's 'happier' because it's not grinding away in a dead end. * * * I find it much trickier to work with other programmers at or above my level in a way that enables them to do better work faster without appearing condescending, insulting, or the group's "know-it-all." I know some programmer's look at this objectively and simply say, "Since it's for the good of the group I will inform them, and if they are insulted that's their problem." This isn't a bad method - all the programmers I have ever worked with take and act on criticism appropriately. It's when they're having a bad day/week/month/year/life that I find it difficult to approach them without a reactive emotional response. I genuinely enjoy working with those around me, though, and don't want to develop bad blood.   * **What skills, techniques, and even outside of work activities do you engage in that enable you to be a support and resource without the tension that can be created in these situations?**   * Or, in other words, how do you mentor someone without appearing to mentor them? I suppose the question could/should be reversed as well - how do you keep yourself 'open' and learning such that you don't scare off people that have useful information for you? How do you keep on top of skills so that the latest college grad isn't necessarily better than you in terms of design patterns, technology, workflow, etc?


title: Data Quality in Relational Database Regression Tests

text: I have been working on an open source Museum Collections Management web application that is to be used to keep track of a museum's accessioned, donated, loaned or otherwise acquired artefacts. This involved designing and creating a rather large database (in relation to my previous experiences), which stores all kinds of varying information (artefact information, changing location information, personal contact information, pictures, etc), that needs to be flexible and easily extendible. I am just finishing my university degree and I am not a professional when it comes to database design and so I am really wanting to create a thorough test suite to ensure that what I have in place "works". I have read up on database testing and have come across a few articles that mention Regression Testing in regards to databases but I do not fully understand what this all involves. From reading this article at Dr.Dobbs I understand that one sort of testing that I will need to do is validate that the logic in the database is correct. So I would create tests that insert certain data into the database and then follow it up with a query to ensure that I get the correct data back from the database (ensuring that all the appropriate triggers or views are working). The confusion comes in with the mention of testing for "Data Quality". In the article above the author makes mention that you want to validate the following with tests:   * Column domain value rules   * Column default value rules   * Value existence rules   * Row value rules   * Size rules What types of tests would this involve and how would they be implemented? Also this is my first time writing a test suite for a database, are there any good guidelines on how/where to begin or any processes that I could follow to guide my test development?


title: Why are part-time jobs in programming an anomaly?

text: I've recently quit my full time developing job at mega-corp, and I decided that I'll look for a part time job. Since then I've talked to half a dozen potential employers, and every one of them had the same reaction when I said the magic words "part-time" - they all closed up and became suspicious. Now, I understand that it might just be me, so as control I asked every one of them what if I were willing to work full time, and they all said I would probably get an offer. My question is two fold:   1. Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?   2. How do I sell the story of part time job better? I usually just list my reasons which are that I prefer that balance currently in my life and that I want to work on my own projects, but it leaves them even more suspicious - am I going to start something myself and quit? Am I just lazy?


title: Doubts about several best practices for rest api + service layer

text: I'm going to be starting a project soon that exposes a restful api for business intelligence. It may not be limited to a restful api, so I plan to delegate requests to a service layer that then coordinates multiple domain objects (each of which have business logic local to the object). The api will likely have many calls as it is a long-term project. While thinking about the design, I recalled a few best practices. 1) Use command objects at the controller layer (I'm using Spring MVC). 2) Use DTOs at the service layer. 3) Validate in both the controller and service layer, though for different reasons. I have my doubts about these recommendations. 1) Using command objects adds a lot of extra single-purpose classes (potentially one per request). What exactly is the benefit? Annotation based validation can be done using this approach, sure. What if I have two requests that take the same parameters, but have different validation requirements? I would have to have two different classes with exactly the same members but different annotations? Bleh. 2) I have heard that using DTOs is preferable to parameters because it makes for more maintainable code down the road (say, e.g., requirements change and the service parameters need to be altered). I don't quite understand this. Shouldn't an api be more-or-less set in stone? I would understand that in the early phases of a project (or, especially, an entire company) the domain itself will not be well understood, and thus core domain objects may change along with the apis that manipulate these objects. At this point however the number of api methods should be small and their dependents few, so changes to the methods could easily be tolerated from a maintainability standpoint. In a large api with many methods and a substantial domain model, I would think having a DTO for potentially each domain object would become unwieldy. Am I misunderstanding something here? 3) I see validation in the controller and service layer as redundant in most cases. Why would I validate that parameters are not null and are in general well formed in the controller if the service is going to do exactly the same (and more). Couldn't I just do all the validation in the service and throw a runtime exception with a list of bad parameters then catch that in the controller to make the error messages more presentable? Better yet, couldn't I just make the error messages user-friendly in the service and let the exception trickle up to a global handler (ControllerAdvice in spring, for example)? Is there something wrong with either of these approaches? (I do see a use case for controller validation if the input does not map one-to-one with the service input, but since the controllers are for a rest api and not forms, the api parameters will probably map directly to service parameters.) I do also have a question about unchecked vs checked exceptions. Namely, I'm not really sure why I'd ever want to use a checked exception. Every time I have seen them used they just get wrapped into general exceptions (DomainException, SystemException, ApplicationException, w/e) to reduce the signature length of methods, or devs catch Exception rather than dealing with the App1Exception, App2Exception, Sys1Exception, Sys2Exception. I don't see how either of these practices is very useful. Why not just use unchecked exceptions always and catch the ones you actually do care about? You could just document what unchecked exceptions the method throws.


title: In which object should I implement wait()/notify()?

text: I'm working in an Android project with multithreading. Basically I have to wait to the server to respond before sending more data. The data sending task is delimited by the flag `boolean hasServerResponded` so the `Thread` will loop infinitely without doing anything until the flag becomes `true`. Since this `boolean` isn't declared as `volatile` (yet), and also looping without doing anything wastes resources, I thought maybe I should use `AtomicBoolean` and also implement `wait() / notify()` mechanism. Should I use the `AtomicBoolean` object `notify()` and `wait()` methods or should I create a lock `Object`?


title: Unit testing statically typed functional code

text: I wanted to ask you people, in which cases it makes sense to unit test statically typed functional code, as written in haskell, scala, ocaml, nemerle, f# or haXe (the last is what I am really interested in, but I wanted to tap into the knowledge of the bigger communities). I ask this because from my understanding:   * One aspect of unit tests is to have the specs in runnable form. However when employing a declarative style, that directly maps the formalized specs to language semantics, is it even actually _possible_ to express the specs in runnable form in a separate way, that adds value?   * The more obvious aspect of unit tests is to track down errors that cannot be revealed through static analysis. Given that type safe functional code is a good tool to code extremely close to what your static analyzer understands, it would seem that you can shift a lot of safety towards static analysis. However a simple mistake like using `x` instead of `y` (both being coordinates) in your code cannot be covered. OTOH such a mistake could also arise while writing the test code, so I am not sure whether it is worth the effort.   * Unit tests do introduce redundancy, which means that when requirements change, the code implementing them and the tests covering this code must both be changed. This overhead of course is about constant, so one could argue, that it doesn't really matter. In fact, in languages like Ruby it really doesn't compared to the benefits, but given how statically typed functional programming covers a lot of the ground unit tests are intended for, it feels like it's a constant overhead one can simply reduce without penalty. From this I'd deduce that unit tests are somewhat obsolete in this programming style. Of course such a claim can only lead to religious wars, so let me boil this down to a simple question: When you use such a programming style, to which extents do you use unit tests and why (what quality is it you hope to gain for your code)? Or the other way round: do you have criteria by which you can qualify a unit of statically typed functional code as _covered_ by the static analyzer and hence without need for unit test coverage?


title: What does it mean by atomic commit for a versioning system?

text: One of the reasons why programmers prefer SVN over CVS is the former allows atomic commits ? What does this mean ?


title: Plug-in based software design

text: I'm a software developer who is willing to improve his software design skills. I think software should not only work but have a solid and elegant design too to be reusable and extensive to later purposes. Now I'm in search of some help figuring out good practices for specific problems. Actually, I'm trying to find out how to design a piece of software that would be extensible via plug-ins. The questions I have are the following:   * Should plug-ins be able to access each others functionality? This would bring dependencies I guess.   * What should the main application offer to the plug-ins if I want to let's say develop a multimedia software which would play videos and music but which could later on get functionality added over plug-ins that would let's say be able to read video status (time, bps, ...) and display it. Would this mean that the player itself would have to be part of the main program and offer services to plug-ins to get such information or would there be a way to develop the player as a plug-in also but offer in some way the possibility to other plug-ins to interact with it? As you see, my questions are mainly for learning purposes as I strive to improve my software development skills. I hope to find help here and apologize if something is wrong with my question.


title: Fork dead SVN based project on GitHub

text: I previously asked this at stack overflow but it was closed, I believe because 'programmers' is a more appropriate venue for this question. I have done some work on the SVN Importer project (Apache license), which appears to be effectively dead (no published changes in 5 years). I have a login to their svn server but do not have commit rights. At any rate, I'd like to convert this project to Git and push my own changes to GitHub. The GitHub site suggests the svn2git tool for converting svn projects to Git, so I was planning to convert the SVN repository to Git, add my changes, and then push this Git repository to GitHub. I'm wondering, what are the legal requirements and common conventions of this process? Is it acceptable to clone the entire history of the project and move it to GitHub? Also, even though this is essentially a dead project, once I've translated the repository to Git should I put all of my commits onto a non master branch or is it acceptable to use master in this case?


title: How common is it to submit papers to journals or conferences outside of academia?

text: I worked in academia a few years, but more on the D-side of R&D. The race for papers never appealed to me and I'm a practical not theoretical type, but I do like reading papers on certain topics (e.g. Google Papers, NLP, FB papers, ...) a lot. How common is it that normally working developers submit papers to conferences or even journals? It seems to be somewhat common in certain companies (it's not common or encouraged in mine). Do journals or conferences even take papers by an academic nobody (BSc) under consideration? I ask, because I have a few rough ideas and I would just like to bring them into _form_ , one way or the other. Bonus question: Is there a list of CS (in the widest sense) conferences/journals with short descriptions? * * * PS (Four out of five researchers I met published quite some fluffy stuff for my taste. I am no expert, but those people told me sometimes themselves, that the implementation does not matter, just the idea and the presentation. I always wondered about that. I probably could write about ideas all day long (not instantly but with a bit of preparation), but the implementation and the practical part is the _really hard part_ , that academia just does not like to be concerned with. Also many papers actually scream: _I was written so the publication list of my author gets longer_ \- which is a waste of time for _everyone_ , and often a waste of tax money, too. When I think of CS-ish papers, I think of running implementations or actual data, like e.g. Google's Map Reduce, Serving Large-scale Batch Computed Data with Project Voldemort or the like.)


title: Support for non-english characters?

text: Is support for non-english characters common in programming languages? I mean, technically, I would think it is feasable, but I don't have any experience in anything other than english, so I don't know how common it is. I know that there are non-english based programming languages, but can something like C#, C++, C, Java, or Python support non-english classes/methods/variables? Example in go (url, http://play.golang.org/p/wRYCNVdbjC)               package main          import "fmt"          type 世界 struct {         世界 string     }          func main() {         fmt.Println("Hello, 世界")         世界 := new(世界)         世界.世界 = "hello world"         fmt.Println(世界.世界)     }


title: Relevance of Metro to ASP.Net developer?

text: I am a web developer, working mostly with ASP.Net(webforms + MVC), C#, javascript and so on. As you know, continuous learning is very important for us, but time is not infinite. I do dabble with the odd technology every now and then that has nothing to do with web but mostly I try to learn more about my field in order to became better at my job. I have the opportunity to attend either a ASP.Net MVC short course or a Metro app short course and not sure which to pick. On the one hand I feel like I would already know 75% of the MVC course material so would not get as much out of it as with the Metro course. but on the other hand I ask myself how useful is a metro course going to be in my future of being a web developer. I could always dabble in it again when I have the time? So my real question is, is there any real benefit to a web developer using his time to learn Metro specifically, instead of something else like knockout.js or some other tec that could actually be of use to me in my daily work life? Thanks


title: Why is using named routes for generating outbound URLs a violation of Separation of Concerns?

text: What is separation of concerns? > In computer science, separation of concerns (SoC) is the process of breaking > a computer program into distinct features that overlap in functionality as > little as possible. A concern is any piece of interest or focus in a > program. Typically, concerns are synonymous with features or behaviors. > Progress towards SoC is traditionally achieved through modularity and > encapsulation, with the help of information hiding. From _Pro Asp.Net MVC 4_ book ( page 375 ): > The problem with relying on route names to generate outgoing URLs ( > @Html.RouteLink("Click me", "MyOtherRoute","Index", "Customer") is that > doing so breaks through the separation of concerns that is so central to the > MVC design pattern. When generating a link or a URL in a view or action > method, we want to focus on the action and controller that the user will be > directed to, not the format of the URL that will be used. By bringing > knowledge of the different routes into the views or controllers, we are > creating dependencies that we would prefer to avoid. a) I understand that we create a _dependency_ ( between _action method/view_ and a _routing configuration module_ ) by having `Html.RouteLink` ( called within _action method_ or _view_ ) specifying the name of the _route_ we want to use. But is introducing such a _dependency_ already considered a _violation of SoC_? Namely, even though we created a _dependency_ between the _two modules_ , we haven't actually introduced any additional _functionality/concern_ into either of the modules ( the definition of **SoC** implies that _violation of SoC_ occurs when _new functionality/concern_ is introduced into a _module_ ) b) Anyhow, I don't understand how will simply generating an URL ( within _action method/view_ ) by specifying a _named route_ bring focus to the _format of the URL_? Thank you


title: Creating an account to receive sensitive information on a mobile device

text: I am developing an Android application for my final year project which allows the holder of a mobile device to receive a text notification containing potentially sensitive information from a server. My question is this, if a User downloads the application, what is a suitable way for them to create an account / log in on my server to receive notifications from it? I was thinking: **Application**   * Open application   * Click Register   * Fill out fields (Name / Address / ID / Phone no.)   * Send to server   * Display "Account Pending"   * If approved, send positive message, begin receiving notifications from server.   * If denied, send negative message, if User tries to log in with that account, the App will inform them that it was rejected. **Server**   * Add received information to a "Pending Account"   * When an Admin comes online, they can review the information (How can they be sure the person is who they say they are?)   * If the account is approved, the details are moved to a normal User account, otherwise moved to rejected accounts. I can't think of another solution which would fit this problem. If anybody knows of a patterns or design I appropriate to hear from you.


title: What is a Developer in Test?

text: I was recently talking with a recruiter who wants to put me at a company for a position of Developer in Test. He essentially made it sound like a position where you get to fiddle with new programming techniques and test bugs and improvements in software but where you don't need to worry about standard deadlines. You get to be very creative in your work. But that description was still kinda vague to me. I have been a Web Developer for a number of years now, mostly working in PHP. So I wanted to know if others in the community know more about what these positions typically entail. I know that this might not be a subject appropriate for this forum, but it was the best fit I could find among Stack Exchange and I would really appreciate it if this wasn't closed since there is really no where else here to ask about it. I have tried Googling it, but there isn't a lot of information out there. So what exactly is a Developer in Test?


title: How do I create a web service with high amounts of traffic that works effectively with lots of different users?

text: I have created web services before that are used by a small number of users but have a new project that would have lots of users. For each user that uses the services, this is what they would do: 1) Call a method on the web service that calculates a "price" based on parameters passed by the user. 2) The actual method and algorithm for calculating and returning a "price" is not very complicated and runtime would be very quick, although a look up in a database table would be necessary for each call. 3) The problem is that this method could be called over and over again for each item that needs a price, and if lots of users are using the web service (I don't know an exact number, lets say 1,000 users, 10,000 users, whatever), I don't know what different things I need to think about in terms of how to manage high traffic, many different users trying to use the method at the same time over and over again, pulling data from a table over and over again. So pretty much I would like some advice from someone who has experience with web services with high amounts of traffic and many different users, with the method pulling from a data base table over and over again, to explain to me steps/thing I need to think about when designing the service to avoid traffic congestion, at what point a certain number of users would start slowing the service down,or just things to think/worry about, etc. Appreciate any help, thanks!


title: Licensing: Derivative work and copyright notice

text: I am currently creating something that has been inspired by another library. It is a complete rewrite on another platform - yet, has the same purpose and functionality and is written in the same language. As far as I understand it, this is still considered a derivative work. The original piece is licensed under the Apache 2.0 license. Which steps do I need to take now when publishing my source under the Apache 2.0 license? Do I have to maintain copyright notices? If so, it can't obviously be in the source files (which are all new and cannot be mapped to the original piece). What do I have to do to be on the safe side? What do I have to include when I distribute the sources?


title: Diff annotation tool

text: Among the 11 proven practices for more effective, efficient peer code review, diff annotation seems to be the one particularly well suited to tool assistance. The article is written by the architect of SmartBear's CodeCollaborator, so he of course recommends using that. Does anyone know of any alternatives? I can't think of anything that would be even close to paper+pen+marker in pure developer efficiency when it comes to explaining a piece of code.


title: Am I allowed to rename a package for a library under Apache V2?

text: I have developed a library at my former employer. After my employment ended, I got to take the library with me. Does the Apache v2 prohibit renaming packages as long as I keep the license header intact?


title: listview malfunctioning with v1 of Mobile framework odoo for Android

text: In the list view there is textview, button and edittext in the single list item. And all the items are getting generated dynamically sometimes 3 sometimes 7 sometimes 14 ... If I put values in those edittext ... I am able to et values of 6 or less edittext ... In the device Genymotion with 4.7" with visible item on screen are 6 and 7th partial... While in the 10" genymotin, the visible items are 9 How to get values from the all the edittext from this dynamic listview? .....               public class DeliveryDetailFinal extends BaseFragment {              Integer mPickingId = null;         Integer mLineSize = null;         LinkedHashMap<String, String> productData = new LinkedHashMap<String, String>();         List<Object> moveLinesfinalData;         View mDOViewFinal = null;         ListView mMoveLinesFinalListDo = null;         Context mDBContextDDF = null;         List<OEDataRow> moveLinesData;              @Override         public View onCreateView(LayoutInflater inflater, ViewGroup container,                                  Bundle savedInstanceState) {             setHasOptionsMenu(true);             mDOViewFinal = inflater.inflate(R.layout.fragment_delivery_order_detail_final_view,                     container, false);             Bundle bundle = getArguments();             if (bundle != null) {                 mLineSize = bundle.getInt("lineSize");             }             init();             mDODHelper = db().getOEInstance();             mDBContextDDF = (Context) getActivity();             return mDOViewFinal;         }              private void init(){                 initControls();         }              private void initControls(){             moveLinesData = mDeliveryOrderData.getO2MRecord("move_lines").browseEach();             mMoveLinesFinalListDo = (ListView) mDOViewFinal.findViewById(R.id.DOMoveLinesFinal);             moveLinesfinalData = new ArrayList<Object>();             moveLinesfinalData.addAll(moveLinesData);             OEListAdapter listAdapter = new OEListAdapter(mDBContextDDF, R.layout.fragment_final_details_view, moveLinesfinalData){                 @Override                   public View getView(int position, View convertView, ViewGroup parent) {                       View mView = convertView;                       if (mView == null)                           mView = getActivity().getLayoutInflater().inflate(                                   getResource(), parent, false);                       mView = createListViewRow(mView, position, moveLinesfinalData);                        mView.setVisibility(1);                       return mView;                   }             };             mMoveLinesAdapterfinal = listAdapter;             Log.d("final", "final  mMoveLinesAdapterfinal "+mMoveLinesAdapterfinal);             mMoveLinesFinalListDo.setAdapter(mMoveLinesAdapterfinal);         }              public View createListViewRow(View mView, int position,                 List<Object> moveLinesObjectData) {                 final OEDataRow row = (OEDataRow) moveLinesObjectData.get(position);             TextView eProductName = (TextView) mView.findViewById(R.id.textViewProductNameFinal);             eProductName.setText(row.getString("name").toString());             LinearLayout innerLinearLayout = (LinearLayout) mView.findViewById(R.id.innerLinearLayout);             EditText editTextProductId = (EditText) innerLinearLayout.findViewById(R.id.editTextProductId);             if(row != null)                 editTextProductId.setText(row.getInt("id").toString());                  EditText eProductSerial = (EditText) innerLinearLayout.findViewById(R.id.editTextProductSerialFinal);                  String id = editTextProductId.getText().toString();             String serialNumber = ((EditText) eProductSerial).getText().toString();             productData.put(id,serialNumber);                  Log.d("final", "final productData before "+productData);             eProductSerial.setOnFocusChangeListener(new View.OnFocusChangeListener() {                 public void onFocusChange(View v, boolean hasFocus) {                    if (!hasFocus)                     {                         LinearLayout parentLayout = (LinearLayout) v.getParent();                         if(parentLayout != null) {                             EditText editTextProductIdFocus = (EditText) parentLayout.findViewById(R.id.editTextProductId);                             String id = editTextProductIdFocus.getText().toString();                             String serialNumber = ((EditText) v).getText().toString();                             productData.put(id,serialNumber);                         }                     }                 }             });                 final Button BarCode = (Button) innerLinearLayout.findViewById(R.id.buttonBarcode);                 BarCode.setOnClickListener(new OnClickListener() {                     @Override                     public void onClick(View v) {                         v.getId();                     }                 });             return mView;         }              @Override         public Object databaseHelper(Context context) {             return new StockPickingDB(context);         }          }      ..... > fragment_delivery_order_detail_final_view.xml               <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_marginTop="55dp"         android:orientation="vertical" >              <ListView             android:id="@+id/DOMoveLinesFinal"             android:layout_width="match_parent"             android:layout_height="match_parent" >         </ListView>     </LinearLayout>      > fragment_final_details_view.xml               <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"         android:id="@+id/topLayoutID"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_margin="3dp"         android:orientation="vertical"         android:padding="2dp"         android:visibility="visible" >                      <TextView                     android:id="@+id/textViewProductNameFinal"                     android:layout_width="match_parent"                     android:layout_height="wrap_content"                     android:layout_marginEnd="3dp"                     android:layout_marginRight="3dp"                     android:layout_marginLeft="3dp"                     android:layout_marginStart="3dp"                     android:text="@string/product"                     android:textAppearance="?android:attr/textAppearanceSmall"                     android:visibility="visible">                     <requestFocus />                 </TextView>                  <LinearLayout                 android:id="@+id/innerLinearLayout"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:padding="1dp"                 android:layout_margin="1dp"                 android:orientation="horizontal"                 android:visibility="visible">                      <Button                     android:id="@+id/buttonBarcode"                     style="?android:attr/buttonStyleSmall"                     android:layout_width="wrap_content"                     android:layout_height="wrap_content"                     android:background="@drawable/barcode"                     android:visibility="visible" />                      <EditText                         android:id="@+id/editTextProductId"                         android:layout_width="match_parent"                         android:layout_height="wrap_content"                         android:hint="@string/serial_no"                         android:visibility="gone">                 </EditText>                      <EditText                     android:id="@+id/editTextProductSerialFinal"                     android:layout_width="match_parent"                     android:layout_height="wrap_content"                     android:hint="@string/serial_no"                     android:visibility="visible">                 </EditText>         </LinearLayout>          </LinearLayout>      please help me ... Thanks in advance ...


title: What does this function do?

text: Does this function means its calculating x=(x-1) + x^2?               Function unknown(x)       if ( x == 1 )         return 1       else         return unknown(x‐1) + x*x


title: SQL Dev and Prod Environments

text: I have been tasked with setting up a SQL Development environment, and i was wondering if anyone has any advice on getting this right? So far, I have restored the prod DB onto another box, and changed all our SSIS packages to use XML configuration files so we can deploy them to either environment without changing the DB connection setting. My plan was to restore the prod DB over the dev DB every 2 weeks (assuming its agreed by all the other developers). Also, i was thinking i would have a UAT DB restored every 1 or 2 weeks to test deploying the changes to prod. The UAT DB would only exist for a day or 2 to test things, and then the actual deployment would happen into the prod environment. Can anyone thnk of anything else that would be good to do, or has any advice on other considerations etc?


title: Notation/Meta Language To Express An Algorithm

text: I need to learn a notational language, so I can express and possibly prove the correctness of what I believe to be a complicated algorithm that distributes a credit adjustment across multiple water bills in issue date descending order. But I cannot tell what that notational language should be. Each bill has three consumption tiers, 1-30, 31-60, and over 60. Each tier is associated with a different water and sewer rate. The higher the tier, the higher is the rate. Two water bills each have 100ccf consumption, which means each bill is billed like this. That is it's distribution across tiers 1, 2, and 3 is tier1 = -30, tier2 = -30, and tier3 = -40. In case it is not obvious, billing takes place from lowest to highest tier, so crediting takes place from highest to lowest tier. If I apply a -170 consumption credit, the first bill consumes -100ccfs. It is the remaining -70 ccf credit to be applied to the second bill that gets crazy. -40 of it has to be credited at tier3 and the remaining -30 at tier2. Nothing is left over for tier1 (second bill). I know this is absolutely correct distribution, because I've consulted the oracles in our municipality. They know what they're talking about. With -70 left (held in one variable) and the second bill's original consumption (held in a separate variable), I subtract the value of the sum of tier1's and tier2's cutoffs (60ccf) from 100ccf (the consumption when the bill was issued). I want to prove why that is right. I'm not content to say "Hey, I fooled around until I got a nice answer." Any ideas or help would be appreciated.


title: Why does C use the asterisk for pointers?

text: I'm just now learning about C. I find it odd that the creators chose the asterisk (`*`) as the symbol for pointers rather than a symbol that actually _looks_ like a pointer (`->`). Considering how confusing dereferencing and function pointers can be, is there a historical --or even practical-- reason for using the asterisk?


title: Best practices for implementing MVVM and MVC in delphi Pascal

text: I'm a Delphi pascal programmer, I use the latest Embarcadero delphi XE, and I would like to take advantage of design patterns such as Model view controller and model view view-model. However, there doesn't seem to be much on the web about the best practices for doing this in pascal. Most of the examples that I can find are in C# and some of the language features are not present in pascal, which means I may have to find ways to implement those features. I'm trying to adapt code from this article here I'll list the issues that I'm facing   * **Nullable types** Pascal does not have nullable types as C# does so I have created my own.               TNullable<T> = record         strict private           fHasValue : boolean;           fValue : T;           function GetValue:T;           procedure SetValue(newValue : T);         public           property HasValue : boolean read fHasValue;           property Value : T read GetValue write SetValue;           procedure SetToNull;         end;      in the implementation section               function TNullable<T>.GetValue:T;     begin         if fHasValue then         begin             Result := fValue;         end         else raise Exception.Create('Value Not Set');     end;          procedure TNullable<T>.SetValue(newValue : T);     begin         fValue := newValue;         fHasValue := true;     end;          procedure TNullable<T>.SetToNull;     begin         fHasValue := false;     end;        * **Get/Set for properties** Now that I have a nullable type I can create nullable properties However it comes with some code smells for example if i create                   TFoo = class           private             function GetBar:TNullable<Integer>;             procedure SetBar(x:TNullable<Integer>);           public              property Bar : TNullable<Integer> read GetBar write SetBar;      in the implementation section               function TFoo.GetBar:TNullable<Integer>;     begin         if **valueExists** then         begin             Result.Value := **the value**         end else         begin             Result.SetToNull;         end;     end;          procedure TFoo.SetBar(x:TNullable<Integer>);     begin         if X.hasValue then         begin             //Store/show value here         end else         begin             //handle null assignment here         end;     end;      This is fine but when it comes to use these properties I can't just use myFoo.Bar.Value := 1; I have to use               var          myBar : TNullable<Integer>;     begin         myBar.Value := 1;         myFoo.Bar := myBar;     end;      Which is a bit messier. I suppose there may be nothing I can do about this.   * **Circular References** I like to separate classes into different units. ie: ![structure](http://i.stack.imgur.com/XD75V.png) keeping the user interface separate from the control logic and the model and data logic layer. I can have a situation where 2 classes can reference each other. While this is a situation that for the most part I would like to avoid, there are occasions where this is needed. for example               unit u_A;          interface          uses       u_B       ;          type        TA = class         public            Foo : TB;       end;          implementation          end;      and another unit               unit u_B;          interface          uses       u_A       ;          type        TB = class         public            Foo : TA;       end;          implementation          end;      This code is broken because the two classes include each other and this can not be done in pascal. This is not such a problem in C#. Solutions that I can think of: 1. include both classes in the same unit, although this is a problem if I do not think this suits the design. 2. Create another parent interface for B and inherit B from that, then this gets around it. Although this is messy for such a simple task.   * **Static classes** There aren't any static classes in Delphi, these are useful for control classes.   * **Best Container classes to use in Delphi** I'm currently using TList and TObjectList in Generics.Collections They were introduced in Delphi XE I hope these are the best to use since delphi 7 didn't seem to have any good options. I'm still thinking about event handlers and any issues that may arise there. Perhaps there are some other issues that I have not thought of yet. Thanks for any advice.


title: Is this a decent use-case for goto in C?

text: I really hesitate to ask this, because I don't want to "solicit debate, arguments, polling, or extended discussion" but I'm new to C and want to gain more insight into common patterns used in the language. I recently heard some distaste for the `goto` command, but I've also recently found a decent use-case for it. Code like this:               error = function_that_could_fail_1();     if (!error) {         error = function_that_could_fail_2();         if (!error) {             error = function_that_could_fail_3();             ...to the n-th tab level!         } else {             // deal with error, clean up, and return error code         }     } else {         // deal with error, clean up, and return error code     }      If the clean-up part is all very similar, could be written a little prettier (my opinion?) like this:               error = function_that_could_fail_1();     if(error) {         goto cleanup;     }     error = function_that_could_fail_2();     if(error) {         goto cleanup;     }     error = function_that_could_fail_3();     if(error) {         goto cleanup;     }     ...     cleanup:     // deal with error if it exists, clean up     // return error code      Is this a common or acceptable use-case of `goto` in C? Is there a different/better way to do this?


title: Were you able to implement design patterns in tight deadlines?

text: I am wondering, in tight deadlines, who has time to implement design patterns? It is a lot more work and programming overhead to get it right the first time and within time frame. I know that it has long term advantages, but were you able to implement any design pattern correctly when the client is sitting on your head and pressure is growing. I think once your first version is released and you have plenty of time for the next release, than you can think of improving code quality and manageability with design patterns.


title: Why disallow int-to-short assignment but allow multiplication and other math?

text: In Java, the following code does not compile:               int val = 1;     short shortVal = val;  // Incompatible types      Anyone know why Java chooses to complain about this assignment, instead of simply truncating, when an integer × integer is also likely to overflow? To illustrate:               int val = 46340;     int result = val * val;                    // 2147395600     System.out.println(result);     int overflowVal = 46341;     int result2 = overflowVal * overflowVal;   // -2147479015     System.out.println("Quietly overflowed: " + result2);


title: Win32 and Win64 programming in C sources?

text: I'm learning OpenGL with C and that makes me include the `windows.h` file in my project. I'd like to look at some more specific windows functions and I wonder if you can cite some good sources for learning the basics of Win32 and Win64 programming in C (or C++). I use MS Visual C++ and I prefer to stick with C even though much of the Windows API seems to be C++. I'd like my program to be portable and using some platform-indepedent graphics library like OpenGL I could make my program portable with some slight changes for window management. Could you direct me with some pointers to books or www links where I can find more info? I've already studied the OpenGL red book and the C programming language, what I'm looking for is the platform-dependent stuff and how to handle that since I run both Linux and Windows where I find the development environment Visual Studio is pretty good but the debugger gdb is not available on windows so it's a trade off which environment i'll choose in the end - Linux with gcc or Windows with MSVC. Here is the program that draws a graphics primitive with some use of windows.h This program is also runnable on Linux without changing the code that actually draws the graphics primitive:               #include <windows.h>     #include <gl/gl.h>          LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);     void EnableOpenGL(HWND hwnd, HDC*, HGLRC*);     void DisableOpenGL(HWND, HDC, HGLRC);               int WINAPI WinMain(HINSTANCE hInstance,                        HINSTANCE hPrevInstance,                        LPSTR lpCmdLine,                        int nCmdShow)     {         WNDCLASSEX wcex;         HWND hwnd;         HDC hDC;         HGLRC hRC;         MSG msg;         BOOL bQuit = FALSE;         float theta = 0.0f;              /* register window class */         wcex.cbSize = sizeof(WNDCLASSEX);         wcex.style = CS_OWNDC;         wcex.lpfnWndProc = WindowProc;         wcex.cbClsExtra = 0;         wcex.cbWndExtra = 0;         wcex.hInstance = hInstance;         wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);         wcex.hCursor = LoadCursor(NULL, IDC_ARROW);         wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);         wcex.lpszMenuName = NULL;         wcex.lpszClassName = "GLSample";         wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);;                   if (!RegisterClassEx(&wcex))             return 0;              /* create main window */         hwnd = CreateWindowEx(0,                               "GLSample",                               "OpenGL Sample",                               WS_OVERLAPPEDWINDOW,                               CW_USEDEFAULT,                               CW_USEDEFAULT,                               256,                               256,                               NULL,                               NULL,                               hInstance,                               NULL);              ShowWindow(hwnd, nCmdShow);              /* enable OpenGL for the window */         EnableOpenGL(hwnd, &hDC, &hRC);              /* program main loop */         while (!bQuit)         {             /* check for messages */             if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))             {                 /* handle or dispatch messages */                 if (msg.message == WM_QUIT)                 {                     bQuit = TRUE;                 }                 else                 {                     TranslateMessage(&msg);                     DispatchMessage(&msg);                 }             }             else             {                 /* OpenGL animation code goes here */                      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);                 glClear(GL_COLOR_BUFFER_BIT);                      glPushMatrix();                 glRotatef(theta, 0.0f, 0.0f, 1.0f);                      glBegin(GL_TRIANGLES);                          glColor3f(1.0f, 0.0f, 0.0f);   glVertex2f(0.0f,   1.0f);                     glColor3f(0.0f, 1.0f, 0.0f);   glVertex2f(0.87f,  -0.5f);                     glColor3f(0.0f, 0.0f, 1.0f);   glVertex2f(-0.87f, -0.5f);                      glEnd();                      glPopMatrix();                      SwapBuffers(hDC);                      theta += 1.0f;                 Sleep (1);             }         }              /* shutdown OpenGL */         DisableOpenGL(hwnd, hDC, hRC);              /* destroy the window explicitly */         DestroyWindow(hwnd);              return msg.wParam;     }          LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)     {         switch (uMsg)         {             case WM_CLOSE:                 PostQuitMessage(0);             break;                  case WM_DESTROY:                 return 0;                  case WM_KEYDOWN:             {                 switch (wParam)                 {                     case VK_ESCAPE:                         PostQuitMessage(0);                     break;                 }             }             break;                  default:                 return DefWindowProc(hwnd, uMsg, wParam, lParam);         }              return 0;     }          void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)     {         PIXELFORMATDESCRIPTOR pfd;              int iFormat;              /* get the device context (DC) */         *hDC = GetDC(hwnd);              /* set the pixel format for the DC */         ZeroMemory(&pfd, sizeof(pfd));              pfd.nSize = sizeof(pfd);         pfd.nVersion = 1;         pfd.dwFlags = PFD_DRAW_TO_WINDOW |                       PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;         pfd.iPixelType = PFD_TYPE_RGBA;         pfd.cColorBits = 24;         pfd.cDepthBits = 16;         pfd.iLayerType = PFD_MAIN_PLANE;              iFormat = ChoosePixelFormat(*hDC, &pfd);              SetPixelFormat(*hDC, iFormat, &pfd);              /* create and enable the render context (RC) */         *hRC = wglCreateContext(*hDC);              wglMakeCurrent(*hDC, *hRC);     }          void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)     {         wglMakeCurrent(NULL, NULL);         wglDeleteContext(hRC);         ReleaseDC(hwnd, hDC);     }


title: Case Class naming convention

text: In my recent adventures in **Scala** , I've found **case classes** to be a really nice alternative to enums when I need to include a bit of logic or several values with them. I often find myself writing structures that look like this, however:               object Foo{       case class Foo(name: String, value: Int, other: Double)            val BAR = Foo("bar", 1, 1.0)       val BAZ = Foo("baz", 2, 1.5)       val QUUX = Foo("quux", 3, 1.75)     }      I'm primarily worried here about the naming of the object and the case class. Since they're the same thing, I end up with `Foo.Foo` to get to the inner class. Would it be wise to name the case class something along the lines of `FooCase` instead? I'm not sure if the potential ambiguity might mess with the type system if I have to do anything with subtypes or inheritance.


title: What are solutions and tradeoffs to maintain search result consistency in a web application

text: Consider a web application with a custom search function that must display the results in a paged manner (twenty per page with up to hundreds of thousands of total results) and the ability to drill down to individual results that maintain next/previous links to navigate through the results. Re-executing the search on each page request to get the appropriate results for that page of data can be too expensive (up to 15s per search). Also, since the underlying data can change frequently (e.g. addition of new results), re- executing could cause the next/previous functionality to result in inconsistent behavior (e.g. the same results reappearing on a later page after having been viewed on an earlier page). What options exist to ensure the search results can be viewed across multiple pages in a consistent manner, and what tradeoffs does each option have in terms of network, CPU, memory, and storage requirements? EDIT: I thought caching the query search results was an obvious necessity. The question is really asking about where to cache the result set and what tradeoffs might exist to each. For example, storing the ids of the entities in the result set on the client, or storing the IDs of the entities themselves in the users session on the web server, or in a temporary table in the database. I'm not looking specifically for a single solution as different scenarios may result in different approaches (and such a question would be more suited for stackoverflow.com rather than here), but more of a design comparison between the possible approaches.


title: Contract / Freelance Programming, The initial communication process / sending documents to them (terms, etc)

text: I've been searching around for info on contract / freelance programming as far as steps to take in the initial communication with a client (someone who has contacted me regarding a project). I am wondering if anyone has links to good resources as far as what I should send them (should I send them a document outlining "my process", etc?). Often the initial requirements that they send are vague and I want to immediately "take charge" of the process and starting asking them questions, talking about price, etc but I don't want to be too overbearing so I'm just curious if there is much out there written about this, my google searches aren't turning up much that is good about this sort of thing.


title: What approach to use to query multiple XML files?

text: I'll be receiving tens of thousands of XML files, which will continue to grow with new files over time. I need to be able to query these files as a whole (like SQL querying all the records in a database). What technologies and/or approaches should I be looking at for this problem? I feel like I should be looking into XQuery. I'm not that familiar with it, though. **UPDATE 1:** Example queries I might run:   * Return all the product code, product name, product description from all XML files in /folder 1/ where the supplier id = x and store id = y   * Return all the product code and product price from all XML files in /folder 2/ where the supplier id = x and store id = y   * Maybe join the results of the two queries above, joining on product code   * As there may be multiple results per product code for the two queries above, only get the most recent values based on some tag / attribute in the XML **UPDATE 2:** It seems like this article suggests that XQuery can be used: http://www.ibm.com/developerworks/xml/library/x-xquerymaven/index.html?ca=. As I am implementing a LAMP solution, I think there might be XQuery libraries available to PHP. Does this mean that I don't need an XML database to query loads of XML files?


title: Safe project development - free repositories

text: Some time ago we started a private hobby project. We made a project on javaforge.com, created an svn repository and started developing our app. Right now we are really far with our project, but somehow we never worried if our project is really safe on such free development tool like javaforge ? I mean, what if our project would earn some money and the source code become valuable ? Could it be stolen or could somebody take it over ? We want to be sure that we are not wasting our time and want to be really sure about our project safety. Is it possible to safely develop a project in such free repository ? We would like also to start using redmine, so if you know any safe place for moving our project, please take this under consideration. Thanks a lot.


title: Is it a really required skill to program without API documentation?

text: I barely passed my Java programming exam today. I had to answer some general questions about threading which I did well and to write a little threaded program which was worse. I had to connect my laptop to the projector screen and write the program right away. My first attempt was to use anonymous classes but I forgot the exact syntax. Maybe because of some excitement or maybe because last two weeks I was coding mostly in php. Then I asked is it allowed to use the API documentation. The answer was "NO". So I decided to go another way around and I implemented Runnable. The program was doing what was requested at the end. Of course the examiners noticed my first fail and that affected my score greatly. I was amazed that it was not allowed to use the API documentation. So, my question is: Is it really important to be able to code flawlessly without API documentation? Should I develop this skill? Is it really important in the real world and in the work environment? While on programming courses I focused on learning patterns, developing skills to write good design applications, skills to use API and find the necessary information fast. I was not trying to learn how to program without API documentation. Is it must-have during job interviews (coding without API documentation)?


title: How to catch DllNotFoundException in C#?

text: this question in my opinion straightforward. How can I catch an DllNotFoundException in C# as it is just an attribute to some methods use like this:               [DllImport("NativeLib.dll")]         private static extern void print_line(string str);      When are these functions being invoked ? As I instance the class containing the methods ( sounds odd to me as it's being "static" )? Or as I want to use the methods?


title: Building simulation architectures : Which one to choose?

text: I am writing a simulation which unites discrete event and continuous system simulation. For example, you can use State Charts, System Dynamics and Queues side by side. Theese will then reduced to DEVS, a mathematically defined and executable modelling formalism. Now I became stuck on how to organize the systems architecture. I'd like to use some kind of MVC pattern, so I thought lets make a state machine model, controller and state diagram, lets make a system dynamics model, controller and a stock and flow visualization, and so on. But these are also expressible via the DEVS model but it would be a bit complicated doing the translation to DEVS on the fly inside the controller ... So, should i have multiple models and representations which are then reduced to DEVS (base model) OR should I work directly with the DEVS base, so that e.g. the state machine is visualized as a state diagram, but internally it is automatically converted to the base model. Which architecture would you recommend?


title: Multiple Same Object Instantiation

text: What exactly happens in Java when you instantiate the same object multiple times? For example:               Test test = new Test();      then later on I will call it again, `Test test = new Test();` again or inside a loop. Will the previous instantiation be disposed?


title: Java - Why do we call an array a "vector"?

text: I am reading a book on Java Programming, and want to confirm I understand the definition of the word "vector". Wikipedia says vector is "A one-dimensional array", source http://en.wikipedia.org/wiki/Vector. Wouldnt it be simpler to call the array simply an array? Is there any reason we need to use such fancy language as "vector"? Is there a difference between an array and a vector?    ![enter image description here](http://i.stack.imgur.com/daFEx.png) Source: Cracking the Coding Interview, 4th Edition, by Gayle McDowell, page 47. FAQ   Q - Why didnt you post this on english.stackexchange.com?   A - Because I think only computer science oriented people will have a good answer.


title: Examples of UNIX Domain Socket Usage

text: Can anyone give an example of instances in which the AF_UNIX i.e unix domain sockets are used for process communication in a unix-based system


title: C++11 Header-only Library: in-class body vs. out-class body code?

text: ## BACKGROUND:optional **Since 2002** I've been slowly building my own **Windows Native C++ library**. And let's just say that I have jumped **150KLOC** _(reusable code)_ having everything I need and the kitchen sink in it _(from most of the Windows API objectualized to a decent IMAP4 client implementation and the WordPress XMLRPC client for mass publishing... I do Affiliate Marketing and SEO Tools)_. It's not yet `.NET` but it ain't that far :) The only **3rd party libraries** used in it are `ZLib`, `MySQL` and `SQLite`. Everything else is built from scratch using the `STL` and/or `Windows API`. _(I still have a PDF writer/reader to implement, IOCP all network things, and there's always room for more work...)_ **For the past 1.5 years I've been in a sustained effort of updating it for C++11.** Move semantics where due, _(explicit)_ bool operators, chained constructs and much more of what _(MSVC's modest)_ C++11 brought us. Plus CRTP for chained parent/child calls, minimal use of virtuals, strict const- correctness. **And succeeded.** **Recently I've been really considering publishing it.** It's a huge amount of work that I've only done for my own benefit and I assume there's still `Windows C++` devs out there that could use such a thing. And to do that, went on to read **C++ code practices and API/Library design guidelines**. It was great! I nailed 80-85% of best coding practices myself. With a few things I'll address soon and **one major question**. ## QUESTION **Currently the entire library is quite-templated and header only.** That means all code is in the body of the classes. It's not very easy to manage but it's OK. I collapse code, use `#pragma region`s and nicely structure things. **BUT I'm VERY tempted, after reading several C++ library coding guidelines, to break it into`.hpp` \+ `.inl` files.** Experimentally done so for a few classes and it does increase readability and makes it easier for others to deal with _(even if it's a bit harder to write)_. I know where everything _(line of code, functionality)_ is at any given time. But other users might want to a quick overview of a classes declaration... and the definition ONLY if/when necessary _(debugging)_.   1. **What are the accepted and/or preferred practices regarding splitting declarations from definitions.** Would you rather have header only classes with in-body code or code separated from the function declaration?   2. **What are the current practices of other libraries?** I've always written everything myself. Not that up to speed with how others do it. Except the 3 libraries mentioned above, I've yet to use other 3rd party code. > **This is an important question for me because it's a one way road.** I > can't refactor it the other way later on so **any feedback matters and is > appreciated**... _Thanks_.


title: Are there any good reasons to use, learn, or recommend XSLT?

text: I am a developer for the last 8 years. We used XSLT primarily to transform XML into HTML. We also used it for XML to XML transformation. But we have replacement for everything now. HTML can be comfortably created through programming languages such as ASP.Net. XML can be read and manupulated in any standard highlevel languages. As programming in XSLT is a little complex, any one would prefer working on latest programming languages. Now my question: Will XSLT be a significant choice in future, not considering the fact of maintaining already developed XSLT? Can I recommend new programmers to study XSLT?


title: How would one go about building pluggable software?

text: If you have an application of some sort and you want your users to be able to write plugins for it, how should the application be designed? What do you have to take into account, what design patterns are for this etc?


title: Who usually does the use case analysis in the team?

text: I've just started my first IT job in a team with two developers (junior and senior), a project leader and an architect. My role is not yet completely defined and I said I'd be ok with both programming or testing. For now they put me on use case analysis since the PL says that it would leverage my analytical skills (I'm a science phd). Now the question is who's usually responsible for use case analysis? How usual is it to put a newbie on it? The hidden fear I have is: are they trying to keep me away from programming (after two weeks I still haven't SEEN a line of code...)?


title: Dynamic typing across the whole technology stack - where to enforce data validity?

text: Over the past year or two, I've been playing with newer technologies in my side projects. As a web developer, I've gone from the following (and still the following, at work): ## The 'classic' technology stack   1. Web browser POSTs forms to...   2. a C#-coded web application server-side, communicating to...   3. external services via XML, then ultimately...   4. writing the application state to a SQL database. To using a very different arrangement: ## The fully-dynamic technology stack   1. Web browser submitting XmlHttpRequests to...   2. a JavaScript-coded Node.js server-side, communicating to...   3. other external services via RESTful services in JSON, ultimately...   4. writing the application state to a no-SQL database It's gotten to the point where my whole stack has absolutely **no enforcement of type or schema, anywhere**. Now, this has been just fine before, when consuming others' web services. It might have even been fine up until the SQL databases were ditched (along with their DB schemas). But now I'm stuck at: ## Where do I _declaratively_ define what is the valid structure of my business-domain data? I want to enforce data validity before making any of my projects publically available - after all, what's to stop someone from just submitting invalid data to my services, and using it all as just a hacky free database provider? At some point, it has to be enforced that "this web service will only accept a collection of at least one X. X must contain A, B, and optionally C". The first solution I thought of was to do validation inside my node.js, through a big block of imperative code/if-elses/etc. This felt wrong. I have been using CouchDB, and for a while I thought that it might be best to put that validation code in the `_update` handlers. At least we're performing validation as part of persistence, but it's still an ugly imperative block. Next, I looked into JSON schema languages. There is no standard as far as I can see, and I wasn't confident in the multiple solutions offered. I could roll my own, but then I'd only be expanding the body of non-standard JSON schema languages. XML? I could put the **X** back into AJAX, and have them all schema-validated on the server side. That doesn't seem to follow the trends in software development, however. Neither would using an XML data store instead of a JSON CouchDB/BSON MongoDB persistence layer. So, I'm stuck. Ideas? **TL;DR** Where do I declaratively define the valid structure of my business- domain data when I am using no static Object Oriented language, and no schema- bound SQL database, in my technology stack? Is it possible that there must be some static typing (or DB schema, or validated XML) _somewhere_ for a technology stack to make any sense? If so, where?


title: What is a cross-platform way to expose an Array[][] over a webservice? Any JSON nuances to be aware of?

text: I need to expose an Array[][] to many different clients (iPhone, Android, PC, Unix, etc), and need to make it available over HTTP/s This brings me to JSON, and makes me wonder how do all the other *endian machines work with JSON and will I need to worry about how the array will be reconstructed on other platforms. Initially this will be an array of UTF8 strings, but I want to support other types, for example, Array[0][] will be a image, while Array[1][] will be a audio file. ...etc. If JSON is the right way to send Array[][] data across HTTP, what "gotchas" should I be concerned about?