How to deal with multiple output modes of multiple types?

_Note: The business domain being a bit complicated to explain, I replaced the names of actual classes by more illustrative examples._ I'm writing an application in which the business layer returns a set of `Pet`s: either a `Cat` or a `Dog`:               class Pet(metaclass=ABCMeta): # Pet is abstract.         ...         getName(self):         ...          class Dog(Pet):         ...          class Cat(Pet):         ...      I want to display those pets using a given format which is determined by the user. For example, the user may ask to show only the name of each pet, or obtain a JSON representation, or have a rich representation which is biased towards cats, i.e. it _displays much more information about cats than about dogs_. In the presentation layer, I have an abstract class `Output` with an abstract method which outputs the pets, and then I have concrete implementations of every type of output: a `class NameOutput(Output)`, a `class JsonOutput(Output)`, or a `class RichOutput(Output)`. The first two ones are easy: they just use the abstract `Pet` class, and don't care if it's a dog or a cat. The problem is the last class, since the logic is different for a dog than for a cat.               class Output(metaclass=ABCMeta): # Output is abstract.         generateOutput(self):             for pet in self.pets:                 yield self.processPet(pet)              @abstractmethod         processPet(self, pet):             pass          class NameOutput(Output):         ...          class JsonOutput(Output):         ...          class RichOutput(Output):         ...         processCat():             ...         processDog():             ...      Determining the type of pet during the execution and calling different methods for each pet feels ugly. Also, when a maintainer would need to add `class Hamster(Pet)`, he will learn the hard way that he also should create an additional method in `RichOutput(Output)`. On the other hand, moving the output logic to the pets themselves doesn't look right either: what if I need to create an additional display format? What are my options? How is this problem usually solved?


Should I group all of my .js files into one large bundle?

One of the difficulties I'm running into with my current project is that the previous developer spaghetti'd the javascript code in lots of different files. We have modal dialogs that are reused in different places and I find that the same .js file is often loaded twice. My thinking is that I'd like to just load all of the .js files in _Layout.cshtml, and that way I know it's loaded once and only once. Also, the client should only have to download this file once as well. It should be cached and therefore shouldn't really be a performance hit, except for the first page load. I should probably note that I am using ASP.Net bundling as well and loading most of the jQuery/bootstrap/etc from CDN's. Is there anything else that I'm not thinking of that would cause problems here? Should I bundle everything into a single file?


How did they count the number of lines of code executed at runtime?

There was a PC game released in 2001 called Black & White by Lionhead studios in which there was a lengthy statistics page which updated in real-time. There were stats such as how many people killed, how much money you've earned, etc... but the really puzzling one was Total lines of code executed, which was into the billions and counting. How would they have known this, how would they have calculated this at runtime? Did they make it up?


Tracking hours on a project

Other than the following, are there any helpful (to programmers) reasons to track hours/time on a project down to the "accurate number of hours per week" level? Reasons:   * Beneficial to see how estimates vs. actuals came out (to improve estimation)   * Management said so (for contractual or business reasons) This is a bit tongue in cheek, but my personal preference has always been to track at an abstracted level. For example: a person is either "full time" (defined as either 40hrs/week or a less intense 32hrs/week) or part time, or they spend a few hours here and there on the project. It seems (as a manager) that chasing any kind of accurate number for actual hours is much like measuring the length of a coastline. The more accurate you try to get, the more confounding it is. That said, I'd appreciate any insights on benefits to programmers. thanks!


What is the advantage of learning about and understanding compiler construction?

I'm a undergraduate in my 3rd year of a Software Engineering degree. From this year on, my university has introduced a new course called 'Compiler Constructions', which teaches you the basics of the theory of building a compiler. What would be the real world advantage for a Software Engineer of learning about compiler construction?


What is the equivalent of functions and methods in SQL?

In language like C or Java, there are things like functions/methods to modularize and abstract stuff. What is there in SQL, specifically for Oracle? I've seen people talking about using views to reduce the complexity in various blogs but there is only so much that can be done with a view. (For example, a bind variable cannot be passed as a runtime parameter to a view). In tools like Oracle Reports the query sometimes gets very awkward running several hundreds of lines. I was wondering what sort of techniques people use to manage the complexity of their SQL? What are the equivalents of functions and methods in SQL to keep SQL from becoming extremely complex?


How to specify WIP limits in Kanban?

Consider a typical Kanban board: Input, Analysis, Dev Ready, Development, Build Ready, Test, Release Ready How to specify WIP limits for each column? any formula?


Is there a common denominator of all Smalltalk implementations?

In most languages, there is standard libraries. And this is foundation, common denominator of them. Applications can be written with guarantee of the denominator. What's the core of Smalltalk?


Are there any FOSS operating systems available that conform to NASA's JPL coding standards?

I, like many others, have been completely enamored with the recent successful landing of Mar's Curiosity rover. After reading a couple of articles, and following a few links, I've found a couple C based coding standards that NASA JPL uses to formalize their code and protect it from error. (See here and here.) This has me curious. Are there any open-source operating systems available that adhere to these coding standards that are available for common architecture, such as x86, x64 or possibly ARM?


Provide multiple SendCompleted callbacks to SmtpClient

I have an `Email` class that has a `Send` method that optionally takes an `SmtpClient` and sends an email asynchronously using `SendAsync`. If no `SmtpClient` is supplied to this method, it instantiates a default `SmtpClient` and uses that to send the email. Inside the `Send` function, I provide a `SendCompleted` callback which disposes of the `MailMessage` and the default `SmtpClient` if one was not supplied to the method. **So when I am supplying the`SmtpClient`, how do I go about disposing it?** I can't dispose of it inside `Send` because it may be used for sending other emails, plus I figure it's the responsibility of the thing that instantiated the passed in `SmtpClient` to dispose of it again. Is it possible to add multiple `SendCompleted` callbacks to the `SmtpClient` that run after each other?


Except garbage collector, what else makes Java a non real time programming language

Except the garbage collector, what are some other features in Java that make it unsuitable for real time programming? On the net, whenever Java vs C++ is discussed with regards to real time programming, it is always the garbage collector that is mentioned. Is there anything else?


PayPal proof of payment - is there a need to store it at our server?

I am developing an iPhone app, which I am integrating with PayPal. I did it successfully using PayPal library. I am testing it on sandbox mode. When I transfer money from one account to the other account, it displays a message "send to server for verification". Is there a real need to store this PayPal transaction id and other details on our server?


Thoughts on type aliases/synonyms?

I'm going to try my best to frame this question in a way that doesn't result in a language war or list, because I think there could be a good, technical answer to this question. Different languages support type aliases to varying degrees. C# allows type aliases to be declared at the beginning of each code file, and they're valid only throughout that file. Languages like ML/Haskell use type aliases probably as much as they use type definitions. C/C++ are sort of a Wild West, with `typedef` and `#define` often being used seemingly interchangeably to alias types. The upsides of type aliasing don't invoke too much dispute:   * It makes it convenient to define composite types that are described naturally by the language, e.g. `type Coordinate = float * float` or `type String = [Char]`.   * Long names can be shortened: `using DSBA = System.Diagnostics.DebuggerStepBoundaryAttribute`.   * In languages like ML or Haskell, where function parameters often don't have names, type aliases provide a semblance of self-documentation. The downside is a bit more iffy: aliases can proliferate, making it difficult to read and understand code or to learn a platform. The Win32 API is a good example, with its `DWORD = int` and its `HINSTANCE = HANDLE = void*` and its `LPHANDLE = HANDLE FAR*` and such. In all of these cases it hardly makes any sense to distinguish between a HANDLE and a void pointer or a DWORD and an integer etc.. Setting aside the philosophical debate of whether a king should give complete freedom to their subjects and let them be responsible for themselves or whether they should have all of their questionable actions intervened, could there be a happy medium that would allow the benefits of type aliasing while mitigating the risk of its abuse? As an example, the issue of long names can be solved by good autocomplete features. Visual Studio 2010 for instance will alllow you to type DSBA in order to refer Intellisense to System.Diagnostics.DebuggerStepBoundaryAttribute. Could there be other features that would provide the other benefits of type aliasing more safely?


How to stay focused on learning a language with so many other possibilites?

What do you do to stay focused when learning a new language with so many other interesting languages out there?


Best source control system for busy web development team

Having had a number of instances of merge problems and other difficulties with a large Subversion repository and a team of 10+ developers I'm considering whether SVN is the right tool and what else to consider? Primary system being managed is a large PHP web application with release cycles averaging 2-3 weeks apart and 4+ concurrent projects in active development at any time. Is subversion the right system or should we adopt Git, Mercurial or something else?


MVC sending information from view to controller

I am using the MVC pattern. Lets say I want to create a new object and add it to my database. Where is it better to create the new object: View:               Boo boo = new Boo("awesomness");     Controller.AddDB(boo);      Controller:               public void AddDB(string name)     {        Boo boo = new Boo(name);        addtodb(boo);     }


Controller JSP - no view

Most people say do not use JSPs. But what if I have a JSP that does not show anything, it only acts as a controller? Why would I do that? Because we do not need to redeploy complete webapp to make a small but significant change in a servlet -> instead can just put my new JSP in the JBoss _tmp_ folder till we do a full deploy. This controller JSP will of course include / redirect to other view JSPs for final rendering. Question what are the downsides of doing this? If we already have it in our application (it's been working for the last 8 years before I joined); should we keep it as it works or are there any compelling reasons to change it to a regular servlet? Note: the JSPs in question are not the only controller, rather they do some of the processing for certain use cases


How and why to decide between naming methods with "get" and "find" prefixes

I always have trouble figuring out if I should name a certain method starting with `getSomething` versus `findSomething`. The problem resides in creating _helpers_ for poorly designed APIs. This usually occurs when getting data from an object, which requires the object as a parameter. Here is a simple example:               public String getRevision( Item item ) {         service.load( item, "revision" );         // there is usually more work to do before getting the data..         try {             return item.get_revision();         }         catch( NotLoadedException exception ) {             log.error( "Property named 'property_name' was not loaded", exception );         }         return null;     }      How and why to decide between naming this method as `getRevision()` or `findRevision()`?


Referential integrity in a database where tuples are not physically deleted

Many modern Relational Database Management Systems automatically support referential integrity, i.e. when you try to delete a tuple which has a reference (in the form of foreign key, for example), the DBMS doesn't complete the operation and brings an error. Consider a database where every table has an attribute, which indicates if a tuple is deleted or not. So no data is actually deleted from the database, but is marked as deleted instead. If a tuple is marked as deleted, all its references need to be marked as deleted too or an error should occur. How can this be supported? Is performing additional checks (programmatically or with triggers) before deleting a tuple the only way to have referential integrity? Are there any accepted practices or algorithms? Edit: This flag is mostly used for statistics, and partially for data recovery after a long period of time. It is filter with a special meaning, and right now when queries are made, referential integrity is checked right in the query, which is extremely error prone and not reliable at all.


Why is binary search,which needs sorted data, considered better than linear search?

I have always heard that linear search is a naive approach and binary search is better than it in performance due to better asymptotic complexity. But I never understood why is it better than linear search when sorting is required before binary search? Linear search is `O(n)` and binary search is `O(log n)`. That seems to be the basis of saying that binary search is better. But binary search requires sorting which is `O(n log n)` for the best algorithms. So binary search shouldn't be actually faster **as** it requires sorting. I am reading CLRS in which the author implies that in insertion sort instead of using the naive linear search approach it is better to use binary search for finding the place where item has to be inserted. In this case this seems to be justified as at each loop iteration there is a sorted list over which the binary search can be applied. But in the general case where there is no guarantee about the data set in which we need to search isn't using binary search actually worse than linear search due to sorting requirements? Are there any practical considerations that I am overlooking which make binary search better than linear search? Or is binary search considered better than linear search without considering the computation time required for sorting?


Will Python 3.0's backwards-incompatibility affect adoption?

I visited Slashdot this morning to find out that Python 3.0 has been released. I know C# and Perl, but have wanted to learn Python for some time, especially after I saw its ease of use to create useful tools, not to mention its use in game scripting. My question is, how does the intentionally backwards-incompatible release of Python 3.0 affect adoption, and should I learn Python 2? Or should I take the dive and learn Python 3.0 first, and wait for the libraries to be ported?


How many bits' address is required for a computer with n bytes of memory?

How many bits of address is required (for the program counter for example) in a byte-addressed computer with 512 Mbyte RAM? What does the formula look like? How is this connected with the fact that 32 bits can address no more than 4 GB RAM?


Dealing with similar objects with different method signatures

I am fairly new to OO design and have problems with the design of some software and looking for a pattern or a combination of patterns that could help me solving my problem. I have a type that has a collection of different geometric shapes (say lines, rectangles, and cubes). I actually even have composites of these shapes. Each shape has one or more values. A value is a coordinate (between one-dimensional for lines and three-dimensional for cubes). All types of shapes have two methods that are essential. A method for adding values and a method for getting all values of a shape. E.g. `Cube.AddValue(new Value3D{X=4,Y=7,Z=11})` or `Line.AddValue(new Value1D{X=42})` respectively `Cube.GetValues()` would return a collection of `Value3D` and `Line.GetValues()` would return a collection of `Value1D`. Since these methods have fundamentally different signatures, I can't just derive from a single interface to store all of these different objects in one collection. Splitting the collection into multiple separate collections, one for each type would be possible, but not desirable since they belong together (domain wise). I've considered using three-dimensional values for all shapes and just ignoring Y/Z for lines/rectangles, but that isn't really nice and would actually violate the O and L in SOLID (a 4th dimension is possibly needed in the future). Another possibility would probably be to use a generic Interface like `IShape<T>` where `T` is Value*D. This interface would look like:               public interface IShape<T> {         public IEnumerable<T> GetValues();         public void AddValue(T value);     }      But this would require another, non-generic `interface INonGenericShape {}` because I can't use a generic interface without specifying the type. I would end up with something like this:               public class SomeShape{         private IList<INonGenericShape> _shapes = new List<INonGenericShape>();     }      But then I could as well use `System.Object`, since IShape does not provide any valuable information. So here I am, not knowing how to solve this (storing the objects in a single collection for consumers of that class). Can anyone provide some idea or insight?


How can you learn to design nice looking websites?

I am a moderately capable web developer. I can put stuff where I want it to go and put some JQuery stuff in there if I need to. However, if I am making my own website (which I am starting to do) I have no idea how to design it. If someone was to sit next to me a point to the screen and say "put this picture there, text there" I can do that quite easily. But designing my own site with my choice of colours and text will look like a toddler has invented it. Does anyone know any websites/books I can look at or has anyone got any tips on the basics of non-toddler web design?


Is there a difference between a component and a module

I have a little problem with the terms module and component. In my mind, a module are bundled classes, which are only accesable via a well defined interface. They hide all implementation details and are reusable. Modules define modules on which they depend. What is the difference to components? I looked it up in some books, but the description of components is very similar.


C project avoiding naming conflicts

I'm struggling to find pragmatic real-world advice on function naming conventions for a medium sized C library project. My library project is separated into a few modules and submodules with their own headers, and loosely follows an OO style (all functions take a certain struct as first argument, no globals etc). It's laid our something like:               MyLib       - Foo         - foo.h         - foo_internal.h         - some_foo_action.c         - another_foo_action.c         - Baz           - baz.h           - some_baz_action.c       - Bar         - bar.h         - bar_internal.h         - some_bar_action.c      Generally the functions are far too big to (for example) stick `some_foo_action` and `another_foo_action` in one `foo.c` implementation file, make most functions static, and call it a day. I can deal with stripping my internal ("module private") symbols when building the library to avoid conflicts for my users with their client programs, but the question is how to name symbols in my library? So far I've been doing:               struct MyLibFoo;     void MyLibFooSomeAction(MyLibFoo *foo, ...);          struct MyLibBar;     void MyLibBarAnAction(MyLibBar *bar, ...);          // Submodule     struct MyLibFooBaz;     void MyLibFooBazAnotherAction(MyLibFooBaz *baz, ...);      But I'm ending up with crazy long symbol names (much longer than the examples). If I don't prefix the names with a "fake namespace", modules' internal symbol names all clash. Note: I don't care about camelcase/Pascal case etc, just the names themselves.


White box testing with Google Test

I've been trying out using GoogleTest for my C++ hobby project, and I need to test the internals of a component (hence white box testing). At my previous work we just made the test classes friends of the class being tested. But with Google Test that doesn't work as each test is given its own unique class, derived from the fixture class if specified, and friend-ness doesn't transfer to derived classes. Initially I created a test proxy class that is friends with the tested class. It contains a pointer to an instance of the tested class and provides methods for the required, but hidden, members. This worked for a simple class, but now I'm up to testing a tree class with an internal private node class, of which I need to access and mess with. I'm just wondering if anyone using the GoogleTest library has done any white box testing and if they have any hints or helpful constructs that would make this easier. * * * Ok, I've found the FRIEND_TEST macro defined in the documentation, as well as some hints on how to test private code in the advanced guide. But apart from having a huge amount of friend declerations (i.e. one FRIEND_TEST for each test), is there an easier idion to use, or should I abandon using GoogleTest and move to a different test framework?


Are there two type of associations between objects or are there just different representations?

I've been spending some time on 're-tuning' some of my OOP understanding, and I've come up against a concept that is confusing me. Lets say I have two objects. A `user` object and an `account` object. Back to basics here, but each object has **state, behaviour and identity** (often referred to as an entity object). The `user` object manages behaviour purely associated with a user, for example we could have a `login(credentials)` method that returns if successfully logged in or throws exception if not. The `account` object manages behaviour purely associated with a users account. For example we could have a method checkActive() that checks if the account is active. The account object checks if the account has an up-to-date subscription, checks if there are any admin flags added which would make it inactive. It returns if checks pass, or throws exception if not. Now here lies my problem. There is clearly a relationship between `user` and `account`, but I feel that there are actually two TYPES of association to consider. One that is data driven (exists only in the data/state of the objects and the database) and one that is behaviour driven (represents an object call to methods of the associated object). ## Data Driven Association In the example I have presented, there is clearly a data association between `user` and `account`. In a database schema we could have the following table:               -----------------       USER_ACCOUNTS     -----------------      id      user_id      ----------------      When we instantiate the `account` and load the database data into it, there will be a class variable containing `user_id`. In essence, the `account` object holds an integer representation of `user` through `user_id` ## Behaviour Driven Association Behaviour driven associations are really the dependencies of an object. If object A calls methods on object B there is an association going from A to B. A holds an object representation of B. In my example case, neither the `user` object nor the `account` object depend on each other to perform their tasks i.e. neither object calls methods on the other object. There is therefore no behaviour driven association between the two and neither object holds an object reference to the other. ## Question Is the case I presented purely a case of entity representation? The association between `user` and `account` is always present, but its being represented in different ways? ie. the `user` entity has an identity that can be represented in different forms. It can be represented as an object (the instantiated `user` object) or as a unique integer from the users table in the databases. Is this a formalised way of recognising different implementations of associations or have I completely lost my mind? One thing that bugs me is how would I describe the differences in UML or similar? Or is it just an implementation detail?


Find bugs in Java programs, specially using the eclipse plug-in

Is it any good ? http://findbugs.sourceforge.net/ I had a go on the webstart/demo version and it did indeed look useful. Has anyone got any experience with it, is it a valuable tool ?


URL parameters in RESTful web services

I'm wondering about the appropriateness of URL parameters in RESTful resource creation. First, here's some context. I'm working on an API that will remotely update the software on embedded devices connected to an online device cloud. The basic workflow is:   1. Discover available updates   2. Apply desired updates   3. Monitor update progress The update discovery resource will allow users to POST a new update discovery.               POST /updateDiscovery?apikey=a1b2c3      The above URL will trigger update discovery for all devices. It is also useful to restrict which devices are targeted for updates. There are two identifiers used to restrict target devices:   1. a device id   2. a group id (which may reference many devices) This restriction can be communicated using either URL parameters or the request body. Using URL parameters:               POST /updateDiscovery?deviceIds=1,2,3&groupIds=2,3      Using the request body:               POST /updateDiscovery     Content-Type: application/json     {         targets: {              deviceIds: [1, 2, 3],              groupIds: [3, 4]          }     }      Either way, a new resource will be created with the following representation:               {         id: 1,        targets: {             deviceIds: [1, 2, 3],             groupIds: [3, 4]        },        status: 'pending',        ...     }      Which of the above methods best follows the RESTful design pattern and why?


Disk I/Os incurred by readLine () in Java

Does `readLine()` Java function used with `BufferedReader` cause one disk I/O per call? If yes, is there any way to read specific number of lines, say n, from a text file causing only one disk I/O? Here's the code:               String file;     BufferedReader br = new BufferedReader (new FileReader (file));     int n = 10;     for (int i = 0; i < n; i++)     {         String line = br.readLine ();         /* Do something */     }


Source code "prints" at release

Is there a best practice for how to document the source code you're releasing? Currently, we have a table of the versions of the software, what SVN tag it's labeled as, what SVN rev that tag was created at and the SVN URL. Then, our CM department wants us to include a file listing of all the source files we're including for the .zip that we provide them which is just a zip of the tag we're releasing. I'm more fishing for ideas to update our print template, hopefully with good arguments to remove the file listing.


Why is a tooltip's attribute labelled 'title='?

> HTML 4 supports a "title" attribute that can be inserted inside any HTML > tag. Inserting this attribute effectively gives the element a tooltip that > pops up when the mouse moves over it. It just seems like a bad word choice.. or am I missing something?


How fast should a Python factoring script be?

Just how efficient is "good enough" for all intents and purposes? I wrote a script to simply list off all numbers that divide into an input, x, as pairs (i, n//i) and was just curious how efficient I should be going for? what is the acceptable rate at which the script starts to lose its efficiency? This is my code (although advice is appreciated, I just want to give an idea as to how it works).               import time     print('''This program determines all basic factors of a given number, x, as ordered            pairs, (a, b) where ab=x.     Type "quit" to exit.''')          timer = input('Would you like a timer? (y/n) ')     while  1:         try:             x =(input('x = '))                                                            T0 = time.time()             b = []             n = int(x)**0.5             ran = list(range(1, int(n)+1))             if int(x) % 2 == 1:                                                           ran = ran[::2]             for i in ran:                 if int(x) % i == 0:                     m = (i, int(x)//i)                     b.append(m)             else:                 pass         except ValueError as error_1:             if x == 'quit':                 break             else:                 print(error_1)         except EOFError as error_2:             print(error_2)         except OverflowError as error_3:             print(error_3)         except MemoryError as error_4:             print(error_4)         T1 = time.time()         total = T1-T0         print(b)         print(str(len(b)) + ' pairs.')         if timer == 'y':         print("%.5f" % total + ' seconds.')      some of the results are:               x = 9     [(1, 9), (3, 3)]     2 pairs.     0.00000 seconds.          x = 8234324543     [(1, 8234324543)]     1 pairs.     0.07404 seconds.          x = 438756349875     [(1, 438756349875), (3, 146252116625), (5, 87751269975), (15, 29250423325), (25,         17550253995), (75, 5850084665), (125, 3510050799), (375, 1170016933), (557, 787713375),   (1671, 262571125), (2785, 157542675), (8355, 52514225), (13925, 31508535), (41775,   10502845), (69625, 6301707), (208875, 2100569)]     16 pairs.     0.88859 seconds.      So this program can be pretty quick, but then the speed drops rather rapidly once you get up to higher numbers. Anyways, ya, I was just wondering what is considered acceptable by todays standards?


Estimating tasks in Scrum

Our team using Scrum three iterations. We successfully estimate PBI in storypoints using poker-planning. But next we cannot do anything because we don't know   1. Who create tasks? PBI is created by everyone and approved by product owner, but what about task   2. Who estimates task?   3. What technique should be using for task estimating? Poker planning are good for PBI estimating


Alternatives to JDT Annotation - License issues

I have used the JDT Annotation library in my Java project as I am quite fond of what it offers. To be more exact, I used the `@Nullable` and `@NonNullByDefault` annotations as I can use the synergy with Eclipse to automatically analyse possible `null` values and what may lead to `NullPointerException` bugs. Unfortunately, JDT Annotation is licensed under EPL1 which, as far as I know, is incompatible with GPL2 due to the former being a weak copyleft license and choice of some clauses. As the project should be published under a GPL2 license, I am exploring different options but have yet to fine any that would offer the same, or nearly the same, functionality. I am not keen on adding null checks as they only clutter the code with what an annotation could have solved as well. But unfortunately it seems to be the only viable option? I am looking for some expertise regarding this matter. What I propose is to use Google's `Preconditions` to formulate preconditions such as:               Preconditions.checkArgument(providedArgument != null, "The provided argument must not be null!");      respectively:               Preconditions.checkState(invariantField != null, "The field may not be null!");      These will solve the problem of course and be more explicit, in my opinion, when it comes to documenting my contracts by code. I usually also report these with custom tags in my Javadoc, for example, `@pre providedArgument != null` or `@inv invariantField != null`. I would be thankful for all


Problem with OAuth2 authentication process and session persistance

We're using node-oauth2-provider as an authentication library for our service. The current process for a user to log in is:               POST /oauth2/access_token      Which creates and saves the access_token to the database. On subsequent requests we send the `access_token` which is pulled from the database to verify that it exists. From there the user is added to session manually by us in a similar fashion to their examples. After this happens, if a request comes in without the access token, the session still seems to be set. As if it's persisting across requests. Maybe I misunderstand how this is supposed to work... but shouldn't the access token be the indication that a user's requests are still valid? If so, do I need to clear the session manually? If not and it stores it in memory... possibly indicated by:               express.session({store: new MemoryStore({reapInterval: 5 * 60 * 1000}), secret: 'abracadabra'})      Then how does the server know that subsequent requests are valid?


Using words instead of numbers for versioning?

Would it be considered acceptable to use word compounds instead of numbers for version iterations? For example in a pattern: "[Adjective] [Noun]" The first version could be something like: "Auspicious Armadillo" Thus on each sequential release the noun would change to the next letter of the alphabet and the version could be along the lines of: "Auspicious Bear" Once the alphabet for the nouns runs out the Adjective gets changed and the Nouns can start over e.g: "Bewildered Armadillo" etc. This would give me around 676 possible different versions to iterate through. Assuming the project is small & short enough to fall within these 676 releases before a complete remake/overhaul, would such a versioning pattern be considered acceptable to use? Or would it just create needless confusion and chaos? I understand this might be somewhat opinion related, but I was hoping for some kind of a general consensus on whether this is an acceptable or terrible idea.


Can a recursive function have iterations/loops?

I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function). However, while surfing the web for examples (the 8-queens-recursive problem), I found this function:               private boolean placeQueen(int rows, int queens, int n) {         boolean result = false;         if (row < n) {             while ((queens[row] < n - 1) && !result) {                 queens[row]++;                 if (verify(row,queens,n)) {                     ok = placeQueen(row + 1,queens,n);                 }             }             if (!result) {                 queens[row] = -1;             }         }else{             result = true;         }         return result;     }      There is a `while` loop involved. ... so I'm a bit lost now. Can I use loops or not?


In an online questionnaire, what is a best way to design a database for keeping track of users all attempts?

We have a web app where users can take online exams. Exam admin will create a questionnaire. A questionnaire can have many Questions. Each question is a multiple choice question (MCQ). Let's say an admin creates a questionnaire with 10 questions. Users attempt those questions. Now, unlike real exams users can attempt single questionnaire multiple times. And we have to keep track of his all attempts. e.g.                +-------+-----------------+------------+-------+------------+----------+      |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|      +-------+-----------------+------------+-------+------------+----------+      |1      |1                |1           |a      |1 June 2013 |1         |      |1      |1                |2           |b      |1 June 2013 |1         |      |1      |1                |1           |c      |2 June 2013 |2         |      |1      |1                |2           |d      |2 June 2013 |2         |      +-------+-----------------+------------+-------+------------+----------+      Now it can also happen that after user has attempted same questionnaire twice, admin can delete a question from same questionnaire, but users' attempt history should still have reference to that so that user can see his that question in his attempt history in spite of admin deleting that question. If user now attempts this changed questionnaire he should see only 1 question.                +-------+-----------------+------------+-------+------------+----------+      |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|      +-------+-----------------+------------+-------+------------+----------+      |1      |1                |1           |a      |3 June 2013 |3         |      +-------+-----------------+------------+-------+------------+----------+      Also, after this user modified some part of question, users attempt history should show question before modification while any new attempt should show the modified question. How do we manage this at database level? My first gut feeling was that, For deletes, do not do physical delete, just make a question inactive so that history can still keep track of users attempt. For modifications, create versions for questions and each new attempt refres to latest version of each question and history keeping reference to version of question at attempt time.


mercurial or tfs for codeplex?

I've been working on a .NET personal project for a little while now and it's almost ready to go open source. I've decided (arbitrarily) to host it on codeplex. Codeplex offers TFS or mercurial. I'm wondering which I should pick. Consider:   * I've only ever used subversion.   * I'm using VS 2010 express as my IDE.   * Tools must be free (so the mercurial client if I go that route).   * From what I've been hearing, mercurial sounds interesting but I know _very_ little about it so if there's a learning curve, then I don't want to add too many more learning objectives to the project.   * I don't expect any contributors. So I guess the actual question is, is mercurial easy enough to use with codeplex and does it add anything that the TFS option doesn't?


design a model for a system of dependent variables

I'm dealing with a modeling system (financial) that has dozens of variables. Some of the variables are independent, and function as inputs to the system; most of them are calculated from other variables (independent and calculated) in the system. What I'm looking for is a clean, elegant way to:   1. define the function of each dependent variable in the system   2. trigger a re-calculation, whenever a variable changes, of the variables that depend on it A naive way to do this would be to write a single class that implements `INotifyPropertyChanged`, and uses a massive case statement that lists out all the variable names x1, x2, ... xn on which others depend, and, whenever a variable `xi` changes, triggers a recalculation of each of that variable's dependencies. I feel that this naive approach is flawed, and that there must be a cleaner way. I started down the path of defining a `CalculationManager<TModel>` class, which would be used (in a simple example) something like as follows:               public class Model : INotifyPropertyChanged     {         private CalculationManager<Model> _calculationManager = new CalculationManager<Model>();               // each setter triggers a "PropertyChanged" event         public double? Height { get; set; }         public double? Weight { get; set; }         public double? BMI { get; set; }              public Model()         {             _calculationManager.DefineDependency<double?>(                 forProperty: model => model.BMI,                 usingCalculation: (height, weight) => weight / Math.Pow(height, 2),                 withInputs: model => model.Height, model.Weight);         }              // INotifyPropertyChanged implementation here     }      I won't reproduce `CalculationManager<TModel>` here, but the basic idea is that it sets up a dependency map, listens for `PropertyChanged` events, and updates dependent properties as needed. I still feel that I'm missing something major here, and that this isn't the right approach:   1. the (mis)use of `INotifyPropertyChanged` seems to me like a code smell   2. the `withInputs` parameter is defined as `params Expression<Func<TModel, T>>[] args`, which means that the argument list of `usingCalculation` is not checked at compile time   3. the argument list (weight, height) is redundantly defined in both `usingCalculation` and `withInputs` I am sure that this kind of system of dependent variables must be common in computational mathematics, physics, finance, and other fields. Does someone know of an established set of ideas that deal with what I'm grasping at here? Would this be a suitable application for a functional language like F#? * * * **Edit** More context: The model currently exists in an Excel spreadsheet, and is being migrated to a C# application. It is run on-demand, and the variables can be modified by the user from the application's UI. Its purpose is to retrieve variables that the business is interested in, given current inputs from the markets, and model parameters set by the business.


How to control work of programmers (outsourcers)

Some time ago I decided to outsource web development projects (php coding & design). I've opened small office abroad with manager and couple of programmers and designer. I just started but already have a problem controlling their work. Some programmers are fast, others work much slower. I pay them fixed salary, so it matters for me if they do their job on time. When they work from office, I at least have a person responsible for the project to tell if they really worked. But sometimes they work from home and in that case I have no way to know if they really spent that time working on some issue. Some of my ideas were: controlling amount of code done with svn, strict deadlines, everyday reporting.. But nothing seems perfect to me. It creates even more work from my side. Can anyone suggest a way of fair judgement on how much really time was spent on actual work? How to stimulate people to work? Maybe create some bonus system if work is done fast? Any idea/experience on this topic would be highly appreciated.


Does (/could) an LGPL-based license exist without clause 4d?

I've started writing a framework in C (you may have heard of it: Raphters). Someone contacted me to ask whether I could re-license it because it would be useful in embedded products, but clause 4d (the clause that says, and I'm paraphrasing, you must allow modified versions of the library to be re-linked against your executable) would make that difficult. I like LGPL because it prevents people making modifications and keeping them secret, but I don't want to prevent people using Raphters in their embedded products. What do you suggest?


What do you consider to be the prime cause of software defects (and how to minimize them)

I define **defect** as : > "something within the application design or code which prevents it > functioning as per requirements." I'm looking for ideas about the causes of defects, eg the human factor, lack of testing, lack of prototyping, and possible ideas to mitigate these.


Is a degree needed for low-level/embedded programming jobs?

I know that it is possible to get into software development without a degree in computer science, but is it possible (or rather, common) to be able to get an embedded programming job without the computer science degree (or any engineering degree as well)?


Fellow programmer used worst programming practices

I know it seems odd to say, but a fellow programmer at work deliberately used a couple of bad programming practices on purpose! I'll explain. First let me say that he's an intelligent guy and for the most part he writes intelligible code. He was asked to implement licensing on a web application project written in Java. Since it's Java, if one really wanted to, one could probably hack open the jars and read the names of the classes and methods written inside. His solution to this problem was to quite literally to awkwardly call variables and methods less-than-obvious names and plant them inside already congested classes rather than generating new classes. His justification was that if a hacker wanted to switch out certain classes in order to bypass licensing checks (and therefore get a free copy of the product), he'd have a far more difficult time of it if it weren't obvious which methods perform these particular tasks. Only after he had done it did I confront him about it, suggesting that we could perhaps buy some sort of obfuscator library to do it for us, while maintaining good programming practices. He claims to not have had the time or resources to search for that kind of solution. ..Which leaves me at a dilemma. Do I look for a obfuscator library in Java and fix his old code (which might be a little touchy about remodeling his code), or do I leave it as it, as much as that irks me to no end?


Program coded in .Net

What does it generally mean when a programmer says his program/application was "coded in .Net"? When I think of .Net I think of C# and Visual Basic. I don't usually think of any other language on this list: http://en.wikipedia.org/wiki/List_of_CLI_languages


how do you seperate from designing question to programming questions?

As i try to program a solution to a request arise. I can't separate the difference between implementation problems and design problems. How do you specifically express the design problem?


Avoiding wrapper objects in collections

I'm getting a little annoyed of having to wrap primitive types in wrapper objects to store them in collection data structures (sets, maps, lists, etc.) in languages like Java and Objective C. I'd really like to have, say, a Map data structure that works the same way whether I'm mapping NSNumbers to Strings or integers to doubles or integers to MyBigCustomObject*. My understanding is that the reason collection data structures in these languages require wrapping in an object is so it can just always assume that the number given is a pointer - I actually _can_ make a NSDictionary with [NSDictionary dictionaryWithObject: MyCustomObject forKey: 1], but it will treat the 1 as a pointer instead of an integer, try to access memory address 1 and segfault. But I don't see any reason why you couldn't make a collection data structure that keeps track of the _type_ of keys and values that wouldn't have this problem. Even a relatively inflexible data structure like a Map of specifically-ints to specifically-pointers-to-objects would be a decently common use case (I certainly could use one, I'm doing a lot of work recently that involves indexing objects by an integer ID). Is there a reason why this isn't a common paradigm in languages that have an Object/primitive type distinction?


Best resources for learning idiomatic PHP

My experience has primarily been in Java, but I'm working on a PHP project and conscious of my lack of knowledge of idiomatic PHP. What resources (online or print) will help me avoid making the mistakes that people with Java goggles normally make? First prize would be something that would give me short in- depth examinations of important PHP ideas, a la Joshua Bloch's Effective Java.


LINQ Style preference

I have come to use LINQ in my every day programming a lot. In fact, I rarely, if ever, use an explicit loop. I have, however, found that I don't use the SQL like syntax anymore. I just use the extension functions. So rather then saying:               from x in y select datatransform where filter       I use:               x.Where(c => filter).Select(c => datatransform)      Which style of LINQ do you prefer and what are others on your team are comfortable with?


Software technical and project specification: How to?

We have a project here in my company of developing a new CRM. It's, basically, a big CRUD, with sub-CRUDS, with various details, such as, some users can do that, others don't. We will develop the system in PHP with Symfony. Developing is easy, but we're having some difficulties in the analysis part of the job. We have to present the project specification, as well the tecnical specification of the project. We have to draw and explain how to system will work. And we're not sure on how to do this. We always just... did the system. Not planning with graphics or text, or explaining what we were doing. We already asked everyone and got suggestions, as well requirements. Apparently, we have to take that and explain the system. Any tips, guys? :)


Citing Borrowed Code

If you borrow code from some source, it is probably best to cite it (like "adapted from [source]"). However, if you take let's say you borrowed this function (example in C++):               void doWork()     {          cout << "Doing work!\n" << endl;     }      and now you editted it to be like this:               void doWork()     {          string name = "";               cout << "Starting work...\n" << endl;          cout << "Hello user. What is your name?" << endl;               cin >> name;          ...     }      Would you still have to say "adapted from [source]" or something like that? Or are you in the safe zone? **Note** : I am specifically wondering how this applies to copyrighted (and open source) code


What is the value in hiding the details through abstractions? Isn't there value in transparency?

## Background I am not a big fan of abstraction. I will admit that one can benefit from adaptability, portability and re-usability of interfaces etc. There is real benefit there, and I don't wish to question that, so let's ignore it. There is the other major "benefit" of abstraction, which is to hide implementation logic and details from users of this abstraction. The argument is that you don't need to know the details, and that one should concentrate on their own logic at this point. Makes sense in theory. However, whenever I've been maintaining large enterprise applications, I always need to know more details. It becomes a huge hassle digging deeper and deeper into the abstraction at every turn just to find out exactly what something does; i.e. having to do "open declaration" about 12 times before finding the stored procedure used. This 'hide the details' mentality seems to just get in the way. I'm always wishing for more transparent interfaces and less abstraction. I can read high level source code and know what it does, but I'll never know how it does it, when how it does it, is what I really need to know. What's going on here? Has every system I've ever worked on just been badly designed (from this perspective at least)? # My philosophy When I develop software, I feel like I try to follow a philosophy I feel is closely related to the ArchLinux philosophy: > Arch Linux retains the inherent complexities of a GNU/Linux system, while > keeping them well organized and transparent. Arch Linux developers and users > believe that trying to hide the complexities of a system actually results in > an even more complex system, and is therefore to be avoided. And therefore, I never try to hide complexity of my software behind abstraction layers. I try to abuse abstraction, not become a slave to it. # Question at heart   1. Is there real value in hiding the details?   2. Aren't we sacrificing transparency?   3. Isn't this transparency valuable?


Can I use an LGPL-licenced library in my commercial app?

I want to use an LGPL-licensed library in my app for Microsoft's app marketplace. Is that OK?


Is it possible to integrate UDP file transfer into a .NET web application?

# Background I have recently been tasked with designing a rebuild of an existing .NET web application that _currently_ uses a third-party company to handle large file transfers (as big as 50Gb). Currently, the .NET app depends on a .JAR (Java Applet) provided by this third-party which is called up inside of an iFrame and exposes the appropriate file-system interaction for selecting entire directories for upload and so forth. I realize that so far all of this is possible using some combination of .NET networking classes (ftp) and Flash or Silverlight for client access. I have been told that the reason that the third-party plugin is so special is that it uses UDP protocol so that if an upload or download is interrupted, it can be resumed later right where it left off. I have also been told that the third-party tool suite allows the IT folks to throttle bandwith (I don't even know what that means) and do a couple of other cool things. # Question Assuming that we will use the latest version of C# and and the .NET framework (4.0), is it reasonably possible to replicate this UDP-based behavior? By reasonable, I mean could it be accomplished in less than, say, 240 dev hours. **Please note** that the rebuilt app will ideally use all Microsoft technologies (including Silverlight for client access) and will run on Azure.


Graphic demonstrating emphasis of front end in web apps

I remember stumbling across an amusing graphic a year or so ago which demonstrated the tiers of web development. The back-end was shown as a tiny box, but the front end was shown as a huge box crammed with lots of front-end technologies like AJAX, DHTML. This is all a vague recollection. Does anyone know where on the Intraweb this graphic might be? It was probably on a programming cartoon site, but I only view XKCD on a regular basis, and I couldn't find it on there. Although tagged as fun, my request does have a productive edge to it - it would be quite useful in driving home to my colleagues how UI top-heavy web application development has become.


Is it possible to develop an IOS application without a Mac?

I'm a postgraduated student and I had the idea to build an app for elementary school kids. My question after many days of searching is whether anyone here have ever tried and what was their experience of developing an IOS app on other platforms than Xcode such as Phonegap, Monotouch, flex or others?


Are Datasets Patentable

I'm working on a project that uses a dataset produced from software informally licensed as "non-commercial use only". I'm developing an application that uses that dataset as an input to another algorithm. Our own software has a permissive free software license in which we don't restrict commercial usage. Are there legal implications of using that dataset in our own software in the sense that we are violating a copyright? **Edit** : Thanks folks, the ask a lawyer thing is the way to go, but its helpful for me to hear some opinions bounce around.


How should I write new code when the old codebase and the environment uses lots of globals in PHP

I'm working in the Wordpress environment which itself heavily relies on globals and the codebase I'm maintaining introduces some more. I want this to change and so I'm trying to think how should I handle this. For the globals our code has introduced I think I will set them as dependencies in the constructor or in getter / setter so that I don't rely on them being globals and then refactor the old codebase little by little so that we have no globals. With Wordpress globals I was thinking to wrap all WP globals inside a Wrapper class and hide them in there. Like this               class WpGlobals {         public static function getDb() {             global $wpdb;             return $wpdb;         }     }      Would this be of any help? The idea is that I centralize all globals in one class and do not scatter them through the code, so that if Wordpress kills one of them I need to modify code only in one place. What would you do?


Is it possible for a browser to use peer-to-peer browsing?

I was recently asked this from my friend after explaining how µTorrent worked, he then went to ask me, "Could this be used for browsing the web?", (not a direct quote) but I found my self thinking about this for a while there after.   * Could someone be credited with making the first Peer-2-Peer browser?    * How could it send the correct data without it being modified?   * Would it be faster than normal browsers? (Referring to the way µTorrent works, I find when I use a torrent it's faster than a web download.)    * Can it save on server loads, prevent DDoS, more?


How can I reverse engineer a hash code?

I am building an application in C# that works with a Progress database. The passwords that are stored in this database are stored using a hash algorithm that Progress has not made public. However, I would like to authenticate using these hashes. Is it feasible to reverse engineer such a hash algorithm and how would I go about doing this? To be clear: I am not looking for a way to get the unhashed passwords from the hashes. I'm looking for the algorithm to get a hash from a password.


Why must a constructor's call to the superconstructor be the first call?

It is an error if you do anything in a constructor before calling the superconstructor. I remember that I had problems because of that. Yet, I do not see how this saves us from errors. It could save you from using uninitialized fields. But, the Java compiler that checks for using uninitalized variables does that and this stupid rule does not improve anything here. The only serious consideration argument I remember was that we need it for OOP, because objects in real life are constructed this way: you create a cucumber by first creating a vegetable and then add cucumber attributes. IMO, it is opposite. You first create a cucumber and, by duck is a duck principle, it becomes a vegetable. Another argument was that it improves safety. Not writing the code improves the dependability much better, so I do not consider this as argument. Creating more complex code when you need to workaround a stupid restriction, is what makes the program more error-prone. This rule creates a serious pain (at least for me). So, I want to hear the serious argument and serious example where it could be useful.


How to solve cyclic dependencies in a visitor pattern

When programming at work we now and then face a problem with visitors and module/project dependencies. Say you have a class A in a module X. And there are subclasses B and C in module Y. That means that module Y is dependent on module X. If we want to implement a visitor pattern to the class hierarchy, thus introducing an interface with the handle Operations and an abstract accept method in A, we get a dependency from module Y to module X, which we cannot allow for architectural reasons. What we do is, use a direct comparison of the types (i.e. `instanceof`, since we program in Java), which is not satisfying. My question(s) would be: Do you encounter this kind of problem in your daily work (or do we make poor architectural choices) and if so, how is your approach to solve this? Here is a minimal example in Java to illustrate my point. Package a has ClassA and the Visitor-Interface over the ClassA Hierarchy:               package pkg.a;       public abstract ClassA extends ClassA {           public abstract void accept(ClassAVisitor visitor);          /* other methods ... */        }           package pkg.a;       import pkg.b.ClassB;     import pkg.b.ClassC;     public interface ClassAVisitor {           public abstract void handle(ClassB visitee);         public abstract void handle(ClassC visitee);       }       Package b has the concrete classes that extend from ClassA:               package pkg.b;       import pkg.a.ClassAVisitor;     public ClassB extends ClassA {           public void accept(ClassAVisitor visitor) {               visitor.handle(this);           }        }           package pkg.b;     import pkg.a.ClassAVisitor;       public ClassC {           public void accept(ClassAVisitor visitor) {               visitor.handle(this);           }        }      Package a and b have a cyclic dependency.


AngularJS: structuring a web application with multiple ng-apps

The blogosphere has a number of articles on the topic of AngularJS app structuring guidelines such as these (and others):   * http://www.johnpapa.net/angular-app-structuring-guidelines/   * http://codingsmackdown.tv/blog/2013/04/19/angularjs-modules-for-great-justice/   * http://danorlando.com/angularjs-architecture-understanding-modules/   * http://henriquat.re/modularizing-angularjs/modularizing-angular-applications/modularizing-angular-applications.html However, one scenario I have yet to come across for guidelines and best practices is the case where you have a large web application containing multiple "mini-spa" apps, and the mini-spa apps all share a certain amount of code. I am not referring to the case of trying to have multiple `ng-app` declarations on the same page; rather, I mean different sections of a large site that have their own, unique `ng-app` declaration. As Scott Allen writes in his OdeToCode blog: > One scenario I haven't found addressed very well is the scenario where > multiple apps exist in the same greater web application and require some > shared code on the client. Are there any recommended approaches to take, pitfalls to avoid, or good sample structures of this scenario that you can point to?


How to use Subversion in conjunction with DTAP with several Scrum teams?

I've read _How Do You Pull Something from a Release?_ , but it doesn't solve our problems, as our case is more complex. Our situation is as follows. We're developing an application for an internal customer. We're doing Scrum with four more or less aligned teams (i.e. sprints end on the same day), one of which is off site. We have a basic DTAP street and we use Subversion for source control. We want to deploy to the TAP-end of the street from source control, as a preparation to use continuous integration later on. To be able to deploy from source control, we maintain branches that are in sync with each of the T, A, and P environments.   Our current setup is a clean trunk, which is in sync with Production, an acpt branch that was branched from trunk at some point in the past and which is in sync with Acceptance, and a branch for each sprint that branches from the acpt branch at the start of each sprint and merges back into it at the end. This sprint branch is in sync with the Test environment for the duration of the sprint. At the end of each sprint, issues that are done are merged into acpt. A new sprint branch is made and a new sprint begins. Meanwhile, the acpt branch is deployed to Acceptance and tested there. Of course, in an ideal world, we would complete all user stories during the sprint and during UAT there would be no defects found. But alas, this world is not perfect and problems _are_ found during UAT. _Of course not bugs_ , but we may have interpreted a request incorrectly. Or there may be some other reason for a user story to not be released (yet). So now we have to pull some stories from that branch. Since the changes were merged from sprint branch to acpt branch in one go, this is not a trivial task. **How can we adjust our method to allow for user stories to be pulled from the acpt branch?** * * * I've also read _Agile version control with multiple teams_ by Henrik Kniberg. That looks like a model that's better suited to our needs, but even then I have some questions about it. If we adopt his model, should we sync the trunk to Acceptance? That would give us opportunity to conduct UATs _during_ a sprint, and would effectively uncouple the sprint schedule from the release schedule. But Kniberg promotes a stricter adherence to Scrum than we currently follow, where user stories are done pretty much in sequence. **How could we adjust Kniberg's method to suit our needs?**


How to present domain model exceptions thrown through validation

In domain model of my web application I've an entity Foo which can be created only by a pojo FooBean: `Foo.newInstance(FooBean fooBean)` (Might have been better a Builder-pattern.) In the factory methode `newInstance()` the pojo FooBean is validated and throws NullPointerExceptions and IllegalArgumentExceptions if needed. The fields of the pojo are filled by a form on the presentation layer. That form does some validation on the user input and shows user friendly messages if needed. The exception message of the NullPointerExceptions and IllegalArgumentExceptions thrown in the `newInstance()` method are rather technical and shouldn't be displayed to the end user. What is a proper way to show user friendly error messages that are originated by the NullPointerException or the IllegalArgumentException?


Bitbucket and a small development house

I am in the process of finally rolling Mercurial as our version control system at work. This is a huge deal for everyone as, shockingly, they have never used a VCS. After months of putting the bug in management's ears, they finally saw the light and now realise how much better it is than working with a network of shared folders! In the process of rolling this out, I am thinking of different strategies to manage our stuff and I am leaning towards using Bitbucket as our "central" repository. The projects in Bitbucket will solely be private projects and everyone will push and pull from there. I am open to different suggestions, but has anyone got a similar setup? If so, what caveats have you encountered?


UI design for changing multiple records at once

I have a desktop application where the user has tabular views on some data records. Now we got the requirement to let the user select multiple of these records at the same time and let the him edit some properties of the selected records all at once in a separate edit dialog. The idea is   * to change only the properties the user really want change   * to keep all other properties unchanged Furthermore, when the user has selected the records and opens the edit dialog, the properties with equal values in all of the selected records are shown in the corresponding UI fields, the other properties should be shown as "undefined" as long as the user does not starts to enter something in there. After pressing "Ok", the changes are applied to the records. This kind of UI behaviour is not "rocket science", we already found this, for example, in graphical editors (where you can select multiple drawing elements at once and change their properties.) The problem is how to visualize the "undefined" state in an intuitive manner, especially for text properties. For boolean values, this is easy: we use just a tri-state check box. For number values, this is easy, too: the "undefined" state is displayed as an empty numeric UI field, and if there is actually a number in there, the state is "defined". But how shall one design this for text properties? An empty text box field is actually not an "undefined" state, since many of the text properties _can_ actually be empty. One could add a separate check box beside each text box to indicate the difference between "undefined" and "defined", but since our edit dialog contains already check boxes for boolean properties, this seems to be counterintuitive and confusing to the user. If this matters, we are using Winforms (but I think this problem is not specfic to the actual UI framework).


Which license retains copyright while allowing work to be shared and derived from?

I am working on an academic research project whose results and _some_ code we intend to publish. Research journals and conferences explicitly require that the authors have copyright over the work done in a paper. However, I would like to share the code with the community as it progresses using an open source license. Is there a license that explicitly retains copyright while allowing sharing, redistribution and derivative works based on the original work? Alternatively, which license would be suitable for such projects?


Most efficient data structure for implementing inheritance structure without classes

I have a number of types that all relate to each other in terms of them being 'derived' from one another. I'd need a way to do `is` relationships, which made me initially think of classes, but I realized that other than the `is` relationships, there would be no reason to use classes as each 'type' of data function the exact same way. I'd also thought of enums, but since there is no way to extend or inherit from enums it was a poor choice. For context (this being my specific example): I have a number of different kinds of resources that all are 'types' so that they can be used in conjunction with an int to denote how much of that resource is available. I have several different kinds of these resources, such as foods, metals, building materials etc. Within the food category would be something like wheat or corn; under metals would be copper, iron, gold etc. Since all of these are still just 'resources' and have no actual functionality other than typing, it seems pointless to use classes and OO inheritance. How would I implement this kind of data type without resorting to using classes?


What's the difference between lists constructed by quote and those constructed by cons in Scheme?

(define ls1 '((1 . 2) 1 . 2))     (set-car! (car ls1) 6)     ls1     (define ls2 (cons '(1 . 2) '(1 . 2)))     (set-car! (car ls2) 6)     ls2      After `set-car!`ing, ls1 will be `((6 . 2) 1 . 2)` and ls2 `((6 . 2) 6 . 2)`. It seems that `ls1` and `ls2` have different storage model, and what does it mean when someone says `x is bound to a list`? is x stand for a `starting address` or `location` like that a is the starting address of a[10] in C?


Organisation by business function vs technical function

I am designing a large application (a static code analyser) and I have a choice in how to organise the code into modules:   * One approach is by what I'd call by **technical function**. This is where you have a package for data objects, another for service functions, views, controllers, etc.   * Another approach is what I'd call by **business function**. This where you'd have a package for, say, stock control, another for product listings, customer orders, etc. Most frameworks tend to push me towards the first approach. Sometimes there are technical reasons for this, e.g. if the view is written in JavaScript and the rest in Python, you really need to keep it separate. But mostly it is just a matter of convention. Sometimes organising by technical function results in spreading related code across the application. If I have code to support a product, I end up with ProductModel, ProductService, ProductView, etc. Often I feel it would be neater to simply have a Product object that does all these. Organising by business function has issues too. Some classes are borderline and it's quite arbitrary which package you put them in. And there are some support objects that are used across all business functions. Which approach will be the most effective for making a scalable and maintainable application?


Disadvantages of vertical user stories

The **agile approach** is to structure the work into **vertical user stories** and deliver a focused but fully functioning piece of the application from **end-to-end**. Because this is the new approach to building software I read a lot of literature about why this is better than horizontal stories but I do not find much about the disadvantages to this approach. I already drank the agile cool-aid and I too agree that vertically slicing the cake has much advantages over horizontal slicing. Here is a short list of disadvantages that I could come up with:   * A developer might initially be slower at implementing a feature because s/he must understand all the technologies required to develop the story (UI + service layer + data access + networking, etc...)   * Overall architecture design (crating the backbone of the application) does not really fit this mantra (however some might argue that it is part of a user story to develop/change the overall architecture) **What are some more drawbacks of vertically slicing user stories?** _Note: The reason I am asking this question now is because I am going to attempt to convince a team to start writing stories the 'vertical way' and I want to be able to bring up the possible trade-offs ahead of time so they won't consider the approach a failure when they are faced with the drawbacks._


Efficient Copy While Sorting

I have an algorithms library called NDex. I am in the process of upgrading it to a new version. Part of this upgrade involves providing two versions of many algorithms: an in-place version and a version that copies the results to a destination list. I will be providing two sort variations: quick sort and merge sort. The merge sort is stable. I am curious whether quick sort is better than, say, heap sort when copying items to a new list. Merge sort uses a buffer internally. I am curious when doing a merge sort whether I can double up the destination as the buffer. I was hoping someone could give me some advice or point me to some useful material.


Communicate to a junior developer about bad style

I have a friend who's managed to pick up comma first (best case might be made here: http://ajaxian.com/archives/is-there-something-to-the-crazy-comma-first- style) but it's 100% against our org's style guide and the Python culture. If you don't want to click the link, he's basically doing this:               a, b, c, d = tuple('abcd') # setup for interpreter demo, if desired     foo = ( a           , b           , c           , d           )      Maybe it's just habit or training, but I do not want to even begin to have the spark of a thought about even starting to think about doing this; much less see others pick it up. But I'm also a bit of a grammar fiend too. How do I communicate to a him that keeping to idiomatic style is better for his career and reputation as a programmer?


Separation of Tasks in an n-tier app: By module or by tier?

Developing an n-tier app with a team, is it better to divide tasks by module or use case (e.g. Employee 1 creates Admin module, employee 2 creates Payroll module, etc.) or by tier (e.g. Employee 1 creates UI, Employee 2 creates Logic, Employee 3 creates all Data Access)? I'm more inclined towards the former. I think that it's only logical that if I'm coding one whole module or at least related use cases, I would be able to code continuously without waiting for others to finish before integrating my work. But the counter-argument, which is the latter, is that by separating tasks between layers, a programmer can take advantage of n-tier's separation of concerns and focus only on a specific layer (to some) they're familiar with.


What are the benefits and drawback of documentation vs tutorials vs video tutorials

Which types of learning resources do you find the most helpful, for which kinds of learning and/or perhaps at specific times? Some examples of types of learning you could consider:   * When starting to integrate a new SDK inside an existing codebase   * When learning a new framework without having to integrate legacy code   * When digging deeper into an already-used SDK that you may not know very well yet For example - (video) tutorials are usually very easy to follow and tells a story from beginning to end to get results, but will nearly always assume starting from scratch or a previous tutorial. Therefore such a resource is useful for quick learning if you don't have legacy code around, but less so if you have to search for the best-fit to the code you already have. SDK Documentation on the other hand is well-structured but does not tell a story. It is more difficult to get to a specific larger result with documentation alone, but it is a better fit when you do have legacy code around and are searching for perhaps non-obvious ways of employing the SDK or library. Are there other forms of resources that you find useful, such as interactive training?


How are you setting up re-usable development environments?

I'm trying to come up with a good approach to creating a re-usable development environment such that it doesn't take a couple days to re-build a machine if it starts to sputter and to be able to onboard new developers faster. Reading about Quora's development setup made me consider alternatives to the old development environment build delay. For a .NET/Windows shop though, how are you solving this problem?   * Local virtual machine on your desktop/laptop that you can share with the other members of the team?   * A dedicated server (physical or virtual) that all developers remote desktop into and that can be easily backed up. (obviously requires a network connection, so there's a downside)?   * An instance in the cloud (like Quora)?


How do you automatically test a time check?

Say you have a property `startTime`. Then you have a method `doSomething`:               doSomething() {        //...stuff        startTime = System.currentTimeMillis();        //... more stuff     }      How do you test that `startTime` was assigned correctly? You can't test against an absolute timestamp - it'll likely change between assignment and test. Maybe use a range?


Is it wise to store a big lump of json on a database row

I have this project which stores product details from amazon into the database. Just to give you an idea on how big it is: ` [{"title":"Genetic Engineering (Opposing Viewpoints)","short_title":"Genetic Engineering ...","brand":"","condition":"","sales_rank":"7171426","binding":"Book","item_detail_url":"http://localhost/wordpress/product/?asin=0737705124","node_list":"Books > Science & Math > Biological Sciences > Biotechnology","node_category":"Books","subcat":"","model_number":"","item_url":"http://localhost/wordpress/wp- content/ecom-plugin- redirects/ecom_redirector.php?id=128","details_url":"http://localhost/wordpress/product/?asin=0737705124","large_image":"http://localhost/wordpress/wp- content/plugins/ecom/img/large- notfound.png","medium_image":"http://localhost/wordpress/wp- content/plugins/ecom/img/medium- notfound.png","small_image":"http://localhost/wordpress/wp- content/plugins/ecom/img/small- notfound.png","thumbnail_image":"http://localhost/wordpress/wp- content/plugins/ecom/img/thumbnail- notfound.png","tiny_img":"http://localhost/wordpress/wp- content/plugins/ecom/img/tiny- notfound.png","swatch_img":"http://localhost/wordpress/wp- content/plugins/ecom/img/swatch- notfound.png","total_images":"6","amount":"33.70","currency":"$","long_currency":"USD","price":"$33.70","price_type":"List Price","show_price_type":"0","stars_url":"","product_review":"","rating":"","yellow_star_class":"","white_star_class":"","rating_text":" of 5","reviews_url":"","review_label":"","reviews_label":"Read all ","review_count":"","create_review_url":"http://localhost/wordpress/wp- content/ecom-plugin- redirects/ecom_redirector.php?id=132","create_review_label":"Write a review","buy_url":"http://localhost/wordpress/wp-content/ecom-plugin- redirects/ecom_redirector.php?id=19186","add_to_cart_action":"http://localhost/wordpress/wp- content/ecom-plugin- redirects/add_to_cart.php","asin":"0737705124","status":"Only 7 left in stock.","snippet_condition":"in_stock","status_class":"ninstck","customer_images":["http://localhost/wordpress/wp- content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg","http://localhost/wordpress/wp- content/uploads/2013/10/ecom_images/31FIM- YIUrL.jpg","http://localhost/wordpress/wp- content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg","http://localhost/wordpress/wp- content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg"],"disclaimer":"","item_attributes":[{"attr":"Author","value":"Greenhaven Press"},{"attr":"Binding","value":"Hardcover"},{"attr":"EAN","value":"9780737705126"},{"attr":"Edition","value":"1"},{"attr":"ISBN","value":"0737705124"},{"attr":"Label","value":"Greenhaven Press"},{"attr":"Manufacturer","value":"Greenhaven Press"},{"attr":"NumberOfItems","value":"1"},{"attr":"NumberOfPages","value":"224"},{"attr":"ProductGroup","value":"Book"},{"attr":"ProductTypeName","value":"ABIS_BOOK"},{"attr":"PublicationDate","value":"2000-06"},{"attr":"Publisher","value":"Greenhaven Press"},{"attr":"SKU","value":"G0737705124I2N00"},{"attr":"Studio","value":"Greenhaven Press"},{"attr":"Title","value":"Genetic Engineering (Opposing Viewpoints)"}],"customer_review_url":"http://localhost/wordpress/wp- content/ecom-customer- reviews/0737705124.html","flickr_results":["http://localhost/wordpress/wp- content/uploads/2013/10/ecom_images/5105560852_06c7d06f14_m.jpg"],"freebase_text":"No around the web data available yet","freebase_image":"http://localhost/wordpress/wp- content/plugins/ecom/img/freebase- notfound.jpg","ebay_related_items":[{"title":"Genetic Engineering (Introducing Issues With Opposing Viewpoints), , Good Book","image":"http://localhost/wordpress/wp- content/uploads/2013/10/ecom_images/140.jpg","url":"http://localhost/wordpress/wp- content/ecom-plugin- redirects/ecom_redirector.php?id=12165","currency_id":"$","current_price":"26.2"},{"title":"Genetic Engineering Opposing Viewpoints by DAVID BENDER - 1964 Hardcover","image":"http://localhost/wordpress/wp- content/uploads/2013/10/ecom_images/140.jpg","url":"http://localhost/wordpress/wp- content/ecom-plugin- redirects/ecom_redirector.php?id=130","currency_id":"AUD","current_price":"11.99"}],"no_follow":"rel=\"nofollow\"","new_tab":"target=\"_blank\"","related_products":[],"super_saver_shipping":"","shipping_availability":"","total_offers":"7","added_to_cart":""}] ` So the structure for the table is:   * asin   * title   * details (the product details in json) Will the performance suffer if I have to store like 10,000 products? Is there any other way of doing this? I'm thinking of the following, but the current setup is really the most convenient one since I also have to use the data on the client side:   * store the product details in a file. So something like ASIN123.json   * store the product details in one big file. (I'm guessing it will be a drag to extract data from this file)   * store each of the fields in the details in its own table field Thanks in advance! **UPDATE** Thanks for the answers! I just want to add some more details to my question. First, the records are updated for a specific interval. Only specific data such as the price or the title are updated. Second, I'm also using the json encoded data in the client-side so I thought at first it would be easier to just have it json encoded so I can easily use it in the client side without having to convert. Does this change your opinion about simply storing the fields in a regular table field in an RDBMS setup?


Is it time to do away with 'front-end' and 'back-end' as tech jargon?

It seems that the primary usage of these terms is either:   1. mutual mystification of contractors and/or clients who don't know what they are talking about or how to talk about it,   2. the innocent and ignorant (see this question) , or   3. laziness to avoid having to say user-interface/user-facing or business logic/database/infrastructure. Granted, you don't always want to explain to the boardroom what the aforementioned terms mean. Is that justification for adding confusion by using these terms to generalize and mis-generalize all kinds of technologies?


What is a best practice tier structure of a Java EE 6/7 application?

I was attempting to find a best practice for modeling the tiers in a Java EE application yesterday and couldn't come up with anything current. In the past, say java 1.4, it was four tiers:   1. Presentation Tier   2. Web Tier   3. Business Logic Tier   4. DAL (Data Access Layer ) which I always considered a tier and not a layer. After working with Web Services and SOA I thought to add in a services tier, but that may fall under 3. the business logic tier. I did searches for quite a while and reading articles. It seems like Domain Driven Design is becoming more popular, but I couldn't find a diagram on it's tier structure. Anyone have ideas or diagrams on what the proper tier structure is for newer Java EE applications or is it really the same, but more items are ranked under the four I've mentioned? **Aftermath:** Really, I should have reworded my question as my real intent was to ask where to put the business logic in a Java EE application? In thinking along those terms, I somehow concluded that the tier structure had changed, when it had not. However, with the advent of POJO programming and lightweight frameworks that I was using in my day to day work, I lost sight of all this. The tier structure of Java EE apps still holds to the same, but now instead of heavy weight EJB2 type business logic in the middle tier I was using POJO's with services to implement business logic.


Small Product backlog / user story feedback - media player application

I have been tasked with developing a short product backlog for the following: > A media player application is needed for playing mp3 files. It should have > the ability to search the users file structure for playable files which can > be played or imported into a media library for playing later. There should > be the usual options for starting, pausing and stopping playback of a > selected file… My solution / user stories are as follows:   * As a user I can use the media player application so that I can play MP3 files.   * As a user I want the ability to search for playable files to play them later   * As a user I want the ability to search for files so that I am able to import them to my media library.   * As a user I can use certain options on an app so that I can start, pause and playback a file. Am I on the right track?


Design review for application facing memory issues

I apologise in advance for the length of this post, but I want to paint an accurate picture of the problems my app is facing and then pose some questions below; I am trying to address some self inflicted design pain that is now leading to my application crashing due to out of memory errors. An abridged description of the **problem domain** is as follows;   * The application takes in a “dataset” that consists of numerous text files containing related data    * An individual text file within the dataset usually contains approx 20 “headers” that contain metadata about the data it contains. It also contains a large tab delimited section containing data that is related to data in one of the other text files contained within the dataset. The number of columns per file is very variable from 2 to 256+ columns. The original application was written to allow users to load a dataset, map certain columns of each of the files which basically indicating key information on the files to show how they are related as well as identify a few expected column names. Once this is done, a validation process takes place to enforce various rules and ensure that all the relationships between the files are valid. Once that is done, the data is imported into a SQL Server database. The database design is an EAV (Entity-Attribute-Value) model used to cater for the variable columns per file. I know EAV has its detractors, but in this case, I feel it was a reasonable choice given the disparate data and variable number of columns submitted in each dataset. **The memory problem** Given the fact the combined size of all text files was at most about 5 megs, and in an effort to reduce the database transaction time, it was decided to read ALL the data from files into memory and then perform the following;   * perform all the validation whilst the data was in memory    * relate it using an object model    * Start DB transaction and write the key columns row by row, noting the Id of the written row (all tables in the database utilise identity columns), then the Id of the newly written row is applied to all related data    * Once all related data had been updated with the key information to which it relates, these records are written using SqlBulkCopy. Due to our EAV model, we essentially have; x columns by y rows to write, where x can by 256+ and rows are often into the tens of thousands.    * Once all the data is written without error (can take several minutes for large datasets), Commit the transaction. The problem now comes from the fact we are now receiving individual files containing over 30 megs of data. In a dataset, we can receive any number of files. We’ve started seen datasets of around 100 megs coming in and I expect it is only going to get bigger from here on in. With files of this size, data can’t even be read into memory without the app falling over, let alone be validated and imported. I anticipate having to modify large chunks of the code to allow validation to occur by parsing files line by line and am not exactly decided on how to handle the import and transactions. **Potential improvements**   * I’ve wondered about using GUIDs to relate the data rather than relying on identity fields. This would allow data to be related prior to writing to the database. This would certainly increase the storage required though. Especially in an EAV design. Would you think this is a reasonable thing to try, or do I simply persist with identity fields (natural keys can’t be trusted to be unique across all submitters).    * Use of staging tables to get data into the database and only performing the transaction to copy data from staging area to actual destination tables. **Questions**   * For systems like this that import large quantities of data, how to you go about keeping transactions small. I’ve kept them as small as possible in the current design, but they are still active for several minutes and write hundreds of thousands of records in one transaction. Is there a better solution?    * The tab delimited data section is read into a DataTable to be viewed in a grid. I don’t need the full functionality of a DataTable, so I suspect it is overkill. Is there anyway to turn off various features of DataTables to make them more lightweight?  Are there any other obvious things you would do in this situation to minimise the memory footprint of the application described above? Thanks for your kind attention.


What is block level design in context of mobile application?

I was wondering if anyone can give me some direction related to "Block level design" in context of mobile application? Recently I saw a video in my university and a professional mentioned about building block level design of applications, since then it has stuck in my brain! It would be really helpful if someone can share their knowledge.


Why should I not do a masters degree

I have left university on July 2010 where I studied web design (as we all know you learn more by your self but that’s not the issue at the moment). Since then I have not managed to find a job (apart from a one month work experience), from the way things are going, and by taking into account the fact that all my university friends are in the same situation, I don’t think that I am going to find a job soon (within the industry) Now as we all do, even though I don’t have a job, I am still working on personal projects and try to keep up to date (I don’t need a job or uni to do this) – but I am thinking, because there is not work available, would it be worth going back to uni for a master degree? I know I don’t need it and I know that is unlikely that I will learn anything important, as I believe in self learning, and in most cases it is a lot more effective (but I have to say I don’t mind going back to school) The only reason I am thinking of doing the master is, (and this is where I need your help): If it takes me a year to get a job, then on the interview, would the employer think “what the hell did this guy do since he left university” – now if I go to university that would solve this problem. Or I’m I making up a problem that does not exist Plus, I know that employers need examples of sites that I have been working on, at the moment I only have 3 (as when working on personal projects, where their is not time limit I tend drag things in order to get them perfect, and they never get perfect) – so by going back to uni, then this problem maybe solved I said all this as I have read a lot about the fact that you don’t need to have a masters degree to work on web design market (and I totally agree) but considering my concern, the question is should I do a masters course to avoid just spending hours in my room working and learning in my own (but that it would be hard to convince employers that I was really learning in my room) Maybe because I’m still young age 22 not that old anyway :), but I don’t have the “dream” of being rich, so if I were to tell the truth I don’t really care of the fact that I don’t have a job (at the moment), because regardless, I am working on what I love every day, but I know that in the future when I will need the job I may find it harder to get one, if I neglect doing so now Every time I ask a question that I’m not sure about, I keep going on and on, but I really hope you get what I am trying to get across. By the way the course that I am looking at for a masters says that it would teach me how to do these: e-commerce e-government e-science e-learning I don’t know any of them, a part from e-commerce Thanks


What is the general tech news website every programmer should read?

A link and a quick explanation why would be very helpful. General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO. EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.


Generic object construction - Inherited Classes

Basically I am writing a MSMQ based multi-threaded messaging pattern utility library. It's like a set of components all inherited (directly or indirectly) one class that's called my base component class. Each of these messaging components have the ability to listen to multiple queues via multiple threads and to process messages via multiple threads. So I have a worker base class that executes itself on a thread, but in implementation you would inherit this class, and fill in the gaps. So I want to be able to basically construct a generic object that inherits this class on the fly, and then put it to work. So far I have this which works, but I am just wondering if there is a better way to do it out there. My current code...               public class EzQBaseComponent<TWorker> : IEzQComponent where TWorker : EzQWorker     {         /// LOTS OF CODE YOU DON'T NEED TO KNOW :"D              private void Listener_MessageRecieved(Guid listenerID, MessageQueue queue, Message msg, MessageQueueTransaction myTransaction)         {             try             {             lock (m_MessageRecievedLocker)             {                 if(myTransaction == null)                 {                     // YAWN                 }                 if(msg.Label == c_CustomComponentMessageCommandLabel)                 {                     // YAWN                 }                 else if(Workers.Count < DelegatedWorkers)                 {                     Type t = typeof(TWorker);                     ConstructorInfo[] conInfos = t.GetConstructors();                     ConstructorInfo correctConstructor = null;                     foreach (ConstructorInfo cInfo in conInfos)                     {                         if (cInfo.GetParameters().Count() < 1)                         {                             correctConstructor = cInfo;                         }                     }                          if (correctConstructor == null)                     {                         throw new Exception("Generic TWorker class does not contain a consturctor with '0' arguments. Cannot Construct class.");                     }                          TWorker worker = (TWorker)correctConstructor.Invoke(null);                          // YAWN                 }                 else                 {                     // YAWN                 }             }         }         catch (Exception Ex)         {             // NOOOO EXCEPTION!!         }     }      Basically, my base class has a no-parameter constructor. So I look for the one without parameters via reflection, and then use that constructor. Any thoughts on the construction of the generic object? Is that the best way?


Algorithm for optimal combination of two variables

I'm looking for an algorithm that would be able to determine the optimal combination of two variables, but I'm not sure where to start looking. For example, if I have 10,000 rows in a database and each row contains price, and square feet is there any algorithm out there that will be able to determine what combination of price and sq ft is optimal. I know this is vague, but I assume is along the lines of Fuzzy logic and fuzzy sets, but I'm not sure and I'd like to start digging in the right field to see if I can come up with something that solves my problem.