Where should I declare variables used in for-loops in Java for maximum efficiency?

I'm talking hypothetically but I'll use an example of what I worked on in a programming class a while ago. There's a better way to actually perform the operation, but that's not the point. An example to show what I mean I want to take a BufferedImage and individually manipulate each pixel. So something like this:               for(int x = 0; x < out.getWidth(); x++)     {         for(int y = 0; y < out.getHeight(); y++)         {             int color = in.getRGB(x, y);             int r = (color & 0xff0000) >>> 16;             int g = (color & 0x00ff00) >>> 8;             int b = (color & 0x0000ff);             //Do something with r             //Do something with g             //Do something with b             color = (r << 16) | (g <<8) | b;              out.setRGB(x, y, color);         }     }     return out;      Would this loop be more or less efficient if I declared color, r, g and b outside of the for loops?


Where are C variables declared

I see a lot of code with variables declared right after the function, but when I post something like that people end up mad and say it is better to declare them when they are used. I assume this all compiles to the same executable, so it is simply a matter of style. As far as I can tell, pretty much all C code (99.9% that I've seen) declares them near the beginning and this is how it has been done for many years. So why do people keep suggesting that they are declared closer to the block that uses them?


Where do you declare variables? The top of a method or when you need them?

I am in sort of a dilemma (in a geekish way of course). I **love** to declare variables at the beginning of my methods, and usually order them in some logical way. The problem is, when the list gets long, it sort of gets out of hand. Should I just declare them **when I need them**?


> **Possible Duplicate:**   >  Where do you declare variables? The top of a method or when you need them? Does it make a difference if I declare variables inside or outside a loop in Java? Is this               for(int i = 0; i < 1000; i++) {        int temp = doSomething();        someMethod(temp);     }      equal to this (with respect to memory usage)?               int temp = 0;     for(int i = 0; i < 1000; i++) {        temp = doSomething();        someMethod(temp);     }      And what if the temporary variable is for example an ArrayList?               for(int i = 0; i < 1000; i++) {        ArrayList<Integer> array = new ArrayList<Integer>();        fillArray(array);        // do something with the array     }      EDIT: with `javap -c` I got the following output Variable outside the loop:                 public static void main(java.lang.String[]);         Code:            0: iconst_0                  1: istore_1                  2: iconst_0                  3: istore_2                  4: iload_2                   5: sipush        1000            8: if_icmpge     25           11: invokestatic  #2                  // Method doSomething:()I           14: istore_1                 15: iload_1                  16: invokestatic  #3                  // Method someMethod:(I)V           19: iinc          2, 1           22: goto          4           25: return        Variable inside the loop:                 public static void main(java.lang.String[]);         Code:            0: iconst_0                  1: istore_1                  2: iload_1                   3: sipush        1000            6: if_icmpge     23            9: invokestatic  #2                  // Method doSomething:()I           12: istore_2                 13: iload_2                  14: invokestatic  #3                  // Method someMethod:(I)V           17: iinc          1, 1           20: goto          2           23: return              And for the interested, this code:               public class Test3 {         public static void main(String[] args) {             for(int i = 0; i< 1000; i++) {                 someMethod(doSomething());             }            }         private static int doSomething() {             return 1;         }         private static void someMethod(int temp) {             temp++;         }     }      produces this:                 public static void main(java.lang.String[]);         Code:            0: iconst_0                  1: istore_1                  2: iload_1                   3: sipush        1000            6: if_icmpge     21            9: invokestatic  #2                  // Method doSomething:()I           12: invokestatic  #3                  // Method someMethod:(I)V           15: iinc          1, 1           18: goto          2           21: return         But the optimization happens at runtime then. Is there a way to look at the optimized code? (Sorry for the long EDIT)


Where should variables be declared

Considering I have a `for` loop in a method of a class. Should the incremented variable be declared as `member of the class`, or should it be declared `in the method` it uses it(or even in the `for` loop, directly)? While declaring it inside the method seems easier and cleaner, doesn't declaring it at the start of the class makes you have more control over it? Something like declaring it `int var_used_for_loop_in_method_x`. What is good programming practice? Note that I'm not asking specifically for the `for` loop. I am asking if we should try to put most variables as class members as much as possible or not.


Writing a unit test for a platform dependent unit

I have a method to be tested which depends on the OS, what's the best approach for testing the method depending on the OS? Is it to test on every OS that I have I require? Is there a better approach for running the tests on only one system? Some more specific information is that I have a method which is dependent on the OS using Python's `platform.system` method in a if-else statement and I need to test that which all the possible outcomes from this method. This method looks like:               def updateString():         if platform.system() == 'Darwin':             return "http://download.com/to/OSX/version"         elif platform.system() == 'Linux':             return "http://download.com/to/Linux/version"         elif platform.system() == 'Windows':             return "http://download.com/to/Windows/version"         else:              return "Seek advice on how to update."


What's the best documentation you produce and why?

I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination. So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests. The bigger question is _why_ is that the best documentation you produce?


Is array dependence on previous terms considered recursive?

For example, take the case of Fibonacci number to calculate nth number you require `n-1` and `n-2` term. If I do it with bottom up approach, is it recursion as `f(n)` depends on `f(n-1)`?


DBMS agnostic - What to name the COUNT column from a SQL Query

I have trouble naming the COUNT() column from SQL queries and will swap between various variants   * _Count   * [Count] (sql, or "count" or backticks for MySQL etc)   * C   * Cnt   * CountSomething (where "something" is the field being counted, or "CountAll")   * NoOfRows   * RowCount   * etc Has anyone come up with any name that you are happy with and always use without hesitation?   This is bothering me because after joining SO just recently, my answers have shown this tendency of flip-flopping with no consistency.   I need to get this sorted. Please help. (While we're at it, what do you use for SUM etc?) **Note:** Before you close this question, consider that this one was not: What's the best name for a non-mutating “add” method on an immutable collection?


What's the difference between model for test and model for development? Is it that the model for test contains only what we should test? Do we use the same diagrams in model for test and model for development? For example, if we use sequence diagrams for generating test cases, these diagrams will not be used for coding? I speak in the context of Model Based Testing (MBT).


How to develop an app for a smartphone to access a web app?

My colleague developed an internal web application. This app works only in Internet Explorer, which means that I can't access it from my smartphone. Is there any way to develop an application which will serve as a bridge between my smartphone and this web app, enabling me to use the web app from any other browser/mobile device?


What do I have to do when using libraries with BSD license?

I am making a game using LWJGL and this is their license. What I don't understand is what must I do? I plan on making a game and distributing it, not the source code just the .jar file and maybe sell it for a few dollars. It said that I must retain the copyright, so would that mean I must include the doc folder that the library comes with in the jar or do I have to make something in-game like credits and say "made with LWJGL"?


Functions returning either "OK" or "error message" instead of procedures

I have joined writing middle-size multi-purpose database application as co- lead. It currently has about 150 tables (and growing) and overall functionality you can imagine as very small ERP. At many places in code, functionalities which would normally belong into procedures (I mean functions without return value) like `DeleteAttachment` or `SaveRecord` are put into functions with return value reporting their exit status in string. They return either `"OK"` on success or messages like `"Deletion failed because ......."` or `"Insufficient privileges for ......."`. At the end, often the end user is presented with message they provided. On one hand, this is effective mechanism of tracing of potential problems. On the other hand, I'm not sure whether I should encourage this approach of writing the inner business logic. I understand that putting non-fatal problems into exceptions is also not very good way to go (`EInsufficientUserPrivileges`, `ERecordAlreadyExists`). Should we stick with current approach or is there some other which is more suitable for applications using a many checks and business logic?


Why is Global State so Evil?

Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here. Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really **is** so bad about the ominous global state? Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials. In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application. I know it's bad to **abuse** it, but is the global space really **THAT** evil? And if it is, what good alternatives are there?


Passing central objects around or having global instances?

Having a larger WinForms application with several classes I currently pass references to several "central" objects around to function calls. This leads to more method parameters. Example:               public static class Program     {         private static MyCentral _central;              ...     }          ...          public class SomeController     {         public object SomeFunction(MyCentral central)          {             // Do something with the MyCentral instance.         }     }      Now I'm asking myself whether I should ditch this approach and instead use singletons for those central objects so that everyone can always access these objects and I do not need to pass them around anymore. Example:               public static class Program     {         public static MyCentral Central { get; private set; }              ...     }          ...          public class SomeController     {         public object SomeFunction()          {             // Do something with the Program.Central singleton.         }     }      **My question:** Are there any rules-of-thumb whether the singleton approach or the "passing objects around" approach should be prefered?


Should I use extern global variables or static global variables with "get" and "set" functions in C

I am working on one of my first projects in C (microcontroller code) which is split up into multiple C files. I noticed some inconsistency in my coding where I had some variables declared as extern global variables and would just access them directly (ISR and some other places), and others declared static global variables, and would then accesses them from different files using function calls. What is the best way to do this? Should I always keep the scope as small as possible even if it means adding extra functions just to set or read the values? Or should I just make them global across all files and just access them directly.


Indefinite loops where the first time is different

This isn't a serious problem or anything someone has asked me to do, just a seemingly simple thing that I came up with as a mental exercise but has stumped me and which I feel that I should know the answer to already. There may be a duplicate but I didn't manage to find one. Suppose that someone asked you to write a piece of code that asks the user to enter a number and, every time the number they entered is not zero, says "Error" and asks again. When they enter zero it stops. In other words, the code keeps asking for a number and repeats until zero is entered. In each iteration _except the first one_ it also prints "Error". The simplest way I can think of to do that would be something like the folloing pseudocode:               int number = 0;     do     {         if(number != 0)         {             print("Error");         }         print("Enter number");         number = getInput();     }while(number != 0);      While that does what it's supposed to, I personally don't like that there's repeating code (you test number != 0 twice) -something that should generally be avoided. One way to avoid this would be something like this:               int number = 0;     while(true)     {         print("Enter number");         number = getInput();         if(number == 0)         {             break;         }         else         {             print("Error");         }     }      But what I don't like in this one is "while(true)", another thing to avoid. The only other way I can think of includes one more thing to avoid: labels and `goto`s:                   int number = 0;         goto question;     error:         print("Error");     question:         print("Enter number");         number = getInput();         if(number != 0)         {             goto error;         }      Another solution would be to have an extra variable to test whether you should say "Error" or not but this is wasted memory. Is there a way to do this without doing something that's generally thought of as a bad practice (repeating code, a theoretically endless loop or the use of `goto`)? I understand that something like this would never be complex enough that the first way would be a problem (you'd generally call a function to validate input) but I'm curious to know if there's a way I haven't thought of.


Should my boss decide what IDE I should use?

I just have a simple Question: Should/could my boss decide/dictate what kind of IDE i should/must use for my development? Background: I have been developing software for 10 years, using diffent IDE's for diffrent languages. But, for the last years I have settled with using Eclipse. This is mostly because I use it both for Android (Java) and PHP and Web development. I know its not the newest, and does not got all the new cool features that other IDE's got, but I feel quite comfortable with it, and I specaially like the SVN plugin and Android tools it got. I'm kind of new in this company and the choice of IDE have always been my own decicions when working for other companies. My previous employers have never tried activly to change my choice of IDE. But, my new boss want me to change to something called PHPStorm, which I have tried, and found a bit to "busy" for me. It just got too much features for me. My boss says he don't want to force me, but uses every chance he got to mention the PHPStorm, and seems a little annoyed because I still use eclipse. That is the feeling I get. In my opinion, what kind of IDE I use is not "his table". It should be my personal choice. Maybe I'm wrong. Maybe I'm being arrogant ? It does not help that all other team members have moved to PHPStorm (away from intelliJ, netbeans, etc). My boss want "One-Ide-Too-Rule-Them-All". This way the code will become more consistent and we can learn from each-other he says. That said, I like my boss, so this is strictly a IDE issue. So, yes, I feel a bit annoyed about the situation. What do you think, how would you feel, what would you do in this situation ?


Am I personally liable for bugs in medical software I've developed as an employee?

Some background: I'm employed at a small, Australia-based web agency that is dipping it's toe into Mobile Application development (iOS). The project that I'm working on provides a way for users to save medication dosage information which is sync'd with a backend server. Users must agree to ToS, Disclaimer etc before using the application. This is my first iOS application, and the project is currently over budget. As a result, management is not devoting the resources to Q&A and is pushing instead for more features. I am an employee of the agency, that has been contracted by a non-for-profit. The application will probably be released under our agency's name, but we also have the option of releasing it as the not-for-profit. My question is, if there are bugs found in the application, and as a result a user takes an incorrect dosage of a medication, am I personally liable? Is there anything that I can or should do in order to protect myself personally?


Does Scrum turn active developers into passive developers?

I'm a web developer working in a team of three developers and one designer. It's now about five months that we've implemented the agile scrum software development methodology. But I have a weird feeling I just wanted to share in this site. One important factor in human life is decision-making process. However, there is a big difference in decisions you make. Some decisions are just the outcome of an internal or external force, while other decisions are completely based on your free will, and some decisions are simply something in between. The more freedom you have in making decisions, the more self-driven your work would become. This seems to be a rule. Because we tend to shape our lives ourselves. There is a big difference between you **deciding what to do** , or **being told what to do**. Before scrum, I felt like having more freedom in making the decisions which were related to development, analysis, prioritizing implementation, etc. I had more feeling like **I'm deciding what I'm doing**. However, due to the scrum methodology, now many decisions simply come from the product owner. He prioritizes PBIs, he analyzes how the software should work, even sometimes how the UI and functionality should be implemented. I know that this is part of the scrum methodology, and I also know that this may result in better sales of product in future. However, I now feel like **I'm always getting told to do something, instead of deciding to do something**. This syndrome now has made me more passive towards the work.   1. I tend to search less to find a better solution, approach, or technique   2. I don't wake up in the morning expecting to get to an enjoyable work. Rather, I feel like being forced to work in order to live   3. I have more hunger to work on my own hobby projects after work   4. I won't push the team anymore to get to the higher technological levels   5. I spend more time now on dinner, or tea-times and have less enthusiasm to get back to work   6. I'm now willing more for the work to finish sooner, so that I can get home The big problem is, I see and diagnose this behavior in my colleagues too. Is it the outcome of scrum? Does scrum really makes the development team feel like they have no part in forming the overall software, thus making the passive to the project? How can I overcome this feeling?


Ubuntu, OpenSuse, the world of linux for a web-developer

I'm learning web development. My main OS is windows 7 but I've used Linux and currently dual-booting with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting, don't know very well the most important commands, nor the system in general. I am interested in web development. Should I get myself familiarized more with Linux ? Is it a must for future job positions considering my field of interest?


RESTful HTTP OPTIONS request content

I'm having trouble determining what I might put in the body of a response to an `OPTIONS` request? are there conventions? standards? What do you put? do you just provide a list of other METHODS? should you give the representation?


Are separate parsing and lexing passes good practice with parser combinators?

When I began to use parser combinators my first reaction was a sense of liberation from what felt like an artificial distinction between parsing and lexing. All of a sudden everything was just parsing! However, I recently came across this posting on codereview.stackexchange illustrating someone reinstating this distinction. At first I thought this was very silly of them, but then the fact that functions exist in Parsec to support this behavior leads me to question myself. What are the advantages/disadvantages to parsing over an already lexed stream in parser combinators?


How can I learn about optimising for the CPU cache (in C)?

Reading these two questions, I see that understanding CPU caching behaviour can be important when dealing with large amounts of data in memory. I would like to understand the way the caching works to add another tool to my optimisation toolbox. How can I learn about the way the CPU cache works so I can write code that uses it sensibly? Relatedly, is there a way to profile code to see if poor cache use is slowing things down?


Into which artifact does one package intermediate classes?

We have modularized our API into some independent components. Independent meaning these can be built via Maven and used as dependencies for other projects such as webapps. Now, to use this API, there needs to be an _intermediate processing class_ which does a _translation of the client data model into the callee (component) data model_. The question is does this handler/processor class belong and need to be packaged along with the client application JAR/WAR or is it part of the component JAR. What is the convention?


New to Programming/objective c

I've recently started to work on some iPhone apps, starting from a base where I had essentially no programming experience (I studied Maths & had very few programming modules) I worked my way through Beginning Mac Programming: Develop with Objective-C and Cocoa and found it useful, while it gave me the feeling that I needed to quickly address my lack of a real foundation in programming. For the forseeable future my work will involve developing iPhone apps - I want to have a real grasp of objective-c before things get more pressurised in the coming months. Is my best bet to study c first of all, before worrying about the finer points of objective-c? If so has anyone had any experience teaching themselves through an online resource? It would be great if someone could recommend a website with which to self-teach c. Sorry if this covers some old ground but nothing in the similar questions quite answered my question. Any help is greatly appreciated :)


Is Ruby on Rails a suitable framework for a desktop application?

I was wondering if there are obvious advantages and disadvantages to using Ruby on Rails to develop a desktop application. RoR has great infrastructure for rapid development, proper implementation of specs and automated acceptance tests, an immense number of popular libraries and the promise of being actively developed and maintained in the future. The downsides I can see are mostly about usability - installation of a Rails app as a local service and launching of a browser when it needs to be active may not come naturally to many users... or be technically easy to implement and support for different platforms.


Is it "normal" for people to not work?

After graduating from college I was hired as a junior programmer a little over a year ago. I quickly noticed that I was degrees of magnitude faster than all the other programmers; this seems to be because I simply don't waste time "in general". The majority of other people however seem to enjoy staring at the ceiling, browsing YouTube, Facebook, and random websites, and in general doing in a day the work I usually do in an hour. I'm 100% sure they would be able to do that work in an hour too if they focused. I've been quickly promoted to senior developer and more recently to team leader and now I replaced a lot of those people with new hires (still a couple to go). The situation is now more acceptable, but still I think it could be much better. I can't help but notice though, that everyone seems to behave like this is "normal". All my bosses aren't concerned about this and they too seem to work little to nothing. I always have a very hard time finding them, they arrive much later than they are supposed to and leave early. Obviously there is nothing I can do in this case since they're above me, but is this is the "norm" in all companies, or did I simply end up in a very bad one (this is my first work experience)? Also, will I "become like them" in a few years?


How to implement Continuous Delivery with Java webapp?

I've been reading about Continuous Delivery and it sounds awesome to automate the deployment process. I've been reading about possibilities how to do this with Java Webapps, but usually it ends up with CI server or maven plugin deploying to Tomcat WITHOUT restarting the Tomcat using Tomcats management API. But that leads to OutOfPermGenSpace issues and so I wouldn't use those solutions for production. In addition it is a hassle to kill an out of control Tomcat. Is there any technology that would make it easy to deploy Java web apps to production? I use maven to build my artifacts and deploy to nexus repository. EDIT: I'm not trying to find ways to prevent Permgen space issues. I'm trying to automatically deploy to production. There should be no manual steps beyond choosing a version and clicking a button(or giving a version number to a commandline script). I want to find out if I have to create this kind of setup manually, or if there is a ready made solution for this. Thus far LiveRebel seems to be the only solution so far that doesn't require me to implement everything myself.


Classes shouldn't call other classes?

I've just finished reading The Art of Unit Testing, by Roy Osherove. It was an interesting book, but I'm having trouble with something he mentions near the end (section 11.2.2): > Identifying "roles" in the application and abstracting them under interfaces > is an important part of the design process. An abstract class shouldn’t call > concrete classes, and concrete classes shouldn’t call concrete classes > either, unless they’re data objects (objects holding data, with no > behavior). This allows you to have multiple seams in the application where > you could intervene and provide your own implementation. Specifically, I don't understand what he means when he says that concrete classes shouldn't call concrete classes. Consider the following examples in C#:               double roundedAge = Math.Floor(exactAge);      Is this not considered a call to a class because Math.Floor is a static method? Or is Osherove saying that the line of code above is bad design? Another example:               using (StreamReader reader = new StreamReader(path))     {         // do things     }      Is this bad design due to the use of a StreamReader? Or is this instance of StreamReader simply an object that holds data, as described in the quote above? Rather than starting a discussion on whether or not it's bad practice to have classes call other classes, my goal here is to try and better understand what Osherove means in the passage I've quoted. Does he really mean that the code in the two examples above should be avoided? Thanks in advance for any replies. EDIT: Below is an illustration from the book which is possibly elucidating. ![Nice](http://i.stack.imgur.com/7Jb0F.png)


How to "back track"?

I find that I start projects and, due to my lack of experience, find that old database structures and huge blocks of code are inefficient and memory-costly. However, by the time I realize a re-design of the entire project is needed, the project has grown to such a size that it is simply too late to go back and modify the project in its current state and requires a completely new project file and the whole shebang. **How should I prevent ruts such as this one, where it is too late to go back and modify the current project to fit specifications modified far down the road from the creation of the project?** (Apologies in advance for confusing grammar, it's been a long day here... as you can probably tell.)


Sharing on Github

Over the past couple weeks I have gotten a lot of help from StackOverflow users on a project, and rather than keep the finished product to myself I wanted to share it unencumbered by licenses, but don't want there to be so much legwork during installation that users shy away from trying it. I am about to post it to Github and choosing public domain licensing. I would like to to be super simple for users to make use of and just FTP it up and go. That being said, do I need to make sure I remove things like the JQuery file, and other GPL / MIT licensed dependencies that I didn't write but that my code depends on? I haven't removed any copyright notices from the other code and all of it open source, it would just be nice if users could download everything at once while of course not trying to represent that I am the license holder of the dependencies. Inside my files are also some snippets, do those have to be externalized with installation instructions or can it be posted as is? Here is an example, my nav.php file is 115 lines long and I have these at the top:                    <link href="css/admin.css" rel="stylesheet">


Interested in Feedback on QA System Design

I'm in the beginning phases of creating a QA system and I want to make sure that the design decisions that I'm making now make sense and won't bite me in the butt later on. If you have even the slightest nit-picky thing or whatever, please post, I'd appreciate hearing any feedback about this (I'm quite new to it all). **QA solution folder:**   * Assembly For Regression Tests (Class Library)   * Assembly For Integration Tests (Class Library)   * Assembly For Unit Tests (Class Library)   * Assembly for QA related Utilities (Class Library) **Each assembly has this basic structure:**               [TestFixture]     public class SomeComponent{         [Test]         public void SomeComponentFunction(){             bool someBool;             //Some stuff             Assert.IsTrue(someBool,"");         }         [Test]         //etc.     }      **Some specific things I'm wondering** (but I'm open to feedback about anything)   * Are class libraries the appropriate project type to use? I can see the advantage of using console applications so you can run these tests independent of NUnit (but I don't know why you'd do that instead of just using NUnit).   * I'm having a difficult time understanding the difference between regression level tests and system level tests. For a system level test, it seems like you run an end-to-end test, and compare the final result with some "Standard" result. Isn't that just regression testing?


How valid is ITJobsWatch data?

_(I've been wondering all day whether to ask this question here - my biggest concern would be that it would be seen as off-topic, or not relevant. It's not relevant to the US, this is true, but it is VERY relevant the UK market.)_ My question is: do hiring managers / IT decision makers in the UK use data from ITJobsWatch in their decision making process, how valid is the data and how accurate do you perceive it to be. (as a secondary, more worldwide question: do people use salary aggregation sites in their decision making/negotiation process) A couple of disclaimers! I don't work for them, I have nothing to do with them. I invite (genuine) comments from representatives of the site about how they collect the data (I've read the small paragraph on their website already). I also wouldn't consider that I'm pimping the site here - I imagine any UK hiring manager worth his stuff will already know about it! I've been asked whether the data on the site is valid and relevant, and I'm curious as to the response from the UK market.


How do you guys handle translation for software localization?

Most of the software I have written over my career has been built for English speaking customers, but recently I've been working on a project where localization of the UI for a wider range of languages is desired. I am just curious how other programming shops obtain the translations. Do they use the notoriously flawed online translation engines? I know there are for-hire translators out there, but am I going to have to track down and contract like a dozen of them to do a thorough job of localizing my interface? Are there services that specialize in doing this for a wide range of languages? Perhaps using something like Amazon's Mechanical Turk would be an option, but I have no idea how diverse the available workforce is on that site. I'd imagine not very.


Multiuser System With Encrypted Database

I am currently developing a hosted solution in ASP.NET using MVC3 and Entity Framework. This product will then be made available to a number of clients as a hosted solution. As the data stored by each client will be critical to their business, we anticipate that many of them will insist that the data is stored in an encrypted form in the database. We are therefore designing the system with this in mind. Are there any recommended procedures for doing this? How would one go about encrypting the clients data in such a way that even us with root access to the database cannot possibly access their data? I believe there is no built in support in EF for encrypted data, is this true? And if so, how would one encrypt/decrypt the data?


How to gather critique on a highly specific or niche application?

I'm currently developing, on an independent basis, an application that is highly domain specific; a niche application if you will. This is all well and good, of course; but there is one problem; I'm not in a situation where I have a natural tester group. The issue is not really one of finding testers for technical accuracy; the application in question has the twin benefits of being (at least for now) dead simple in design and implementation, and having a developer that is also has the appropriate domain knowledge. Despite my relevant knowledge, however; I am not actually in the target audience for the application, leading to problems in identifying useful features for future implementation, among other things. What then, are the avenues to explore with regards to actually finding end users?


Is it normal to think about a design problem for days with no code written?

Sometimes I stare blankly into space or sketch ideas and write some pseudo codes on paper. Then I scratch it out and start again, then when I think I have the correct solution for the problem I begin writing the code. Is it normal to think for days without writing any code? Is this a sign that I am approaching the problem entirely wrong? It makes me nervous to not getting any tangible code written in my IDE.


How is CoffeeScript influenced by Haskell?

I've been using CoffeeScript for a while now. On Wikipedia, it is said that CoffeeScript is influenced by Haskell. But after I check out the syntax of Haskell, I have found little resemblance from CoffeeScript. Which aspect of CoffeeScript is influenced by Haskell?


Restart button in Python

I am having trouble with python. I am making a text-based adventure game, and I am trying to make a restart function when you die. I am trying to count deaths by doing deaths = deaths + 1 whenever you die, but the only way to restart is to re-run the entire script, which resets the death counter. Does anyone know how to restart a script without re-running the program?


Where to find clients?

My main area: web development. Of course, I don't expect anybody give away their 'gold mine' or whatever but I am struggling to see where I should be advertising my services. I have one other developer I work with and we have a lot of happy clients - on freelance websites. Thing is, freelance websites just seem to suck the life out of you when you're being out-bidded by ridiculous rates. I want to attract customers who are more concerned about quality and accountability than price. Any suggestions at all? I'm so lost with this. EDIT: Added bounty of 200 - all of my 'reputation'. EDIT: Added second bounty of 50 I did hear of a novel idea. Do work for an opensource project and get featured in their 'trusted developers' section, if they have one. Input?


REST - Tradeoffs between content negotiation via Accept header versus extensions

I'm working through designing a RESTful API. We know we want to return JSON and XML for any given resource. I had been thinking we would do something like this:               GET /api/something?param1=value1     Accept:  application/xml (or application/json)      However, someone tossed out using extensions for this, like so:               GET /api/something.xml?parm1=value1 (or /api/something.json?param1=value1)      What are the tradeoffs with these approaches? Is it best to rely on the accept header when an extension isn't specified, but honor extensions when specified? Is there a drawback to that approach?


Disadvantages of functional intermediate form

I'm writing an optimizer for a language similar to JavaScript, and need to choose an intermediate code representation. The obvious/typical choice these days is Static Single Assignment (SSA). However, _Modern Compiler Implementation in C_ also discusses functional intermediate form, which basically means going pure functional for the intermediate representation (pure in terms only of local variables, heap data is still mutable, and not CPS, just straightforward `let` blocks and tail calls) and has some advantages in terms of being easier to reason about. Presumably it's not a no-brainer or everyone would already be using such a representation, so my question is, what disadvantages does functional intermediate form have compared to SSA?


What is the best way to deal with legacy code not in version control?

What is the best way to develop and maintain legacy code not in version control? Adding it to version control is of course the obvious answer, but if you can't, for some reason, what would you do? A few reasons I can think of why version control wouldn't be possible are:   * Management is against it (doesn't understand it, thinks it would take to much time, isn't worth it, etc.)   * You don't have the administritative privileges to install the required software.   * The code runs/is stored on legacy systems with limited capabilities for version control. So, if real version control isn't available, what do you do? Set up some regular backup system? Or perhaps create version-named folders?


How much detail is in a good UI regression test?

We use a detailed step-by-step user-interface regression test for our commercial web application. It has a "backbone" test for the most used / most important parts of the system, with optional tests for specific areas of functionality. Using this plan has definitely helped us ensure high quality software. But, having very specific tests can be counter-productive. The tester concentrates on following the test and will completely miss usability issues, or not notice fairly obvious problems such as the bottom part of a page that is missing. By contrast, some of the best UI testing happens when building a demo of a new feature. I often do my own best testing by pretending to demonstrate the system to an imaginary prospect. Yet when I tell the testers, "Just demonstrate the system to yourself" they don't cover nearly as much functionality as they do with a detailed point-by-point test. I'm repeatedly asked to provide more and more detail in the test plan so that a new untrained tester can test with it without asking any questions. Yet details seem to be counter-productive. How much detail do you put in a regression test to make it effective? How do you write tests that make the tester focus more on the system than on checking off items on the test?


Can web apps allow fast data-typists to "type-ahead"?

In some data entry contexts, I've seen data typists, type really fast and know so well the app they use, and have a mechanic quality in their work so that they can "type ahead", ie continue typing and "tab-bing" and "enter-ing" faster than the display updates, so that in many occasions they are typing in the data for the next form before it draws itself. Then when this next entry form appears, their keystrokes fill the text boxes and they continue typing, selecting etc. In contexts like this, this speed is desirable, since this persons are really productive. I think this "type ahead of time" is only possible in desktop apps, but I may be wrong. My question is whether this way of handling the keyboard buffer (which in desktop apps require no extra programming) is achievable in web apps, or is this impossible because of the way web apps work, handle sessions, etc (network latency and the overhead of generating new web pages ) ? **Edit:** By "type ahead" I mean "keyboard type ahead" (typing faster than the next entry form can load), not suggets-as-you-type-like-google type ahead. > Typeahead is a feature of computers and software (and some typewriters) that > enables users to continue typing regardless of program or computer > operation—the user may type in whatever speed he or she desires, and if the > receiving software is busy at the time it will be called to handle this > later. Often this means that keystrokes entered will not be displayed on the > screen immediately. This programming technique for handling user what is > known as a keyboard buffer.


Is there a difference between the quotes in `help',``help", 'help' and "help"?

Sometimes I find in the source code files comments have quotation marks like these ,notice the ` :               `help'     ``help"      For example, these are comments from GNU cat source code file, cat.c:                 /* Plain cat.  Copies the file behind `input_desc' to STDOUT_FILENO.  */      >                 /* Select which version of `cat' to use. If any options (more than -u,          --version, or --help) were specified, use `cat', otherwise use          `simple_cat'.  */      >               /* Suppress `used before initialized' warning.  */      While in other parts, "" is used :                 /* Determines how many consecutive newlines there have been in the          input.  0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,          etc.  Initially 0 to indicate that we are at the beginning of a          new line.  The "state" of the procedure is determined by          NEWLINES.  */      What does ` mean? and what is it used for?


Java: "Heap pollution"

A " **Heap Pollution** " as in Non-Reifiable Types (The Java™ Tutorials > Learning the Java Language > Generics (Updated)) Why is it called that way?


Object Oriented programming and modelling

I am taking course in OOA/D this semester. In academic they teach till now about Object Oriented Programming. I have some doubts regarding this.   1. Is it true that Object Orinted programming can be done without any specific modelling like OMT.   2. What are the models available for object Oriented software development?


URL Naming Convention for with Repetitive Letter

What is a good practice to name an URL if it contains repetitive letters. For example, `/info/foossite` The two **s** looks kind of odd and if this was access point for a `Web- Service`, this could lead into misspelling. In most programming languages, we have `Camel` notation. However, as URLs are case insensitive, we don't have that luxury here. So, what is the best practice in this regard?


Managing complex relationships with Entity Framework

I'm using Entity Framework with POCO's and change tracking enabled. I started off using CASCADE DELETE relationships, but in some situations, due to cyclic or multiple-possible-cascade-paths, SQL Server prevented me from adding CASCADE DELETE... so I need to manage those deletions myself. Take for example the following situation:   * A site has many chassis   * A chassis has many cards   * A card has many ports   * A link has two ports (`PortAId` and `PortZId`) (and a port may participate in multiple links). The first 3 relationships have CASCADE DELETE, however the final (`Link`) relationship has "multiple cascade path" on the `Link.PortAId` and `Link.PortZId` attributes. Because of this, I _couldn't_ add the CASCADE DELETE relationship. * * * My **problem** is that when a port gets deleted, a foreign key constraint gets thrown because there are still `Link`'s referencing the deleted port. * * * I tried looking through the `ChangeTracker` on `SaveChanges()` for `Port`s which were deleted, and deleting their respective links; _but_ a port deleted implicitly (through CASCADE DELETE) doesn't show up in the ChangeTracker; so I have to look for cards as well, and chassis, and sites... it becomes untenable. I then tried adding `TRIGGER`s to the database, such as:               CREATE TRIGGER delete_port_links ON Ports FOR DELETE AS        DELETE FROM Links WHERE PortAId IN (SELECT Id FROM deleted) OR PortZId IN (SELECT Id FROM deleted)      ... however `FOR` triggers fire _after_ the foreign key constraint has been checked (and failed). I can't use `INSTEAD OF`, because the table has a foreign key. * * * So I'm really stuck in terms of what direction to go down to solve this. What techniques, patterns or features of EF would allow me to detect when a Port (directly or implicitly) been deleted, such that I can delete the Links as well?


libavcodec/libavformat question

I've seen this code referenced in two different places, yet I haven't seen anybody bring this up, but it seems that on line 00339 there is an empty if block and I just copied the code to compile try it out but it won't even compile cause of that.               if (frame_count >= STREAM_NB_FRAMES) {      /* no more frame to compress. The codec has a latency of a few         frames if using B frames, so we get the last frames by         passing the same picture again */     } else {      Any idea or explanation why it is like that. Is it a mistake on the author's part when copying it? What is supposed to be going on in that if block anyways?


Autosave in web development tools

I'm working on a new web based development tool (version management based on git). Usability tests showed that developers are used to manual save. I asked 15 developers that are used to work with Eclipse or Visual Studio to develop in my web based code editor. After a short mission I asked them if they feel their code is saved. They all said no, and looked for a save button, and didn't notice a "saved" label turning on and off at the top right corner. I'm wondering if auto save will be a better experience, and something developers will get used to, like in google docs?


Should I use friend classes in C++ to allow access to hidden members?

Here is my situation (a simple example). Say I have a class called `HiddenData`   Then I have another class called `StoreHiddenData`   And finaly a class called `OperateHiddenData` Here's the thing, my class called `HiddenData` has private members that I don't want to be visible to the rest of the world, but I still need classes to be able to operate on private members of this `HiddenData` class (`StoreHiddenData` and `OperateHiddenData` for example). I would like to be able to pass this object around to different classes that do different things on it. Another thing I was thinking of is to create a form of handle to these `HiddenData` objects, but I can't think of a way to use handles without using friend classes again (as to give the other classes access to a table that contains what the handles point to, without exposing it to the rest of the world as well). I was reading this question on this site just a while ago as I was researching the use of friend classes, and it has me thinking if using friends is the best way to go. If anyone has any suggestions for how to accomplish this task without the use of friend classes in C++, or if the use of friend classes is an OK OOP practice, please provide me with any suggestions. Thanks. EDIT: I figure I should add a little bit more information about my problem. For one thing, I am trying to create an API that consists of several classes that hide their functionality from the outside and only allow public functions to be accessed. On the inside I have data structures (or classes, doesn't really matter), that need to be passed around to these different classes with public functions. I don't want the outside to have access to anything inside these data structures other than being able to pass them around to functions of the API. I kind of think of it like the Windows API, where you pass around Handles to API functions, but you can't actually dissect the handles in your own code. Well I would like to do something very similar, but while remaining object oriented, and NOT passing these private data structures around by value because they will be BIG. Thanks again.


Segmentation fault with a c++ file handling program

I am learning file handling c++. This program read words from a file and inserts them in a vector alphabetically as they are entered. When I am executing this program, I am getting segmentation fault. Can someone spot the error in the program?               #include <iostream>     #include <string>     #include <vector>     #include <algorithm>          using namespace std;          int main(int argc,char *argv[])     {         if(argc!=2)         {         cerr << "Incorrect number of arguements in Usage" << endl;         return 1;         }            ifstream fin(argv[1]);              if(!fin)         {         cerr << "File " << argv[1] << " not found\n";         return 1;         }            vector <string> v;       string word;       int i;              fin >> word;         v.push_back(word);              while(fin >> word )         {                 i=0;                 while( word.compare(v[i])<0 && i<v.size() )                 i++;                      v.insert(v.begin()+i,word);         }              for(i=0;i!=v.size();i++)         cout << v[i] << "  " ;         cout << endl;              return 0;     }


Is 'lazy' the correct term for timestamp-based skipping?

(1)   * The old`make`utility looks at timestamps, and if the output is newer than the input, it skips (pointless, time-consuming) re-compilation of e.g. C files.   * The same is true for many languages and compilers. “Lazy” thumbnail generation in web aplications skips those thumbs that are newer than the source image.   * “Smart” file syncing tools do the same, looking at time stamps, to reduce transfer volume. I used to refer to this as **“lazy”**. However, looking at web citations, the term “lazy” in Computer Science seems to actually mean something different: „do something as late as possible“.   * only load that extra part when it's necessary   * initialize lazily, aka as late as needed   * only evaluate that part of the equaption, when you get to it... So is my term wrong? And what would be more correct, for all that „is-newer- based“ skip optimizations?


Preventing Liskov Substitution violation

I am reimplementing some component and noticed that the original version has a Liskov Substitution violation. It's not all that critical, though I'd like to get rid of it in the new implementation . It is however not clear to me how to do this. I have a component defining very simple value classes used by the system. This component has a DataValue interface and a dozen implementations such as NumberValue and GeoCoordinateValue. The component I'm reworking is a storage layer meant for indexing data so it can easily be queried against. This component contains a set of classes that provide storage information for a particular DataValue implementing class. This information are things such as which fields a table needs to have to contain the DataValue in question, which field should be used for sorting, and what indexes should be placed. These classes all implement some DataValueHandler interface. The LSP violation occurs for two particular methods in this DataValueHandler interface:               getWhereConditions( DataValue $dataValue )          getInsertValues( DataValue $dataValue )      The interface defines these methods take a DataValue. The implementations however expect the DataValue for which they provide information. For instance, the NumberValueHandler expects a NumberValue, and will throw an exception if it gets a GeoCoordinateValue. So how can I get rid of this? (Before anyone suggests it: putting info of some specific storage backend in DataValue is not going to happen, as this would be worse design wise then the current LSP violation.)


Scheduling a few CPU-intensive tasks

I need to schedule a small number of CPU-intensive tasks to run every so often, reading from shared data and writing to dedicated buffers. I don't necessarily want to roll my own scheduling, but am unsure if libraries like Quartz are appropriate for this small of scale. I'm using Java 8 in a server environment, but with isolated nodes and it doesn't matter if a few iterations are lost every now and then. **Problem detail:** I have 5 buffers of data of binary data to process. Before processing each buffer, I allocate an empty destination and the function writes to that destination. Each buffer needs to be processed on a different schedule with a different function, although all the functions can handle missing an iteration and calculating double on the next go. The first buffer is ~30mb and takes ~200ms to process, and needs to be processed every 500ms. The remainder are around ~6mb each and take ~50ms to process, and need to be processed every 1000ms. The processing functions must only write to the destination buffer and are stateless, but may read any of the existing buffers. The whole process will at least have its own thread, and may have multiple threads. None of this is critical, it won't be clustered, and will be maintained almost exclusively in- memory. **Example:** A fairly dumb implementation might be:               for (layer in parent.layers) {         new thread(() => {             while (true) {                 buffer = new int[layer.data.length]                 process(layer.data, buffer, parent)    // remember, this can access other layers                 layer.data = buffer                 sleep(layer.increment)             }         }     }          Running each layer on its own thread makes the processing fairly simple, so long as nothing in the middle is locked. Grabbing each layer the processing function cares about when it begins an iteration and releasing them at the end should work, since they are read-only and I'm not worried about another thread replacing the reference. **Question:**   1. Are there any issues with Timers for this kind of work? Do they provide a way to discard or wait on the previous iteration?   2. Is Quartz a viable choice, or simply absurd?   3. Can something as simple as `System.nanoTime` suffice at this precision?


Cleanest way to report errors in Haskell

I'm working on learning Haskell, and I've come across three different ways of dealing with errors in functions I write:   1. I can simply write `error "Some error message."`, which throws an exception.   2. I can have my function return `Maybe SomeType`, where I may or may not be able to return what I'd like to return.   3. I can have my function return `Either String SomeType`, where I can return either an error message or what I was asked to return in the first place. My question is: **Which method of dealing with errors should I use, and why?** Maybe I should different methods, depending on the context? My current understanding is:   * It's "difficult" to deal with exceptions in purely functional code, and in Haskell one wants to keep things as purely functional as possible.   * Returning `Maybe SomeType` is the proper thing to do if the function will either fail or succeed (i.e., there aren't different _ways it can fail_ ).   * Returning `Either String SomeType` is the proper thing to do if a function can fail in any one of various ways.


GPL and non GPL software common installer

From my vague understanding of this subject I assumed that if I make an installer for my program and it contains a GPL library my code would have to fall under GPL. However, I noticed yesterday when installing Ubuntu that its installation had checkboxes (selected by default) to install non free software. This question specifies about programming behavior and says that my program wouldn't fall under GPL as long as the library can be seem as separated programs but it does not say anything about making a common installer for the package. I saw this answer saying about common installers in StackOverflow in Portuguese and it does say about a common installer making the code fall under GPL. **If I create an installer for the library and put my non-free program that uses that library there as an option my program wouldn't fall under GPL ?**


Adding new functionality to all of shelve.Shelf's subclasses in Python

In order to avoid the overhead associated with the shelve module's `writeback` option I'm interested in putting together a shelf class that only accepts hashable values, with hashability being a proxy for immutability. So I'd like to subclass `shelve.Shelf` and override the `__set__` method. The catch is that `shelve.open` can return one of a number of different classes (e.g., `Dbfilenameshelf`), and I'd like my code to allow `shelve` this flexibility. Ideally a solution would have the following properties:   1. No need to wrap every function that `Shelf` provides, as in: `def keys(self): return self._shelf.keys()`   2. Will not break if Python adds new methods to `Shelf` or new subclasses of `Shelf`   3. Avoiding fragility, by which I mean doing something complicated that could easily trip up someone (conceivably me) who is modifying or using the code months or years down the road. An example in this context would be reassigning `Shelf.__set__`, as in `Shelf.__set__ = my_func`. To me defining a new `__getattr__` as @Winston hesitantly offers seems moderately fragile--I take it that's why he suggests it only with hesitation Less important but still desirable would be:   1. Consistent with object-oriented design principles. It seems to me that the new class here _is a_ shelf, not that it _has a_ shelf. And probably not both (it's not a shelf which contains another shelf)


strategies for dealing with machine epsilon

Say you have a situation where you divide and then multiply a float, and you need to guarantee that it survives macheps (ie multiplication output equals division input). What are known strategies for guaranteeing this? Rounding would work, but anything else?


Is it acceptable for projects to go over budget?

This question is something that's been bugging me for the past 3 months since I switched from being a freelancer to working at a Web Design firm. Our sales people often ask us something similar to the following series of questions:   * How much does it cost to program a widget   * How many hours will it take to convert this website to this software.   (Without knowing what the website currently runs)   * etc * * *   1. How can we give a quote without any information? ( **No, I can't ask for more info!** ) I have another question if a project goes over budget it's bad. Recently, I missed an entire menu when calculating the cost of transferring a website over to a new platform so the project went over budget. My boss was not happy at all, and it's my opinion that some things like this can't be avoided. 2\. What is the general practice for dealing with going over budget   and do projects like web development often go over budget? If you work at a web development/design/similar company: 3\. How does your billable hour system work? For me, we have a time tracking application that we record how many hours we spend on which project and if they are billable or internal (AKA non- billable). If don't meet xx billable hours a week we can get in trouble/fired eventually. Work you do for the company or for clients that isn't billable isn't part of this system, and we often _have_ to do internal work, so I'm wondering if any alternative systems exist. **EDIT:** Ok I am a developer at this firm not a designer :) Second, I am paid salary, but here is how management looks at it. You have 35 hours a week that you must work. You could be doing work that they bill to clients in that 35 hours and you should. If they figure out a project will take 50 hours and I take 55 hours, that 5 hours could have been spent on another project that wasn't over budget so we just "lost" money. Another example is that if I only have 1 project, that is due in two weeks and I spend a day doing internal work, some how we lost money because I wasn't working. If I worked that day, I would finish a day early and still have no work. Either way, the work is contract so we will get paid the same amount regardless of which days I work!


Kiln - Mercurial and Git limitation

According to this blog post: Kiln now supports repositories accessible from both Git and Mercurial > We decided that the awesome way would be to make Kiln fully bilingual. It > stores every repo in both formats. It automatically converts everything back > and forth, always. The translation is 1:1, reversible, and round-trippable. > Whatever you do to a Kiln repository using Git will be immediately visible > to Mercurial users and vice versa. I can't imagine that everything runs smoothly. What limitations does this have?


Why aren't we building and using parallel processors *meant* for general computation?

We all know GPUs are much faster than CPUs for a wide range of applications. When someone asks why we are not just programming for GPUs at all, one of the most common answers is that GPUs are not good for everything - i.e., they fail to do some things that CPUs do easily. Well, no wonder: after all, they are not **meant to be used for general computations**. GPUs are strongly tied to games and graphical applications, not only having specialized functions for those, but often being advertised for them. My question is: why, then, aren't we building and using processors that are **actually designed for parallel programs**?


What is the legality of making a mobile app version of an existing card or board game?

I see that the market is full of mobile apps based on card/board games. For example, do a search for "Taboo" and there are many results which are not published by Hasbro Inc. Is this legal? The top "Taboo" result says in the description that they are not associated with Hasbro--does this absolve them of infringement issues? I can think of a few games that I could make mobile versions of that could be successful, but I'm wary of publishing (and monetizing) a game based on another, especially if it has the same name. Note: I noticed this useful thread, which hints that it is legal to create such games, but that the original owner may fight to have similar games removed and might win. If I develop such a game and have to pull it down, would I be able to resubmit it after making some changes?


how does semantic versioning apply to programs without API

In http://semver.org/ —which in my perception seems to be the most widely used convention in versioning— it is recommended to increase the major version number when a change that breaks/modify the API is introduced. There are two related scenarios I don't see how to apply this guideline though:   1. What if my code doesn't offer any API? How should I version my code?   2. What if my code starts offering an API in a late stage of its development?


Learning by doing (and programming by trial and error)

How do you learn a new platform/toolkit while producing working code and keeping your codebase clean? When I know what I can do with the underlying platform and toolkit, I usually do this:   1. I create a new branch (with GIT, in my case)   2. I write a few unit tests (with JUnit, for example)   3. I write my code until it passes my tests So far, so good. The problem is that very often I do not know what I can do with the toolkit because it is brand new to me. I work as a consulant so I cannot have my preferred language/platform/toolkit. I have to cope with whatever the customer uses for the task at hand. Most often, I have to deal (often in a hurry) with a large toolkit that I know very little so I'm forced to "learn by doing" (actually, programming by "trial and error") and this makes me anxious. Please note that, at some point in the learning process, usually I already have:   1. read one or more five-stars books   2. followed one or more web tutorials (writing working code a line at a time)   3. created a couple of small experimental projects with my IDE (IntelliJ IDEA, at the moment. I use Eclipse, Netbeans and others, as well.) Despite all my efforts, at this point usually I can just have a coarse understanding of the platform/toolkit I have to use. I cannot yet grasp each and every detail. This means that each and every new feature that involves some data preparation and some non-trivial algorithm is a pain to implement and requires a lot of trial-and-error. Unfortunately, working by trial-and-error is neither safe nor easy. Actually, this is the phase that makes me most anxious: experimenting with a new toolkit while producing working code and keeping my codebase clean. Usually, at this stage I cannot use the Eclipse Scrapbook because the code I have to write is already too large and complex for this small tool. In the same way, I cannot use any more an indipendent small project for my experiments because I need to try the new code in place. I can just write my code in place and rely on GIT for a safe bail-out. This makes me anxious because this kind of intertwined, half-ripe code can rapidly become incredibly hard to manage. How do you face this phase of the development process? How do you learn-by-doing without making a mess of your codebase? Any tips&tricks, best practice or something like that?


How do you send a new command using NSTask to a unix executable file?

I'm trying to learn how to use NSTask, NSPipe, and NSFileHandler to make use of unix executable files in Xcode. I've already written a program that both renders chess and plays it against a user, so I now I want to make a chess GUI with Stockfish, which I have included in my Xcode project as a unix executable file. To this end, I've written the following program, but I've gotten stuck in sending new commands to Stockfish; that is, I can send it a command when I launch the NSTask, but I can't send it commands once the task is running. When I send these commands via Terminal, Stockfish responds perfectly, but for some reason, it ignores any commands I send it after launch (i.e. with [self sendCommandToStockfish]). If I send it a command, it simply ignores it and continues executing the original command while the input-pipe continues executing perfectly. How can I continue to send commands with NSTask after launch? Here's the code I've got so far:               //     //  AppDelegate.m     //  CommandLineToolRunner     //     //  Created by Thomas Redding on 8/28/14.     //  Copyright (c) 2014 Thomas Redding. All rights reserved.     //     #import "AppDelegate.h"     @implementation AppDelegate     - (void)applicationDidFinishLaunching:(NSNotification *)aNotification     {         // Insert code here to initialize your application              self.myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f                                                     target:self                                                   selector:@selector(timerFired:)                                                   userInfo:nil                                                    repeats:YES];              // set up task         self.task = [[NSTask alloc] init];         [self.task setLaunchPath:[[[NSBundle mainBundle] pathForResource:@"stockfish" ofType:@""] copy]];         [self.task setArguments:@[@"go infinite"]];              // set up output-pipe         [self.task setStandardOutput:[NSPipe new]];         NSNotificationCenter* notificaitonCenter = [NSNotificationCenter defaultCenter];         [notificaitonCenter addObserver:self selector:@selector(getReadData:) name:NSFileHandleReadCompletionNotification object:[[self.task standardOutput] fileHandleForReading]];         [[[self.task standardOutput] fileHandleForReading] readInBackgroundAndNotify];              // set up input-pipe         [self.task setStandardInput:[NSPipe new]];         [self.task launch];              self.frame = 0;     }          - (void) timerFired:(NSTimer *)timer {         // do stuff         self.frame++;              if(self.frame == 20) {             // write             NSLog(@"[[Sending Commands]]");             [self sendCommandToStockfish:@"stop"];             [self sendCommandToStockfish:@"position fen rnbqkbnr/8/8/8/8/8/8/RNBQKBNR w KQkq - 0 1"];             [self sendCommandToStockfish:@"go infinite"];         }     }          - (void) getReadData:(NSNotification *)notification     {         NSData *data = [[notification userInfo] objectForKey:@"NSFileHandleNotificationDataItem"];         NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];              [[notification object] readInBackgroundAndNotify];              NSLog(@"%@", response);     }          - (void)sendCommandToStockfish:(NSString *)string     {         NSLog(@"[[%@]]", string);         NSString *strWithNewLine = [NSString stringWithFormat:@"%@\n", string];         NSData *myData = [strWithNewLine dataUsingEncoding:NSUTF8StringEncoding];              @try {             NSLog(@"((START TRY))");             [[self.task.standardInput fileHandleForWriting] writeData:myData];             NSLog(@"((END TRY))");         }         @catch (NSException * e) {             NSLog(@"((ERROR))");             if ([self.task isRunning]) {                 NSLog(@"^^^");                 [self.task terminate];             }             else {                 NSLog(@"***");             }         }     }     @end      When I run this, I get the following output logged (I terminate the program on my own):               2014-09-02 15:02:18.474 CommandLineToolRunner[49999:303] Stockfish 140714 64 SSE4.2 by Tord Romstad, Marco Costalba and Joona Kiiski     2014-09-02 15:02:18.713 CommandLineToolRunner[49999:303] info depth 1 seldepth 1 score cp 85 nodes 27 nps 27000 time 1 multipv 1 pv e2e4     2014-09-02 15:02:18.714 CommandLineToolRunner[49999:303] info depth 2 seldepth 2 score cp 6 nodes 155 nps 77500 time 2 multipv 1 pv d2d4 d7d5     2014-09-02 15:02:18.715 CommandLineToolRunner[49999:303] info depth 3 seldepth 3 score cp 64 nodes 386 nps 128666 time 3 multipv 1 pv d2d4 d7d5 g1f3     2014-09-02 15:02:18.717 CommandLineToolRunner[49999:303] info depth 4 seldepth 4 score cp 25 nodes 1082 nps 216400 time 5 multipv 1 pv e2e4 e7e5 d2d4 b8c6     2014-09-02 15:02:18.724 CommandLineToolRunner[49999:303] info depth 5 seldepth 5 score cp 53 nodes 3129 nps 284454 time 11 multipv 1 pv b1c3 g8f6 d2d4 d7d5 g1f3     2014-09-02 15:02:18.729 CommandLineToolRunner[49999:303] info depth 6 seldepth 6 score cp 26 nodes 4702 nps 313466 time 15 multipv 1 pv e2e4 e7e5 d2d4 g8f6 b1c3 b8c6     2014-09-02 15:02:18.732 CommandLineToolRunner[49999:303] info depth 7 seldepth 7 score cp 58 nodes 6866 nps 343300 time 20 multipv 1 pv e2e4 d7d5 e4e5 b8c6 d2d4 e7e6 f1b5     2014-09-02 15:02:18.754 CommandLineToolRunner[49999:303] info depth 8 seldepth 8 score cp 12 nodes 14656 nps 396108 time 37 multipv 1 pv e2e4 d7d5 e4d5 g8f6 d2d4 d8d5 b1c3 d5a5     2014-09-02 15:02:18.791 CommandLineToolRunner[49999:303] info depth 9 seldepth 11 score cp 33 nodes 24157 nps 402616 time 60 multipv 1 pv e2e4 d7d5 e4e5 c7c5 d2d4 c5d4 d1d4 b8c6 f1b5 d8a5 b1c3 a5b5 c3b5 c6d4 b5d4     2014-09-02 15:02:18.807 CommandLineToolRunner[49999:303] info depth 10 seldepth 14 score cp 28 nodes 44269 nps 465989 time 95 multipv 1 pv e2e4 e7e5 b1c3 b8c6 g1f3 f8c5 c3a4 d7d6 a4c5 d6c5     2014-09-02 15:02:18.839 CommandLineToolRunner[49999:303] info depth 11 seldepth 15 score cp 41 nodes 75424 nps 593889 time 127 multipv 1 pv e2e4 e7e5 b1c3 b8c6 g1f3 f8c5 f3e5 c5f2 e1f2 c6e5 d2d4     2014-09-02 15:02:19.002 CommandLineToolRunner[49999:303] info depth 12 seldepth 16 score cp 28 nodes 254305 nps 879948 time 289 multipv 1 pv g1f3 d7d5 e2e3 b8c6 d2d4 c8g4 f1b5 g8f6 e1g1 a7a6 b5c6 b7c6     2014-09-02 15:02:19.042 CommandLineToolRunner[49999:303] info depth 13 seldepth 16 score cp 34 nodes 309418 nps 937630 time 330 multipv 1 pv g1f3 d7d5 e2e3 e7e6 d2d4 g8f6 f1d3 f8e7 e1g1 b8c6 c1d2 e8g8 b1c3     2014-09-02 15:02:19.224 CommandLineToolRunner[49999:303] info depth 14 seldepth 18 score cp 22 nodes 524342 nps 1024105 time 512 multipv 1 pv e2e4 e7e5 b1c3 b8c6 g1f3 g8f6 f1b5 f8b4 e1g1 e8g8 b5c6 d7c6 f3e5 d8e7 d2d4 b4c3 b2c3 f6e4     2014-09-02 15:02:19.603 CommandLineToolRunner[49999:303] info depth 15 seldepth 19 score cp 24 nodes 1002076 nps 1125928 time 890 multipv 1 pv g1f3 d7d5 d2d4 g8f6 c1f4 b8c6 e2e3 c8f5 f1d3 f5d3 d1d3 e7e6 d3b5 d8c8 b1c3 a7a6 b5a4     2014-09-02 15:02:19.769 CommandLineToolRunner[49999:303] info depth 16 seldepth 19 score cp 24 nodes 1213245 nps 1148906 time 1056 multipv 1 pv g1f3 d7d5 d2d4 g8f6 c1f4 b8c6 e2e3 c8f5 f1d3 f5d3 d1d3 e7e6 d3b5 d8c8 b1c3 a7a6 b5a4     2014-09-02 15:02:20.311 CommandLineToolRunner[49999:303] info depth 17 seldepth 20 score cp 22 nodes 1878116 nps 1174556 time 1599 multipv 1 pv g1f3 d7d5 d2d4 e7e6 c1f4 f8d6 f4d6 c7d6 b1c3 g8f6 e2e3 b8c6 f1d3 e8g8 e1g1 c8d7 a2a3 a7a6     2014-09-02 15:02:20.471 CommandLineToolRunner[49999:303] [[Sending Commands]]     2014-09-02 15:02:20.471 CommandLineToolRunner[49999:303] [[stop]]     2014-09-02 15:02:20.472 CommandLineToolRunner[49999:303] ((START TRY))     2014-09-02 15:02:20.472 CommandLineToolRunner[49999:303] ((END TRY))     2014-09-02 15:02:20.472 CommandLineToolRunner[49999:303] [[position fen rnbqkbnr/8/8/8/8/8/8/RNBQKBNR w KQkq - 0 1]]     2014-09-02 15:02:20.472 CommandLineToolRunner[49999:303] ((START TRY))     2014-09-02 15:02:20.473 CommandLineToolRunner[49999:303] ((END TRY))     2014-09-02 15:02:20.473 CommandLineToolRunner[49999:303] [[go infinite]]     2014-09-02 15:02:20.473 CommandLineToolRunner[49999:303] ((START TRY))     2014-09-02 15:02:20.473 CommandLineToolRunner[49999:303] ((END TRY))     2014-09-02 15:02:20.823 CommandLineToolRunner[49999:303] info depth 18 seldepth 20 score cp 23 nodes 2495624 nps 1182760 time 2110 multipv 1 pv g1f3 d7d5 d2d4 e7e6 c1f4 f8d6 e2e3 g8f6 f1e2 e8g8 e1g1 b8c6 f3e5 c8d7 b1c3 a7a6 a2a3 c6e5 d4e5     2014-09-02 15:02:21.756 CommandLineToolRunner[49999:303] info depth 19 currmove d2d4 currmovenumber 5     2014-09-02 15:02:21.951 CommandLineToolRunner[49999:303] info depth 19 currmove d2d3 currmovenumber 6     2014-09-02 15:02:21.960 CommandLineToolRunner[49999:303] info depth 19 currmove c2c3 currmovenumber 7     2014-09-02 15:02:21.966 CommandLineToolRunner[49999:303] info depth 19 currmove f2f3 currmovenumber 8     2014-09-02 15:02:22.010 CommandLineToolRunner[49999:303] info depth 19 currmove b2b4 currmovenumber 9     2014-09-02 15:02:22.015 CommandLineToolRunner[49999:303] info depth 19 currmove g1h3 currmovenumber 10     2014-09-02 15:02:22.022 CommandLineToolRunner[49999:303] info depth 19 currmove a2a3 currmovenumber 11     2014-09-02 15:02:22.029 CommandLineToolRunner[49999:303] info depth 19 currmove f2f4 currmovenumber 12     2014-09-02 15:02:22.036 CommandLineToolRunner[49999:303] info depth 19 currmove g2g4 currmovenumber 13     2014-09-02 15:02:22.037 CommandLineToolRunner[49999:303] info depth 19 currmove b2b3 currmovenumber 14     2014-09-02 15:02:22.044 CommandLineToolRunner[49999:303] info depth 19 currmove c2c4 currmovenumber 15     2014-09-02 15:02:22.086 CommandLineToolRunner[49999:303] info depth 19 currmove h2h3 currmovenumber 16     2014-09-02 15:02:22.091 CommandLineToolRunner[49999:303] info depth 19 currmove g2g3 currmovenumber 17     2014-09-02 15:02:22.095 CommandLineToolRunner[49999:303] info depth 19 currmove a2a4 currmovenumber 18     2014-09-02 15:02:22.098 CommandLineToolRunner[49999:303] info depth 19 currmove b1a3 currmovenumber 19     2014-09-02 15:02:22.101 CommandLineToolRunner[49999:303] info depth 19 currmove h2h4 currmovenumber 20     2014-09-02 15:02:22.107 CommandLineToolRunner[49999:303] info depth 19 seldepth 23 score cp 17 upperbound nodes 4113455 nps 1211621 time 3395 multipv 1 pv g1f3 d7d5 d2d4 g8f6 c1f4 c8f5 e2e3 e7e6 f1d3 f5d3 d1d3 b8c6 e1g1 f8d6 f4d6 c7d6 b1c3     info depth 19 currmove g1f3 currmovenumber 1     2014-09-02 15:02:22.410 CommandLineToolRunner[49999:303] info depth 19 currmove e2e4 currmovenumber 2     2014-09-02 15:02:23.133 CommandLineToolRunner[49999:303] info depth 19 currmove b1c3 currmovenumber 3     info depth 19 currmove d2d4 currmovenumber 4     info depth 19 currmove e2e3 currmovenumber 5     info depth 19 currmove d2d3 currmovenumber 6     info depth 19 currmove c2c3 currmovenumber 7     info depth 19 currmove a2a3 currmovenumber 8     info depth 19 currmove c2c4 currmovenumber 9     2014-09-02 15:02:23.158 CommandLineToolRunner[49999:303] info depth 19 currmove b2b4 currmovenumber 10     info depth 19 currmove f2f3 currmovenumber 11     info depth 19 currmove g2g4 currmovenumber 12     2014-09-02 15:02:23.159 CommandLineToolRunner[49999:303] info depth 19 currmove h2h3 currmovenumber 13     info depth 19 currmove a2a4 currmovenumber 14     info depth 19 currmove g1h3 currmovenumber 15     info depth 19 currmove b1a3 currmovenumber 16     info depth 19 currmove b2b3 currmovenumber 17     info depth 19 currmove f2f4 currmovenumber 18     info depth 19 currmove g2g3 currmovenumber 19     info depth 19 currmove h2h4 currmovenumber 20     2014-09-02 15:02:23.160 CommandLineToolRunner[49999:303] info depth 19 seldepth 23 score cp 27 nodes 5442993 nps 1223969 time 4447 multipv 1 pv e2e4 e7e5 b1c3 b8c6 g1f3 g8f6 f1c4 f8c5 d2d3 a7a6 e1g1 e8g8 a2a3 d7d6 b2b4 c5a7 c1e3 a7e3 f2e3     info depth 20 currmove e2e4 currmovenumber 1


Why does the Perl community have such a bad reputation?

I'm still fairly new to programming. I spend most of my time in Ruby, and I'm discovering a certain fondness for playing with regular expressions. That being said, I'm considering taking a look at Perl, just as a hobby. However, I've heard a lot about the Perl community, and none of it good. I've heard the community described as extremely elitist and resistant to inexperienced programmers. Is this true? If it is, why is that the case?


Is it easier to write robust code in compiled, strictly-typed languages?

I'd like to read the opinion of experts on whether compiled, strictly-typed languages help programmers write robust code easier, having their backs, checking for type mismatches, and in general, catching flaws in compile time that otherwise would be discovered in runtime ? Has unit testing in loosely typed, interpreted languages need to be more thorough because test cases need to assess things that in a compiled languages wouldn't simply compile ? Need the programer in compiled, strictly-typed need to write less code since he/she doesn't have to constantly check for correct types ( instance of operator ) since the compiler catches those things ( the same applying to misspelled variable names or uninitiated variables ) ? **NOTE: by strictly typed language I mean languages that force you to declare variables and assign a type to them in order to be able to use them, and once a variable is declared, you cannot change its type or assign incompatible type values.**               int myInt = 0;     String myString = "";     myInt = myString; // this will not fly in a strictly typed language     myInte = 10;   // neither will this ( myInte variable doesn't exist )


Starting new project with TDD

I'm studying TDD and I read that it also helps you to define the design of the app, correct? So I decided to start creating a new project to help me understand it better. I want to create a simple user registration system that will ask for its name, email address, country (will pick one from a list) and phone number. So the question is... I created a new solution in VS 2010, added a new Test project and I just don't know what tests to write! Since it will help me define the design, what tests could I write here? Thanks for any help!


Is it a good idea to design an architecture thinking that the User Interface classes can be replaced by a command line interface?

In Code Complete page 25, it's said that it's a good idea to be able to easily replace the regular user interface classes by a command line one. Knowing its advantages for testing, what about the problems it may bring? Will this extra work really pay off for web and mobile projects? What about small and medium projects; do the same rules apply? What if it makes your design more complex?


Using a GPLv3 library in a freemium business model

I read several related questions about the use of GPLv3 in a commercial app but they don't say anything about a freemium app. I would like to use a GPLv3 library in two apps, a free one (with limited features) and a paid one. Basically, the free app will allow to use the library without limitations, and the paid one will include it as well as other unrelated features. I will release the free app under GPLv3 but do I need to release the paid one under the same license? I don't want to release the whole source code of my paid app (for obvious reasons), as the other features don't use the library in any way. It would just be more convenient for users who bought the full version to have all features in a single app instead of putting the library in a separate one.


How Do I Become a More Autonomous and Self-Sufficient Programmer?

The single largest factor in what is holding me back from being a stellar developer is my reliance on others. I feel like I ask too many questions because I fear the consequences of breaking everything and holding everyone back. So I'm overly cautious by asking so many questions that I basically get the answers after enough questioning. I've recognized that's bad but I want to stop it. Part of it comes that there are times where I simply don't know the code (either it's a branch I've never worked with or it's a brand new product), but I want to rely on others less. To preface, these kinds of questions are not the ones about generic patterns or languages: usually my questions revolve around how we do code at our company, and how we get things to work in our ecosystem. I want to be able to take specs and roll with them without having to feel like I need to get help every step of the way. Is this normal? Have you been through this, and if so, how did you get over it?


Is it frowned upon to release works in progress to github/sourceforge/bitbucket/etc?

Long story short, I've spent the last two years in an entirely new career, transitioning from academia to a data analyst role (working towards a data scientist). Before starting at my current company, I knew next to nothing about coding, save for teaching myself SQL for a few hours per week over a couple of months. Besides SQL, I have since become conversant in Perl, have used PHP a bit here and there, and have made some headway into learning other languages (primarily Java and C). So, I still have a lot of catch-up work to do. In order to teach myself things, I've built a few side projects--a lot more sophisticated than `"Hello World, my name is $name."`, but not as complicated as, say, Minecraft or a device driver. I'd like to release the code for them in order to learn from constructive feedback and to build a portfolio to sit alongside my resume. However, a lot of these things are works in progress and, to be honest, I feel some trepidation at putting code out there for all to see that's not completely, 100% "done" and polished. Am I worrying over nothing? If not, is there some minimal polish threshold a project should have before releasing it as open source?


Good practice about Javascript referencing

I am fighting about a web application script optimization. I have an ASP.NET web app that reference jQuery in the master page, and in every child page can reference other library or JavaScript extension. I would like to optimize the application with YUI for .NET. The question is, I should put all the libraries reference in the master page or to compress all the JavaScript code in a single file, or I should create a file for every page that contains only the code useful to the page? Is there any guidance to follow?


Should I use a formal grammar for my interpreted scripting language

I have a scripting engine I just published as an open source project. It's been sitting on my harddrive waiting for about a year. My engine of course isn't complete in any way, but it does work for simple scripts. It has a javascript-ish feel to it, but I don't wish to abide by the ECMA spec or anything. Now, the big thing I'm working on is improving code quality while leaving the language working as it is(which I have a few regression tests to "prove"). It doesn't have a formal grammar at all and works like so:   1. Preprocess/Tokenize. At this point it removes whitespace and cuts everything into "tokens", which is basically just a structure containing a string and a rough "hint" as to what the token is (Number, Identifier, Operation, etc) and some debugging info such as line number   2. A ScriptingEngine class which takes the list of tokens and actually parses them and executes them   3. An "ExpressionEvaluator" class which will take a subset of the tokens list and build a specific tree of operations, values, and then execute operations and such and collapse the tree down into a single value My engine has the goals of being portable(works everywhere .Net does) and self-contained. So far, this "works", but the code is terrible and I'm pretty sure that I'm going about it the wrong way. I'm wondering if a formal grammar and everything that goes with it might help Some benefits I've heard of being more formal with grammar   * Unambiguous specification of the language   * Easier to maintain/change   * More traditional/Bigger community support?  And some of the disadvantages   * Some languages can be very difficult to reduce to a formal grammar, ie Perl.   * A learning curve for someone not in the know(ie, me)    * Generally rely on tools such as yacc and ANTLR, which introduce another step in your workflow and/or add dependencies(which I'd like to avoid) Although this project is in .Net, it could equally apply to any other implementing language. Should I use a formal grammar? Can someone expand on the pros/cons of both sides?


What's the best way to show some of my code during an interview?

I realize that there are already a couple of questions about this, but they mostly are about _if_ you should bring code to the interview, which is not the case here. I have a job interview (at a startup) coming up next week and they _requested_ to bring some code to the interview. I have two smaller open-source projects and a closed-source Android app, which I mentioned (and linked) in my skill sheet I sent along, so I wanted to show them some code of those projects. It's my first job after graduating, so I don't have any sources from previous employments and there won't be any issues regarding "spying", licensing issues, confidential code etc. All the code is completely mine and written by me. I guess I have pretty much three options: print some interesting parts of the code on paper or have everything on my tablet or laptop to show. The latter two have the advantage that I can bring all my projects and basically show them everything they want to see. However you can't directly make notes/underline stuff etc. as if I had printed it out and it's less convenient than just handing out paper. What's the best way to handle this professionally and do this as hassle-free as possible? I currently tend to print out some of the parts that I think are both interesting and well written, but have everything on my tablet in case they want to see more.


How do these technologies go together?

* Ruby on Rails    * Twitter Bootstrap    * Html5Boilerplate    * Backbone.JS or Knockout.JS I sort of understand what each one is individually, but my understanding isn't strong enough to understand whether some of them sort of overlap in functionality and whether any subset of that list contains items you wouldn't use together because they play similar roles. I'm fairly clear on RoR-- it's mainly the latter three that I'm not sure how they play together.


How to plan/manage multi-platform (mobile) products?

Say I've to develop an app that runs on iOS, Android and Windows 8 Mobile. Now all three platforms are technically in different program languages. The only 'reuse' that I can see is that of the boxes-and-lines drawings (UML :) charts and nothing else. So how do companies/programmers manage the variation of the same product across different platforms especially since the implementation languages differ? It's 'easier' in the desktop world IMO given the plethora of languages and cross-platform libraries to make your life easier. Not so in the mobile world. More so, product line management principles don't seem to be all that applicable - what is same and variant doesn't really matter - the application is the same (conceptually) and the implementation is variant. Some difficulties that come to mind:   * **Bug Fixing** : Applications maybe designed in a similar manner but the bug identification and fixing would be radically different. A bug on iOS may/may-not be existent for that on Android. Or a bug fix approach on one platform may not be the same on another (unless it's a semantic bug like `a!=b` instead of `a==b` which would require the same 'approach' to fixing in essence   * **Enhancements** : Making a change on one platform would be radically different than on another   * **Code-Design Divergence** : They way the code is written/organized, the class structures etc., could be very different given the different implementation environments - leading to further reuse of the (above) UML models. There are of course many others - just keeping the development in sync and making sure all applications are up to the same version with the same set of features etc. Seems the effort is 3x that of a single application. So how exactly does one manage this nightmarish situation? Some thoughts:   * Split application to client/server to minimize the effect to client side only (not always doable)   * Use frameworks like Unity-3D that could take care of the cross-platform problem (mostly applicable to games and probably not to other applications etc.) Any other ways of managing a platform line? What are some proven approaches to managing/taming the effects?


Carpool logical architecture

I'm designing a carpool system (drivers can publish their routes and passengers can subscribe to them) with WebServices(axis2) and Android clients (ksoap2). I have been having problems with the logical architecture of the system and I wondered if this architecture is fine. ![enter image description here](http://i.stack.imgur.com/mmyUf.png) And another question: for that architecture (if it is ok), how would be the packages structure? I suppose something like that: (In android)   `package org.carpool.presentation`   *All the activities here (and maybe mvc pattern) (In the server)   `package org.carpool.services`   *Public interfaces (for example: register(User user), publishRoute(Route route) ) `package org.carpool.domain`   *Pojos (for example: User.java, Route.java, etc) `package org.carpool.persistence`   *Dao Interface and implementation (jdbc or hibernate)


There's a most performant way to check that a collection has exactly 1 element?

I came up with this solution :               if (Take(2).Count() == 1)      is there any more performance solution (or better syntactical sugar) to do this check ? I want a performance way because this will be an extension used on Linq To Entites and Linq to Objects. I'm not using `SingleOrDefault` because that will throw and exception if it has more than 1 element. Based on @Telastyn answer I came up with the following:               public static bool HasOne<T>(this IEnumerable<T> enumerable) {         var enumerator = enumerable.GetEnumerator();         return enumerator.MoveNext() && !enumerator.MoveNext();     }      another implementation (slighly slower but 100% sure will work effectivly on Linq to Entities) would be :               public static bool HasOne<T>(this IEnumerable<T> enumerable) {         return !enumerable.FirstOrDefault().Equals(default(T)) && !enumerable.Skip(1).Any();     }      I'm not sure if the `MoveNext` one works with IQueryable on Linq to Entites. (any takers? I don't know how to test that) After some test, `Take(2).Count() == 1`; is the fastest. :S


How to develop complex applications

I want to know the approach in developing big complex application regardless of which programming language to use. I want to know how developers make such big applications such as internet banking, API's and big database management application. How should one approach to make such applications. I have only 1 year programming experience so far and I work as a freelancer so when I saw such applications lots of questions came in my mind. How to understand the basic need of information technology. What actually it is? How it can be useful for common people of small towns. I want everyone to make use of technology no matter they are educated or not, rich or not. Please post some suggestions.


Is it good practice to return an array of objects?

If I have an ItemContainer class that contains, for example, items in an order, where each item is an Item object; is it best to have a method like:               ItemContainer->getItems()       that returns an array containing Item objects, or is it better practice to do something like:               ItemContainer->getItem($itemNo)       which returns a single item object for that item number, and forgoes the array. I realise this may be a trivial question or simply one of preference, but I'd like my app to adopt best practices from the start and I'm unsure which way to proceed. I'm writing in PHP, but I figured this pretty much applies to any OOP language.


What to bring to a programming interview?

I have just completed my Master's degree in Computer Science and have gotten my first job interview as a developer. I do not have much experience in large scale development projects, but I am hoping my university education counts for something. I am wondering, what materials should I bring that would impress my interviewers? What do most interviewers expect, especially from a new graduate? **Edit: The job interview went OK, except I forgot my pants. Thanks for all the great advice!


What are the relative merits for implementing an Erlang-style "Continuation" pattern in C#

What are the relative merits ( _or demerits_ ) for implementing an Erlang- style "Continuation" pattern in C#. I'm working on a project that has a large number of `Lowest` priority threads and I'm wondering if my approach may be all wrong. It would seem there is a reasonable upper limit to the number of long-running threads that any one Process 'should' spawn. With that said, I'm not sure what would signal the tipping-point for too many thread or when alternate patterns such as "Continuation" would be more suitable. In this case, many of the threads do a small amount of work and then sleep until woken to go again ( _Ex. Heartbeat, purge caches, etc..._ ). This continues for the life of the Process.


What are some best practices for cookie based web authentication?

I'm working on a small side project using CGI and Python (scalability is not an issue and it needs to be a VERY simple system.) I was thinking of implementing authentication using cookies, and was wondering if there were any established best practices. When the user successfully authenticates, I want to use cookies to figure out who is logged on. What, according to the best practices, should be stored in such a cookie?


When do we need to apply a software development methodology?

There are many software development methodologies - SCRUM, agile, XP, etc. - and they all have there advantages and disadvantages I suppose. But when do we really need to apply them? Surely they are not necessary for small 1-man projects, but for large 50+ teams you can most certainly not go about ad-hoc:ing the whole thing. So what's the line for when to use and when to not use such a methodology, if there indeed is one?