A new name for unit tests

I never used to like unit testing. I always thought it increased the amount of work I had to do.   Turns out, that's only true in terms of the actual number of lines of code you write and furthermore, this is completely offset by the increase in the number of lines of useful code that you can write in an hour with tests and test driven development. Now I love unit tests as they allow me to write useful code, that quite often works first time! (knock on wood) I have found that people are reluctant to do unit tests or start a project with test driven development if they are under strict time-lines or in an environment where others don't do it, so they don't. Kinda like, a cultural refusal to even try. I think one of the most powerful things about unit testing is the confidence that it gives you to undertake refactoring. It also gives new found hope, that I can give my code to someone else to refactor/improve, and if my unit tests still work, I can use the new version of the library that they modified, pretty much, without fear. It's this last aspect of unit testing that I think needs a new name. The unit test is more like a contract of what this code should do now, and in the future.   When I hear the word testing, I think of mice in cages, with multiple experiments done on them to see the effectiveness of a compound. This is not what unit testing is, we're not trying out different code to see what is the most affective approach, we're defining what outputs we expect with what inputs. In the mice example, unit tests are more like the definitions of how the universe will work as opposed to the experiments done on the mice. Am I on crack or does anyone else see this refusal to do testing and do they think it's a similar reason they don't want to do it?   What reasons do you / others give for not testing?   What do you think their motivations are in not unit testing? And as a new name for unit testing that might get over some of the objections, how about jContract? (A bit Java centric I know :), or Unit Contracts?


Working machines of developers - in what ways are they usually standardized or restricted?

My boss wants to introduce new guidelines for the computers in our company. This means that the software environments will be completely standardized with a predefined set of tools. The goal is that all machines are completely reproducable and exchangable. I'm wondering what the guidelines for developer's computers are in large companies, such as Google or Microsoft, especially companies which are certified according to some standard (e.g. ISO 9001). Do they allow developers to install software from the internet if they need it for some small task? (e.g. a code compare tool, CygWin, Windows Service Packs) or do they really want all needed tools in a fixed, predefined environment where all proposed changes must be discussed with a system administrator first?


Managing a website with version control?

The small website I built a long time ago is starting to pick up a little and I'm starting to run into problems with making changes. Originally, all the pages were .html and I would edit and test them offline to make sure everything worked. Then I realized how helpful php includes were, so I changed everything to .php and used includes. Without apache, I could no longer test offline, so with Filezilla, I would choose the "view/edit" option on files that were already on the server, edit them, and then have them uploaded again. This is what I've been doing so far and it's worked pretty well for the most part. I just save the temp file that filezilla creates, and let it upload it back to the server. Yesterday, I realized that one of the javascript files I had worked on the day before had been replaced by an empty file. This was something to do with sublime text keeping the non-existent temp file open/filezilla uploading an empty file - I'm not really sure what happened, but it shouldn't have been able to happen. And now, I need to change the design of the site, and doing that one page at a time would be noticeable, so I need to do it offline first. I would like to use version control and install apache so that I can completely test my site offline, but there are a couple problems I have with this. The first is that I have a Forum on the site. I could install mysql and export the tables, then import them offline, but then, while people are making posts on the website, the offline copy becomes out of date and I can no longer upload that back to the server. I also have some Python scripts on the site using WSGI. My webhost's settings are very specific, so if I wrote python scripts offline and ensured they were working, I wouldn't know if they were going to work online. Should I edit everything offline and upload it all back to the server when it works? What happens if a php or python script executes one way on my local machine than on the server?


Does an Open Source license exist that allows me to retain rights to revoke usage of software/source at any time, for any reason, and without warning? I want to allow others to use my software and source code for free but at the same time, I want the ability to revoke rights to usage if I don't agree with the ways that the software and/or source is being used.


How I could update a DB table using a POCO class bound in a DataGridView

I try to explain better using an example:   * I create the class Product with attibutes like that:              private string _ProductCode = "";     [DisplayName("ProductCode")]     public String ProductCode     {        get { return _ProductCode; }        set { _ProductCode = value; OnPropertyChanged("ProductCode"); }     }        * the class Product implements the interfaces: INotifyPropertyChanged, IEditableObject   * I create the class ProductList that has the following property:              public List<Product> Products { get; set; }        * I bind the class Product in a DataGridView control using the DataSource property              MyGridView.DataSource = ProductList.Products;        * I have the table **ProductListTable** on db SqlServer that has more column than the class **Product**   * When I push the button "Save" on my form I'd would like to save the ProductList on ProductListTable I'm really confusing about the way to follow ... I have to use Link 2 Sql, Entity Framework? I'm searching for something simple for a small project, but using POCO classes for rapresenting the data layer. Now how I should proceed for linking class to DB table?


Should I write an integration test that verifies rate limits?

This test would call a web service over and over for about a minute to confirm that a particular response code is returned, notifying us of our rate limit being reached. Not only is it a very slow test, it doesn't confirm much of anything, and wastes resources. I feel that this is like confirming that chugging a bottle of vodka will kill a human. Do we really need a test for it?


What's a good approach for updating millions of rows independently?

I have a MongoDB database with millions of users in collection. An aggregation function returns millions of results with the following format:               Array ( [_id] => Array ( [user] =>       MongoId Object ( [$id] => 52050d48e654f6342c002d42 )         [send] => 1         [open] => 1         [click] => 2 )      Now I need to update corresponding user with the new values (open/send/click) and for each of them add a flag, based on how the values compare with variable X. How would be a good approach to it without looping through results (this means loading GB of data in memory and doing millions of updates/finds) Thanks!


Best way of learning Python + GUI when coming from .NET

I've been developing applications in **C#** / **VB.NET** for about 3-4 years ( **.NET Framework** v2.0, 3.5, 4). I have also developed some command-line applications or scripts in C, and Python under Linux. Sometimes I need to develop my applications in another languages, like **Python** , but the ~~problem~~ thing is that lots of those applications require a GUI. Maybe not a too complex one, but it does require some windows with _buttons_ , _text boxes_ , _list boxes_ ,... What books/tips/tutorials do you suggest me to start working with that language and be able to deploy my deliverables not only in **.NET**? **Note:**   Learning python is not the big deal here, because I already know the basic of it. I just want to focus on the GUI. _Maybe this question should be onUI instead of here? If so, please, migrate it :)_


Why is Quicksort called "Quicksort"?

The point of this question is not to debate the merits of this over any other sorting algorithm - certainly there are many other questions that do this. This question is about the name. Why is Quicksort called "Quicksort"? Sure, it's "quick", most of the time, but not always. The possibility of degenerating to O(N^2) is well known. There are various modifications to Quicksort that mitigate this problem, but the ones which bring the worst case down to a guaranteed O(n log n) aren't generally called Quicksort anymore. (e.g. Introsort). I just wonder why of all the well-known sorting algorithms, this is the only one deserving of the name "quick", which describes not how the algorithm works, but how fast it (usually) is. Mergesort is called that because it merges the data. Heapsort is called that because it uses a heap. Introsort gets its name from "Introspective", since it monitors its own performance to decide when to switch from Quicksort to Heapsort. Similarly for all the slower ones - Bubblesort, Insertion sort, Selection sort, etc. They're all named for how they work. The only other exception I can think of is "Bogosort", which is really just a joke that nobody ever actually uses in practice. Why isn't Quicksort called something more descriptive, like "Partition sort" or "Pivot sort", which describe what it actually does? It's not even a case of "got here first". Mergesort was developed 15 years before Quicksort. (1945 and 1960 respectively according to Wikipedia) I guess this is really more of a history question than a programming one. I'm just curious how it got the name - was it just good marketing?


Sum of divisors of numbers of the range ~ 10^6

I was trying to find the sum of divisors of numbers upto 106. The test cases are like of the order of 105. I have done some pre processing like               int divisors(int num)     {         int sum=0;         for(int i=1; i*i<=num; i++)             sum += (num%i)? 0 : ((i*i==num)? i : i+num/i);         return sum;     }      Is there any better method to do the same. Should I also make an array of prime numbers or something like that?


What diagram would be the best to describe the situation

I am working on a software integrated with the hardware component. I need to create a simple diagram to express that:   1. Certain activity runs in a cycle (the device continously monitor a temperature)    2. When the temperature deviates from the baseline and remains so for 10 seconds, a function is called I am writing a high level document and I am not sure how to capture this - UML diagrams do not seem to be suitable..but maybe an activity diagram?


strategies to keep tabs of memory leaks in non memory-managed languages

When it comes to non memory managed languages such as C, C++ or Fortran (my case), it becomes increasingly difficult to keep track of memory allocation/deallocation, especially when ownership must be shared. I implemented refcounting for my objects, but this makes it even more complicated as there's no place where an object gets deallocated. Every reference decrement is a potential deallocation point. So it's now more and more difficult for me to track down memory leaks. I was wondering about some established techniques to deal with memory management in non-memory managed languages, apart from valgrinding your way around. **Edit:** I am more interested in active programming strategies (which are general).


Logistics of code reuse (OOP)

One of the driving points behind OOP is code reuse. I am curious about the actual logistics of this and how others both in team or solo handle it. For example lets say you have 5 projects you have worked on and between them you have a ton of classes that you think would be useful in other projects. How do you store them? Are they just in the normal project repository or do you break out the relevant classes and have them (as now copies) in another unique source repository that only houses code pieces that are intended to be reused? How do you go about finding or even knowing that there is a good piece of code out there that you should reuse? It's easier if your solo because you remember that you have coded something similar but even then it becomes kind of a stretch. If there is some way that you are storing these pieces of code do you then also have them indexed and searchable by tag or something. I fear that it just boils down to some tribal knowledge that you just know that for situation A i need solution B and we have a good piece of code that already can help here. A bit verbose but I hope you get what I am aiming at. If you think of a better way to make the question clearer please have at it :) TIA!


What should I do when my code smells?

I'm a novice programmer and often when I'm working on my own projects, I always get the feeling that the design of my code is not the best it could be, and I hate this feeling. I end up spending time looking things up, but then I become overwhelmed easily with many details, such as design patterns to choose from and when to use an abstract class or an interface. Am I supposed to try and learn a little bit of everything at once?


What non-theoretical, practical programming language has no reserved keywords?

I have been searching for a _practical_ programming language that has no reserved keywords but I haven't had any luck finding one. I am working on a programming language for my own edification and entertainment and I haven't needed to include any keywords yet, that is what led me to my search and the question: I don't see convenience to the compiler writer as being important to the end user of the language. Computers are powerful enough now days to be able to infer meanings from context. No more than a writer needs to label nouns, verbs and such when writing a novel, why should a programmer have to label functions and variables with `function x() {}` or `set x = 1` or `var x = 1` etc; when I can infer from the context of the statements that it is a function declaration or an invocation or that a label is an assignment to a value or a reference to that labels value? Here is a concrete example of what my current parser is doing, no need for reserved keywords to support common things that would normally have a bunch of _noise_ like `func` or `function` or `dec` or what not. _Function Declaration_               sum3(a,b,c) -> a + b + c.      _Function Invocation_               x = sum3(1,2,3).      _Anonymous Function Named x_               x = (a,b,c) -> a + b + c.     y = x(1,2,3).      **I would like to know why are keywords that important to a successful programming language?**


Have you worked at a place which did not mandate annual employee evaluations or like?

Samuel Culbert thinks that they are evil. http://online.wsj.com/article/SB122426318874844933.html I tend to agree - there is nothing worse than for someone creative (let's assume I am) to be judge on a 5-point system and to be stored away in HR department. However, I am not sure how many companies actually followed his advice. Have you ever worked at a place which never required one?


Software license for a publicly funded institution

This is probably something that should go to the legal department -- presuming they have any inklings about software licensing -- but what software license should I use against code developed for use at a publicly funded institution (in the UK)? Specifically, it's internal-use code for various university systems. I believe it should be open source -- and feel that the MIT license would be most appropriate -- but I have a feeling that certain proprietary procedures and policies, that might be revealed by the code, _may_ be restricted. ("May" in italics, because I'm not 100% sure: As a publicly funded body, I am under the impression that anything that doesn't conflict with the Data Protection Act 1998 should be made available under the Freedom of Information Act 2000.) This is largely moot, because the source won't be published publicly. (Although, presumably, if anyone requests it, then that's allowed; providing sensitive information is redacted.) However, I'm interested to hear others' thoughts on the matter.


Moving business logic from services to classes?

I have a Grails application with a number of services that are starting to get very large. The flow in the majority of my service methods is   1. Database read (Returns DBCursor from MongoDB)   2. Iterate through the cursor and perform some operations.   3. Return results from operation. I'm beginning to consider moving the logic in Step 2 out to Groovy classes in order to clean up my code base and allow for unit testing. However reading some guidelines they state that the majority of the logic should go in services. Is moving this logic out to Groovy classes going aghainst best practices?


Does Implementing a New Function Imply A New Major Version?

I am currently developing a new library for RESTful web requests in Puredata, and am about to release version 1.0.0. This version will not implement all HTTP verbs, only GET, PUT, POST and DELETE. In the next version, this library will most likely include the other HTTP verbs for RESTful requests, PATCH, HEAD, OPTIONS, CONNECT, TRACE. I am using Semantic Versioning for the version numbers. In the specs it says: > Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards > compatible functionality is introduced to the public API. It MUST be > incremented if any public API functionality is marked as deprecated. It MAY > be incremented if substantial new functionality or improvements are > introduced within the private code. It MAY include patch level changes. > Patch version MUST be reset to 0 when minor version is incremented. > > Major version X (X.y.z | X > 0) MUST be incremented if any backwards > incompatible changes are introduced to the public API. It MAY include minor > and patch level changes. Patch and minor version MUST be reset to 0 when > major version is incremented. Now, I am unsure what to after implementing the remaining verbs: On the one hand, the functionality is backwards compatible, as the already implemented functionality does not change. On the other hand, the functionality is changing, as issuing a HEAD request will not result in an error message on the console, but in an output. In the first case, only an increase to the minor version is needed, in the second case, the major version must be increased. What is the correct interpretation in this case?


Dealing with management that does not see value in improvements that are not immediately visible to the user

I can understand schedule pressure. You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements. For example, Apple recently introduced Automatic Reference Counting for iOS programs. This is a major improvement over the manual retain/release calls one previously had to use. The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down. I recently mentioned to my boss that I wanted to switch to automatic reference counting. His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO. There are a lot of similar examples. The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks." How should I handle the situation? EDIT: Thanks for the responses. Keep 'em coming. Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like. Apparently their programmer sides have been overwhelmed by other pressures.


Licensing OS code, is it possible to protect certain blocks of code?

I'm working on a piece of code which is free to use, but when a license code (or serial key or any other term like that) has been bought will remove some advertising. The code will be freely available as open source, probably under a GPL license, but of course I would rather not have people messing around with the code that verifies the license code with an external provider. Is there any way to legally protect this piece of code from being modified, or at least from being distributed after being modified, keeping the rest of the code "open"?


Which commit should close a Github issue when multiple commits are responsible?

I want to close issues in Github via my commit messages, but I'm not sure which commit should contain the magic "Closes #XXX" string when multiple commits are responsible for closing the issue. Specifically, I'm wondering if the last commit on my feature branch (always merged with `--no-ff`) should close the issue, or if I should close it via the merge commit that sort of "summarizes" the entire feature branch? Is there a standard way of doing this, something endorsed by the Git community?


Using a variable in a Global context in webapps

In a webapp, I have a scenario where I need some kind of global context (Static like) for few variables, _for the current thread only_. If there are 3 different concurrent users, then I expect three corresponding global context variable for the 3 separate threads/sessions. Using a Static variable makes its scope global for all the threads. Is there a way in which I can achieve this?


Adding new features to an old application

I wrote a .NET Windows application using framework 3.5. At that time, 3.5 was very new and I had knowledge of framework 2.0 only. Due to deadline, I didn't use any new features of version 3.5 and delivered the application. There was no time. It is now two years and the app. is running fine, but my clients have requested new features. There is a major scaling needed. The new code that I wrote so far uses many new features of .NET 3.5 and I am concentrating on reducing the new code size. The problem is that the new classes that I want to write are sometimes creating redundant methods for doing the same thing. I am not disturbing the old code. How to manage? If I replace old classes with new ones, it risks functionality and need thorough testing again. If I don't, the project size is increasing.


Are "skip deltas" unique to svn?

The good folks who created the SVN version control system use a structure they refer to as "skip deltas" to store the revision history of files internally. A revision is stored as a delta against an earlier revision. However, revision N is not necessarily stored as a delta against revision N-1, like this:               0 <- 1 <- 2 <- 3 <- 4 <- 5 <- 6 <- 7 <- 8 <- 9      Instead, revision N is stored as a delta against N-f(N), where f(N) is the greatest power of two that divides N:               0 <- 1    2 <- 3    4 <- 5    6 <- 7     0 <------ 2         4 <------ 6     0 <---------------- 4     0 <------------------------------------ 8 <- 9      (Superficially it looks like a skip list but really it's not that similar - for instance, skip deltas are not interested in supporting insertion in the middle of the list.) You can read more about it here. My question is: Do other systems use skip deltas? Were skip deltas known/used/published before SVN, or did the creators of SVN invent it themselves?


Multiple parameters vs single parameter(object with multiple properties)

I have an Entity `Student` with following properties - (`name`, `joinedOn`, `birthday`, `age`, `batch`, etc.) and a function `fetchStudents(<params>)`. I want to fetch students based on multiple filters. In my method I have two ways to pass filters.   1. Pass all filters as params to the method   2. Make a class StudentCriteria with filters as fields and then pass the object of this class While working in java I always go with the second option but recently I'm working in php and I was advised to go with the first way. I am unable to figure out which way is better in maintaining the code, reusability and performance wise. Thanks.


how to integration dynamic web fields and forms

I'm trying to find a way to design backend that will be handling customized web forms creation on the fly. Once created those forms will be injected to part of the existing web pages. I've created dynamic forms successfully but I'm unable to figure out how I can integrate these newly created forms or custom fields into my web pages to handle like posting data to some restful api most probably, or some unified interface that can handle all of the custom forms/fields? I'm using backbonejs for my client side and for dynamic forms I'm using backbone.form plugin to create custom forms and fields on the fly. I'm persisting this on server. I've figured this part after a lot of RnD. I can show these forms and newly added fields to my already built forms on front end using backbone and presisted schema and data. But problem is, there can be multiple forms and many fields; think of it as multi tabs. I need to device a workaround in a way that all of my forms can post data to some unified/common/generalized server route where I can manipulate it.


How to store pdf files to MySQL and then list, open them using C#

I'm creating a c# employee management system app, I've created a form for Employee files and I don't have any idea how to store pdf files to mysql and then list and open them with c#.


Continuous Integration / Deployment: Test on commit, pull request, or what?

I read about CI/CD, loved it, but I'm having trouble with the details as everything I read was high level. Some authors seemed to suggest that there couldn't be any failing commits on the repository (or master branch?), so a programmer that is delivering bad code would be stopped and he wouldn't be able to create a big mess. He would be forced into fixing his code so that the tests pass. Others mentioned that the trigger would be the pull requests, not the commits. I haven't used pull requests a lot to be honest, and besides aren't they something external to git? They aren't part of git AFAIK, but part of services like github, bitbucket, etc., so I wasn't sure if I should bind my workflow to something like that. Any thoughts on this will help me greatly. Please also mention which tools you are using, eg: Jenkins, Buildbot, etc. None of the tools I have tried were very friendly IMO. The docs and examples were lacking or tied to certain technologies like java, or services like github. I even considered building my own, it shouldn't be too hard to get the basic functionality. Right?


How to create contracts in python

I am currently learning Python (from Java) and have a question on contracts. _Example: an application defines an interface that all plugins must implement and then the main application can call it._ In Java:               public interface IPlugin {        public Image modify(Image img);      }           public class MainApp {        public main_app_logic() {           String pluginName = "com.example.myplugin";           IPlugin x = (IPlugin) Class.forName(pluginName);          x.modify(someimg);          }     }      The plugin implements the interface and we use reflection in main app to call it. That way, there's a contract between the main app and the plugin that both can refer to. How does one go about doing something similar in Python? And also, which approach is better? _P.S. I'm not posting this on SO because I'm much more concerned with the philosophy behind the two approaches._


Using PDO with MVC

I asked this question at stackoverflow and received no response (closed as duplicate with no answer). I'm experimenting with OOP and I have the following basic MVC layout:               class Model {         // do database stuff     }          class View {         public function load($filename, $data = array()) {             if(!empty($data)) {                 extract($data);             }                  require_once('views/header.php');             require_once("views/$filename");             require_once('views/footer.php');         }     }          class Controller {         public $model;         public $view;              function __construct() {             $this->model = new Model();             $this->view = new View();                  // determine what page we're on             $page = isset($_GET['view']) ? $_GET['view'] : 'home';             $this->display($page);         }              public function display($page) {             switch($page) {                 case 'home':                     $this->view->load('home.php');                 break;             }         }     }      These classes are brought together in my setup file:               // start session     session_start();          require_once('Model.php');     require_once('View.php');     require_once('Controller.php');          new Controller();      Now where do I place my database connection code and how do I pass the connection onto the model?               try {         $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE.'', DB_USERNAME, DB_PASSWORD);         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     } catch(PDOException $err) {         die($err->getMessage());     }      I've read about Dependency Injection, factories and miscellaneous other design patterns talking about keeping SQL out of the model, but it's all over my head using abstract examples. Can someone please just show me a straight-forward practical example?


Is Object Oriented stuff really that important?

For years, I have been doing Algorithmic stuff, writing scalable data structures for internet search, for example Randomized Binary Search Trees for Auto Recommendation, BitMaps, Wisdom of Crowd based Algorithms using Graphs, writing some interesting Machine Learning Algorithms like Clustering, Anomaly Detection, working on Information Retrieval stuff and so on There is a common thing in the things that I have mentioned above. All the above stuff;each if coded in a language like C++ requires handful of classes. I mean they are interesting problems but they are not complex in terms of heavily loaded Object Oriented stuff. I have never used Inheritance, virtual stuff etc. Though I have heavily used Generic Programming, Templates and so on. I love C++ (- Bulky OO stuff, As I like what Joe Armstrong's, creator of Erlang says, In OO World if you ask for a banana you get a big jungle alongwith gorilla holding the banana). I enjoy coding in other languages like Java, Python too. Now my question is since I am enjoying the kind of projects/Algorithms I am working on do I need to really learn OO stuff, will I be a better coder/designer just by using the stuff like Inheritance, Dynamic Polymorphism (virtuals)? OR can I move to the world of Functional Programming (I have not done it till now) which attracts me more as I can just focus on tasks/algorithms and not let Kingdom Of Noun based OO stuff, has-a, is-a rule me? In short will/can OO stuff help me at all for the kind of projects/Algorithms that I have mentioned above? EDIT: One extremely interesting link to add here: http://steve-yegge.blogspot.in/2006/03/execution-in-kingdom-of-nouns.html


How can a programmer refine their skills in non-visual ways?

I feel like when I am not writing, I am reading. When I come home from my programming job I write and read software and about software. The problem is though, both reading and writing requires my eyes to be focused. That doesn't work when I'm biking, cooking shopping for groceries. Sometime I use text-to-speech programs to listen to blogs, but I feel like there could be more. What ways can a software developer learn more without requiring eye focus? How to blind coders learn the craft?


What steps should be taken to make sure your software is usable by disabled people?

I want to make sure a piece of software I am writing is usable by people with various disabilities such as blindness and an inability to use a mouse and / or keyboard. Unfortunately I have no experience with things such as screen readers or other methods that disabled people use to make using a computer easier / possible. I've never really had much experience with disabilities at all and unfortunately I don't know any disabled people who I can ask. I was wondering what other people do to make sure that their software is available to a wide range of people with varying abilities? This seems to be a subject matter that is often ignored by developers and I think it is a real shame. Edit: If anyone has any specific information related to desktop development in addition to the information already provided in the answers below I would be grateful. Particularly methods that apply to cross platform development on Windows, Mac OS X and Linux.


Web Development on Windows but on Linux Environment

I do PHP Development on WAMP but sometime it don't work properly when I upload the files to a Linux server, its involve a lot of testing and annoying. I am looking for a solution to do PHP Development on Windows but the files will be sync with Linux Server. I do not want to use SFTP/SSH clients like WinSCP to view or edit files. I was told to look at vagrant, is there any other solution?


How to review code that you do not understand?

I have been given the role to improve development in our company. The first thing I wanted to start was code reviews since that has never been done here before. There are 3 programmers in our company. I am a web programmer, my known languages are mainly PHP, ActionScript and JavaScript. The other 2 developers write internal applications in VB.net We have been doing code reviews for a couple weeks now. I find it hard to understand VB code. So when they say what its doing, for the most part I just have to take their word for it. If I do see something that looks wrong, I explain my opinion and I explain how I would address it in one of the languages I know. Sometimes my suggestions are welcomed but many times I am told things like "this is the best way of doing it in _this_ language" or "that doesn't apply to _this_ language" or similar things of that nature. This may be true, but without knowing the language I am not sure how to confirm or refute these claims. I know one possible solution would be to learn vb so I can do better code reviews. I really have no interest in learning vb (especially since I have a list of other technologies I am trying to learn for my own projects) and would like to keep this as a last resort but it is an option. Another idea that came to me is, they both have interest in C# and so do I. Its relative to them because its .net and relative to me because its more similar to the languages I know. Yet it is new to all of us. I thought about the benefits of us all collaborating on a pet C#.net project and reviewing each others code from that. I guess theres also the possibility hiring a consultant to come in and give us some code reviews. What would you recommend I do in this situation.


Is there a correlation between code complexity and developer productivity?

Is the time spent refactoring a code base worth it in the long run, in terms of developer productivity? It seems pretty clear to me that modifying a clean, well designed system is much simpler and faster than working on a poorly designed one, but I'm after some solid evidence. Are there any studies around this topic?


is it considered plagiarism to comment out code I copied from elsewhere?

If the plagiarized code is commented out because I found another way to solve the problem, but I forgot to remove the comments, is that considered plagiarism? I used the copied code to help me debug and compare the output between my own code and the copied code. In the final code, I commented out the copied code. Since comments don't affect how the code runs, can comments be considered plagiarism?


N queens, X by Y board decision problem interview question

I was asked the following question in an interview today and I've been thinking about it ever since. I was not able to answer it and haven't been able to find a solution online. Given a chess board with dimensions X by Y and N queens, determine whether it is possible to arrange these queens on the board such that they cannot attack each other. A 2 x 3 board with 2 queens does have a solution so the algorithm would return true:               Q . .     . . Q      I'm looking for a programming approach to this puzzle, not just ways to solve it on paper, for example.


db design: circular references for the-one-of-many case

There are many questions about circular references around (if they are bad or not) but this one will be concrete. Consider the following case. There are two models Image and User. Users have associated images and they can pick one of them as their profile image. There are essentially two ways of modelling this (forgive me my pseudo-syntax): 1)               User:        id - primary key        profile_image - nullable foreign key to Image          Image:        id - primary key        user - foreign key to User      2)               User:        id - primary key          Image:        id - primary key        user - foreign key to User        profile - boolean true/false         Both of these approaches have some problems.   **In the first case:**   * well-known chicken-egg problem (e.g. foreign keys must be off when recovering from backup)   * It can happen that profile image points outside of domain of images associated with user   * There is a redundant dependency link (i.e. one more relation when compared to the first solution). That will have some impact on an application code   * What if we later decide to have an ordering on images where the first one is the profile one? **The second case:**   * There is slight data redundancy (many times **false** )   * **true** can occur more than once   * slightly less intuitive (at least for me) So my question is, which of these two solutions is better/cleaner? What do you prefer and how to tackle problems they bring.


Are these programming "classics" still relevant today and should I read them?

I have come across numerous older posts that highly recommend the following language agnostic programming books:   1. **Code Complete** by Steve McConnel   2. **The Pragmatic Programmer** \- Andrew Hunt and Dave Thomas   3. **Programming Pearls** \- Jon Bentley   4. **Refactoring** \- Fowler, Beck, Brant, Opdyke, Roberts   5. **Design Patterns** \- Gamma, Helm, Johnson, Vlissides   6. **Don't Make Me Think: A Common Sense Approach to Web Usability** \- Steve Frug I found these recommendations on Jeff Atwood's Coding Horror and Scott Hanselman's Blog and mostly the same recommendations on other sites as well. If I read these book today, are they still relevant and will they improve my code, expand my mind, thinking abilities and generally make me a better programmer? Are some timeless, while others are not? Are there other brilliant books, I have missed, that will be useful today?


Does DDD make sense for apps which mostly present data?

I'm responsible for designing a dashboard and data manipulation front-end for a sale transaction database and am not quite sure what type of architecture to use. The database is populated by an external ETL system. The required functionality for my app is very simple; it must display a few alerts of exception conditions it detects in the database, present a few charts and tables, and some basic CRUD operations on a few tables. There is very little _behaviour_ required; the business will use the app to find out about things, rather than do things. Given this lack of behaviour, does a DDD approach make sense? My current thinking is to create database views to encapsulate the queries my app will need, wrap these views up with an ORM, and have the web controller query the repository layer to get an ORM object with the data it needs. This ORM object would then be passed into the presentation layer. This does of course create strong coupling between the database, the ORM framework, the presentation layer, and my logic. A reasonable amount of what logic there is would wind up in the database views. Can I make a DDD approach work for this kind of app, or is there a more suitable way of doing it?


Identity matrix using Fortran 95

The following code give the identity matrix of any size the user wish it to be:               program identitymatrix            real, dimension(:, :), allocatable :: I       character:: fmt*8       integer :: ms, j           print*,'the size of the matrix is?'      read*,ms            allocate(I(ms,ms))       I = 0                           ! Initialize the array.       forall(j = 1:ms) I(j,j) = 1     ! Set the diagonal.            ! I is the identity matrix, let's show it:            write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'       ! if you consider to have used the (row, col) convention,        ! the following will print the transposed matrix (col, row)       ! but I' = I, so it's not important here         write (*, fmt) I(:,:)            deallocate(I)          end program identitymatrix     (the end of the code )      I am a bit confused about these two code pieces ?               write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'          write (*, fmt) I(:,:)      What does `(A,I2,A)` do exactly?


What arguments are there in favor of weak typing?

This came up in a discussion with a friend, and I found myself hard-pressed to think up an any good arguments. What benefits do weak typing confer?


The distributed office, is it viable?

I've played with the thought of how I would construct my dream company and how one could make it highly attractive to great programmers. If one could employ a few "superstar" programmers instead of many "good" ones. One thing I personally would enjoy is the freedom to work from whenever I wanted. So I could travel around different cities if I felt like it and work remotely, or I could simply sit at home when there was crunch mode. In my experience however you do want some kind of office with peers where you can discuss things and have company "culture" So say you wanted to hire a bunch of top talent programmers, possibly from different countries and cities. How would one set it up to compete with campuses? Having a completely office-less company seems a bit sub-optimal, you probably want some office space where people can meet and chose to work from. I guess what one could do is have small offices in different countries and let people work from the ones they chose. Programmer's could take off for "crunch- modes" when warranted but also work from location when teamwork and face to face was needed Another model would be to instead of having offices of your own hire seats in offices where other programmers work. That way even if there's only one or two employees in your city you could still get some company if you felt "lonely" from working remotely. Another idea is that like one week every other month you take the whole team to the same location. Which might not be an office but could be just some interesting city or attractice resort and work together from there. People with spouses might have a problem with things like that though. You might also have a network of company apartments in different cities (for 2-3 people) , both where you have offices and also in some other locations so programmers or teams or programmers could roam around and "clump" together as they wish. If it was legal (I'm not sure how it differs from country to country) you could even swat two flies in one go and have combined office/apartments in different cities. "Hack Pad: London" "Hack Pad:Berlin" etc a) So I guess my questions are, would a setup like this be viable? How could one improve the concept? b) Would you find a company which gives you this kind of freedom attractive or would you prefer one with a big office you go into every day? So basically, what would make a "superstar" programmer chose working with a company setup like this instead at the google, facebook or microsoft campus where you get the fun and company of lots of talented individuals.


Code ownership with multiple Scrum teams

If two Scrum teams use the same software component, who is responsible for providing a clear architectural vision of that component and maintain/develop this vision as the code base evolves? In Scrum you are supposed to have a collective code ownership, so how to make sure that development done by Team A doesn't interfere with development done by Team B?


AngularJS: directives and controllers: resolve, loading, reloading

I have a philosophy question about AngularJS and directives but correct implementation of the next problem solves it. So,   1. I need an AngularJS directive,   2. It loads some data via _several_ (not one!) `$http` requests,   3. It shows it,   4. It updates data (and re-shows it) every second,   5. The view has to be unchanged while data is loading/reloading. How should I do it in a correct way? And what about if I need a controller but not directive? (Difference is that controllers have `resolve` options but directives don't.) P.S.: I need a concrete scheme or a code! I know which components (`$http`, `$q`, etc.) I have to use. I don't know how to do it in a **right way**!


How to best implement K-nearest neighbours in C# for large number of dimensions?

I'm implementing the K-nearest neighbours classification algorithm in C# for a training and testing set of about 20,000 samples and 25 dimensions. There are only two classes, represented by '0' and '1' in my implementation. For now, I have the following simple implementation :               // testSamples and trainSamples consists of about 20k vectors each with 25 dimensions     // trainClasses contains 0 or 1 signifying the corresponding class for each sample in trainSamples     static int[] TestKnnCase(IList<double[]> trainSamples, IList<double[]> testSamples, IList<int[]> trainClasses, int K)     {         Console.WriteLine("Performing KNN with K = "+K);              var testResults = new int[testSamples.Count()];               var testNumber = testSamples.Count();         var trainNumber = trainSamples.Count();         // Declaring these here so that I don't have to 'new' them over and over again in the main loop,          // just to save some overhead         var distances = new double[trainNumber][];          for (var i = 0; i < trainNumber; i++)         {            distances[i] = new double[2]; // Will store both distance and index in here         }              // Performing KNN ...         for (var tst = 0; tst < testNumber; tst++)         {             // For every test sample, calculate distance from every training sample             Parallel.For(0, trainNumber, trn =>             {                 var dist = GetDistance(testSamples[tst], trainSamples[trn]);                 // Storing distance as well as index                  distances[trn][0] = dist;                 distances[trn][1] = trn;             });                  // Sort distances and take top K (?What happens in case of multiple points at the same distance?)             var votingDistances = distances.AsParallel().OrderBy(t => t[0]).Take(K);                  // Do a 'majority vote' to classify test sample             var yea = 0.0;             var nay = 0.0;                  foreach (var voter in votingDistances)             {                 if (trainClasses[(int)voter[1]] == 1)                      yea++;                 else                    nay++;             }             if (yea > nay)                 testResults[tst] = 1;             else                 testResults[tst] = 0;              }              return testResults;     }          // Calculates and returns square of Euclidean distance between two vectors     static double GetDistance(IList<double> sample1, IList<double> sample2)     {         var distance = 0.0;         // assume sample1 and sample2 are valid i.e. same length               for (var i = 0; i < sample1.Count; i++)         {                var temp = sample1[i] - sample2[i];             distance += temp * temp;         }         return distance;     }      This takes quite a bit of time to execute. On my system it takes about 80 seconds to complete. How can I optimize this, while ensuring that it would also scale to larger number of data samples? As you can see, I've tried using PLINQ and parallel for loops, which did help (without these, it was taking about 120 seconds). What else can I do? I've read about KD-trees being efficient for KNN in general, but every source I read stated that they're not efficient for higher dimensions. I also found this stackoverflow discussion about this, but it seems like this is 3 years old, and I was hoping that someone would know about better solutions to this problem by now. I've looked at machine learning libraries in C#, but for various reasons I don't want to call R or C code from my C# program, and some other libraries I saw were no more efficient than the code I've written. Now I'm just trying to figure out how I could write the most optimized code for this myself. I cannot reduce the number of dimensions using PCA or something. For this particular model, 25 dimensions are required.


Meet the deadline or less bugs?

In an ideal world it is preferrable to meet the deadline with less bugs. But from your experience which is more preferrable/acceptable:   1. Meet the deadline but has a number of bugs because developer rush into things   2. Less bugs but not quite meet the deadline because the developer is very rigorous in writing the code


Slight extension for SQL prepared statements syntax. Need advice

In my database abstraction library I am extending SQL prepared statements syntax to hint a parser with expected literal type. I take it as a very essential improvement, my reasoning you can read here. If you want to question the idea itself, please let me know in the comments - I'd like to start another question instead of mixing it here. The advice I want is on the syntax. I am quite ignorant of all the languages and dialects beside php and mysql, and may be there already a general purpose solution I am unaware of. If not - then I want to know your personal opinion or suggestion. At the moment, only positional placeholders supported. Yet I was asked many times to add support for the named ones. However, I cannot decide which syntax to choose for that. At the moment I mark a conventional question mark with single letter, i.e. `?s` \- string, `?i` \- int, `?n` \- name (identifier) and so forth. Yet for the named placeholder (`:name` style) the only sane option to me is               i:name      or, if I decide to add more verbose modifiers, even               int:name      so, the query would look like               SELECT * FROM ident:table WHERE id IN (int:id)      The question is: do you see any drawbacks for such a syntax? Do you have a suggestion for any other style? Do you think it's readable at all? Another question is on repeating things. At the moment I have two placeholders for the arrays - `?a` for the comma separated string list and `?u` for the `?n=?s` pairs. It bugs me a long time already, that such a syntax is superfluous, yet insufficient. What if I need a set of comma-separated identifiers? Or even a complex statement like whole VALUES clause? With some sort of repetition operator I can make SQL query building dramatically better. Here are examples of what I am thinking of:               SELECT * FROM table WHERE id IN([?i])     SELECT [?n] FROM table     INSERT INTO table VALUES [(?i,?s,?s,?s)]     UPDATE table SET [?n=?s]      As you can see, I use square brackets to designate a repetition. However, I am still not sure if I should use them. First objection is that they will collide with SQL server identifier syntax. Next is rather philosophical one - it is another syntax element and I want to introduce as less changes to the syntax as possible. Also, this syntax will require much more complicated parsing logic, which I am trying to avoid too. So - another option is just to extend the set of types, either with distinct placeholders like `?k` for the list of numbers, `?o` for the list of identifiers, of with adding a single=letter modifier to the existing type like `?as` (or `?astr` or `astr:name`) is an array of strings, `?an` and the like. There is another option - to detect repetitions automatically. If we have a scalar - format it as a single value. If it's array coming - format as a comma-separated list. However, many people find this approach unacceptable, as it can lead to unpredictable results and erroneous (however still safe) query. I am still in doubts if I may choose this way.


Accessing a private array when I have an extension method

I'm trying to make a number of data classes for my C#/XNA game, which would essentially be a wrapper around `T[,]`:               public interface IGrid<T>         where T : struct     {         Point Size { get; }         T this[int x, int y] { get; set; }     }      For example, I might have a Heightmap object which is essentially an `IGrid<float>`, or I might have a Level.TileData object which is an `IGrid<byte>` or `IGrid<int>`. These could be entirely separate classes with specific helper methods, etc. I also made a small extension library that operates specifically on any 2-dimensional array:               public static class Transformations     {         static T[,] Transpose(this T[,] value);         static T[,] FlipHorizontal(this T[,] value);         static T[,] FlipVertical(this T[,] value);         static T[,] RotateClockwise(this T[,] value);         static T[,] RotateCounterClockwise(this T[,] value);     }      However, when I actually implement `IGrid<T>`, I encounter a small design issue. Because the backing array would be private/protected, any client code that actually uses `IGrid<T>` would be unable to use my extension library. According to CA1819 and Eric's blog, publicly exposing an array (even via properties!) is a bad idea, as it would be fully mutable. The suggested workaround is to clone the array, then expose it as an immutable type (which means I still don't have an array to use the library on). Am I overthinking things, or is there an elegant solution here? I really like the idea of using indexers to read/write data on the object, but in some situations I _might_ want to work with the entire array at once.


ACM membership vs ACM online free articles (Association of Computer Machinery)

I am a software developer. I consider joining ACM. However, I find that there are free articles on ACM Ditial Library, e.g. http://portal.acm.org/citation.cfm?doid=1953122.1953141 In addition to that, there are free RSS feeds I can subscribe to, e.g. http://cacm.acm.org/blogs/blog-cacm/109710-new-sql-an-alternative-to-nosql- and-old-sql-for-new-oltp-apps/fulltext The memberhsip type I consider joining is ACM Professional Membership PLUS ACM Digital Library $198 USD https://campus.acm.org/public/qj/ProfQJ/qjprof_control.cfm?form_type=Professional&promo=QJPUB **What are things available for ACM paid members ONLY**?, below is the list I know **1)** free safari, 24x7 ebook library Please contribute your opinions? Should I join ACM or use its free online document? My interest is in advanced topics in web app, database app.


Software/Tool used in some presentations (TechEd, PluralSight, etc)

Does anybody know what application is used in some presentations in TechEd, PluralSight, etc? It looks like the following: ![enter image description here](http://i.stack.imgur.com/qGtHe.jpg) but it also allows drawing arrows to emphasize on something, rectangles, etc?


Finding out which version of a file a line was added/changed

Is it generally possible while using source code management to figure out in what version of a file a specific line was added? If so, what SCM systems support this?


Better way to read XML

We are storing config files as XML. With that being said, when reading the XML file, is it better to use LINQ to query the XML file or would using the `XMLDocument` and/or `XMLNode` classes better to use? To me, it would seem that in this instance, LINQ is not necessary. But then I tried to think of any value of one over the other down the road if the structure of the XML were to change. So my question is, is one method of reading XML better or more accepted way of doing it over the other?


What are arguments against using articles in method name?

I want to use articles in method names sometimes. Like some service method 'getStudentsOfATeacher()'. What are arguments against that?


How can one guarantee unique identifiers, even in the case of system collapse and restoration from backup

In the manufacturing of a device each one has to get a unique identifier. So far so good, one can have a file containing the last used ID on a shared drive, or a network-based service managing and assigning IDs so that the uploading of the ID into the device will not be limited to a single workstation. However, in the case of a total system crash and restoration from backup, one can have a few devices with the same ID, if some devices were manufactured after the backup was made. One could have each workstation save the biggest used ID, and check whether it's not larger than the one they got from the network, but it might happen that the workstation with the last produced device is not turned on after the crash. One might require workers to write down the last used ID after their shifts, but this doesn't sound to be fool- proof either. Is there a best practice besides having multiple services managing the IDs, with at least one of them off-site? The IDs are large enough (32 bits) compared to the number of devices to be produced to allow for small gaps, but not large enough to go the true RNG way. This way, one can increase the largest ID by a number significantly larger than the amount being produced per day, but how can one keep this "company practice" enforced for possibly decades?


Domain driven design and WCF services architecture

I am trying to figure out how to architecture my project in the DDD paradigm (a complete beginner in DDD) and stumbled upon a problem about the implementation of the web services... These are some options that I see: **Fat client, Fat server (option 1):**   * Server:      * Repository layer: talks to database and can return domain objects.     * Domain layer: contains domain objects with business logic and validations.     * Service layer: acts like a façade to the domain layer.     * WCF layer: exposes the service layer to web methods. It maps domain objects to appropriate DTO objects.   * Client:      * Infrastructure layer: talks to server through WCF services. It maps DTO objects back to domain objects.     * Domain layer: contains domain objects with business logic and validations.     * Service layer: acts like a façade to the domain layer.     * UI layer (WinForms): uses service layer to communicate with domain objects. Good: because the domain layer is both on client and on server, the validations happens on both (good for clients - reduces number of calls to the server, good for server - because of 'never trust the user data'). Bad: validation happens twice, a lot of mapping needed (for example a simple query to the database: domain (returned by repository) -> DTO (needed for WCF) -> domain (needed by domain layer on client) -> DTO (for WinForms). Any change in the domain should be deployed to server and client at the same time. Complicated? **Fat client, thin server (option 2):**   * Server:     * Repository: talks to database and returns DTO objects.     * WCF layer: exposes the database calls to web methods.   * Client: Exactly the same as in option 1. Good: on the client I can treat WCF services as a regular repository which returns DTO objects. Simpler as option nr. 1. Bad: is it OK that the repository works on DTO-s instead of domain objects? Also - server doesn't perform any validation so it has to trust clients about the data. **Thin client, fat server (option 3):**   * Server: Exactly the same as in option 1.   * Client:     * Infrastructure layer: talks to server through WCF services.     * UI layer (WinForms): uses presenters to communicate with the server via WCF calls in infrastructure layer. Good: all domain logic is on the server. Bad: the client doesn't contain any validation, so it can make a lot of unnecessary calls to the server. * * * I am leaning toward my first option, but it looks like I am overcomplicating things... Any advice or other options?


Why does Python use hash table to implement dict, but not Red-Black Tree? What is the key? Performance?


Asking my employer if I can open source a project I'm working on for the company

I'm an intern working for a company for the summer. I've been warmly received and I manage to impress my manager a lot (I guess I'm more experienced than the other people he interviewed). Recently I've been developing a kiosk type application which will generate a simple GUI menu from a text config file a 4 year old could write. I love the project and it has become my baby. However, in the corporate world, whatever you develop for your employer...becomes theirs (or so I've heard). I would really love to be able to keep on working on the project after the summer and I would also want to open source it. How would I go about asking for this? The code doesn't have any company secrets and most of the people here advocate open sourced software.


Should I throw guard exceptions that will be thrown by internal methods anyway?

I have some fairly simple code (C#):                   /// <summary>         /// Truncates a string to a maximum length.          /// </summary>         /// <param name="value">     The string to truncate. </param>         /// <param name="maxLength"> The maximum length of the string. </param>         /// <returns>         /// The original string if its length is less than or equal to max length, else a truncated         /// string of length maxLength.         /// </returns>         public static string Truncate(string value, int maxLength)         {             if(maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");                  if (string.IsNullOrEmpty(value)) return value;                  return value.Length <= maxLength ? value : value.Substring(0, maxLength);         }      It's clear that if `maxLength` is less than 0, I can't use it as a string length, and so I am currently using a guard statement to prevent invalid `maxLength` values. My question is: is it good or bad practice to use this guard statement, when `value.Substring` will throw the same exception anyway? Is it just wasted code?


Is there a canonical book on general abstractions and modeling?

I've been trying to understand the fundamentals of general abstractions and modeling: there are quite a lot of books when you search for abstractions, but most of those seem to be about learning object-oriented programming in a given language. Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information about general abstractions and modeling? What about that book makes it special?


Database is performing slow, even all the tables are having normalization

One of the interviewers asked me this question: > Tables are created with appropriate normalization rules, However the > database is performing slow. [Ie.: The select, insert statements are taking > time to do his operation.] What are areas we need to look to improve the > database performance. I understood this will be a vague question. Please provide some suggestions. And also what are the areas we need to look in Query Execution plan?


experience: coding on netbooks

HI, i want to buy a netbook for doing some stuff in the train. Can someone report how it is to code simple stuff on a netbook? 10/12". I wanted to buy a very cheap one. like 1gb ram 1,6ghz blabla. and run linux on it with apache. i will code with JS/PHP. and as IDE i'll be using notepad++. so nothing big like eclispe or something else. maybe later on eclipse for java, but that doesn't really matter. so first, would this setup work fine on such a netbook and, is it okay for coding? I don't style any homepages on the netbook, I just want to code. would be nice if someone can share his experience in that. thanks :)


Difference between trigger, handler and callback

It's current to see the terms `callback`, `trigger` and `handler` in some API documentations. It is just synonymous or each term correspond to a specific concept? I used to think that this terms are just synonymous, but I must be wrong ... Thanks !


Should I encrypt files saved by my program

I'm trying to decide on what format I should save data in, and hopefully this question will help me come to a decision. The program I'm writing uses 'databases' in which `word=meaning` (not a dictionary, that was just an example). I don't really want people to be able to manually edit these 'databases' without my program easily, but at the same time I'm looking for interoperability between programming langauges (namely C#, PHP, Java and Objective C) At the minute, the main contenders are SQLite, XML and SQL Server CE (although PHP doesn't have support for Server CE, but that doesn't have to be too much of an issue). Really, my question is, should I use encryption because I have read that it is often just as easy to decrypt? And if you support encryption, how do you deal with the encryption key - do I just generate a long, complicated string? Or is binary enough? Nothing in the database is too critical, however I would like to have an `isEditable` 'key' so my program knows whether to allow edits or not. And I'd also like to use my own file extension.


What is the typical Pythonic view on re-using python modules outside of their initial intent?

**Short Question**   Does it fly in the face of the Pythonic view to reuse / repurpose python modules for projects out side of their intent? **Background**   Over the past several months I have been working on a project that uses the Python unittest module to run manual system tests. Please see questions 1 2 and 3 for greater detail on my project and some of the hurdles I have had to overcome. I would like to know, in general, if it acceptable to reuse modules for other purposes? Most of the comments I have received have been along the lines of "this is not a unittest", or "you should write your own testrunner". My push back on that, is if a module does 90% of what you need it to do with litte to no modification and contains additional (knowingly unneeded) functionality why on earth would you write your own module?


What programming magazines pay for articles from guest writers?

Do any programming magazines accept contributions and pay the authors for them? If so, what magazines are these, or how can I go about finding them?


Do I have to write a lot of boilerplate code if I keep working using Java?

I'm working for a company writing ERP applications. My problem is that I have to write tons of boilerplate code. I came up with ideas to automatize/prevent the drudgery but only some of them were accepted. I have been told by the lead developer that my ideas tend to be go far afield and I should write code everyone can understand. I had a discussion about this lately and it seems to me that this kind of code ramp is within java's philosophy. I have to write lots of code to achiveve simple things not because it is necessary but because this is the way most of the people at the company think. Is this universally applicable to most of the companies out there using java or this is just my company's view? Do I have to get used to the drudgery if I keep working for java-based firms?


How do you avoid looping mistakes? Mistakes that are not detected by systems

I had this crazy initialisation -- `documentList = new ArrayList<Map<String,Integer>>();` which I intended to store a new map everytime in a loop but unfortunately put itself inside the loop. And you know the havoc. How do you detect such mistakes? I might be looking for suggestions on 'recommended debugging techniques' but am also looking for more expert advice


Why isn't there a culture of paying for frameworks?

One of the side effects of the recent trend of "Lean" startups, and the app store era, is that consumers are more acclimatised to paying small prices for small games / products. Eg.:   * Online SAAS that charges ~$5 / month (the basecamp style of product)   * Games which are short, fun, and cheap ($0.99 from the app store This market has been defined by "doing one thing well, and charging people for it." DHH of Rails / 37 Signals fame argues that if your website isn't going to make money, don't bother making it. Why doesn't the same rule apply to frameworks? There are lots of software framework projects out there - many which are mature and feature-rich, which offer developers significant value, yet there doesn't seem to be a market or culture of paying for these. It seems that the projects which do charge money are often things like UI component toolsets, and are often marginalized in favour of free alternatives. Why is this? Surely programmers / businesses see the value in contributing back to projects such as Ruby, Rails, Hibernate, Spring, Ant, Groovy, Gradle, (the list goes on). I'm not suggesting that these frameworks should start charging for anyone who wants to use them, but that there must be a meaningful business model that would allow the developers to earn money from the time they invest developing the framework. Any thoughts as to why this model hasn't emerged / succeeded? **Edit** To be clear: This isn't a post about down playing the importance of free, open source software. This is a post about asking why a culture of paying for frameworks doesn't exist.


What sort of Design Patterns do you use in Android Development?

I have been developing on Android for a couple months now, and building upon one in house program I found the scalability to be lacking. I have that gut feeling that if I applied some OO Design Patterns I would get an overall better program in speed, scalability, and readability. Do any of you SOdians have some ways you applied a/many design pattern(s) that just seem to fit extremely well with the way Android works?


How to cross-reference many character encodings with ASCII OR UTFx?

I'm working with a binary structure, the goal of which is to index the significance of specific bits for any character encoding so that we may trigger events while doing specific checks against the profile. Each character encoding scheme has an associated system record. This record's leading value will be a C++ `unsigned long long` binary value and signifies the length, in bits, of encoded characters. Following the length are three values, each is a bit field of that length.   * offset_mask - defines the occurrence of non-printable characters within the min,max of print_mask   * range_mask - defines the occurrence of the most popular 50% of printable characters   * print_mask - defines the occurrence value of printable characters The structure of profiles has changed from the op of this question. Most likely I will try to factorize or compress these values in the long-term instead of starting out with ranges after reading more. I have to write some of the core functionality for these main reasons.   * It has to fit into a particular event architecture we are using,    * Better understanding of character encoding. I'm about to need it.   * Integrating into non-linear design is excluding many libraries without special hooks. I'm unsure if there is a standard, cross-encoding mechanism for communicating such data already. I'm just starting to look into how chardet might do profiling as suggested by @amon. The Unicode BOM would be easily enough (for my current project) if all encodings were Unicode. Of course ideally, one would like to support all encodings, but I'm not asking about implementation - only the general case. How can these profiles be efficiently populated, to produce a set of bitmasks which we can use to match strings with common characters in multiple languages? If you have any editing suggestions please feel free, I am a lightweight when it comes to localization, which is why I'm trying to reach out to the more experienced. Any caveats you may be able to help with will be appreciated.


Hosting long-running worker inside IIS

Is it possible to host a long-running worker inside ASP.NET application? The worker (for it's a windows service) is reading from a queue sending messages to a WCF service. Would it be possible to run this "light long-running worker" inside an ASP.NET application? I read about setting pool start mode to "always running" and then using an AppStart class, which starts the worker. I would like to get rid of the windows service (deployments and debugging problems) and embed this work inside IIS. Any suggestion?


Is there any difference between return n and exit(n) in C?

Is there any difference between `return n` (in the `main` function) and `exit(n)` in C? Is it defined by C or POSIX standards or it depends on OS or compiler?


Logging in JSON Effect on Performance

I see more and more articles about logging in JSON. You can also find one on NodeJS blog. Why does everyone like it so much? I can only see more operations getting involved:   * A couple new objects being created.   * Stringifying objects, which either involves calculating string length or multiple string allocations.   * GCing all the crap that was created. Is there any test on performance when using JSON logging and regular string logging? Do people use JSON (for logging) in enterprise projects?


How to mark unit/integration tests when they do not apply for the current test configuration - Inconclusive or Passed?

In my test environment we are running the same set of integration (and sometimes unit) tests against different systems that have different capabilities.   Some of the tests cannot be executed against some of the systems because a feature that enables this scenario is missing or we need completely different behavior.   Currently we are using MSTest and have tests with this pattern:               [TestMethod]     public void TestMethod1()     {         if(targetSystem.SupportsFeatureX == false)             Assert.Inconclusive("Not supported by underlying system");         // the code for the actual test follows     }      Should we mark the test as `Inconclusive` or just let it `Pass` if the feature check is not satisfied?   Please note that `targetSystem` is a third party system that we have no control over so we just live with features that are present.


Sharing classes or interfaces between different projects

I was looking for some answers in SO or here, but without any results, that's why I would ask you. Let's assume I have a two different projects - for example server part and client part of an app. I'm developing my own part, while my friend is making the second one. But both of us should use some common interfaces like `User` or `AccountInfo` or `ChangableAccount`... whatever in order to ensure a compatibility. For example if a clients send a User data to server, then the server should operate on the same class. The same with interfaces etc. Moreover, if there are any changes in a common interface, both projects should adjust its code to the new situation. The only solution I can see now is, to create a one extra project in which all common things are defined. We, me and my friend, should add this project as a dependency to a main project (client or server). Shared project can be managed by some version control system, so we have always the most up-to-date state. What other solution would you suggest? How such problems are solved in professional apps?


Freelancing and GPL?

Is it possible for a freelance programmer to use Open Source products under GNU Public License and make money given that he cannot stop his customers from freely distributing his products?


Undefined behaviours in C

Recently I came across a number of undefined features in C, one of them being the following: http://stackoverflow.com/questions/8698048/behaviour-of-non-const-int-pointer- on-a-const-int Could someone tell me what should I answer when such a question is asked during online exams ( and **_None of These_** / **_Undefined_** option is not available ) ? Also, could you point me to a document specifying the most commonly encountered undefined behaviours in C ? Thanks.


Unit testing methods with indeterminate output

I have a class that is meant to generate a random password of a length that's also random, but limited to be between a defined min and max length. I'm constructing unit tests, and ran into an interesting little snag with this class. The whole idea behind a unit test is that it should be repeatable. If you run the test a hundred times, it should give the same results a hundred times. If you're depending on some resource that may or may not be there or may or may not be in the initial state you expect then you're meant to mock the resource in question to ensure that your test really is always repeatable. But what about in cases where the SUT is supposed to generate indeterminate output? If I fix the min and max length to the same value then I can easily check that the generated password is of the expected length. But if I specify a range of acceptable lengths (say 15 - 20 chars), then you now have the problem that you could run the test a hundred times and get 100 passes but on the 101st run you might get a 9 character string back. In the case of the password class, which is fairly simple at its core, it shouldn't prove a huge problem. But it got me thinking about the general case. What is the strategy that's usually accepted as the best one to take when dealing with SUTs that are generating indeterminate output by design?


How does a script download a Youtube Video?

Knowing that Youtube uses Adobe Flash which is compiled server side to deliver its video content, I am wondering how its possible to find a video's file name & location on the server? This is a general question about the security of Adobe Flash and swf files on a server. If google can't protect the video files from offsite download using Flash, why is it so widely used?


C# Classes instance members vs. enum

What is the difference between private variables in a clsClass type and using enumeration enum to instantiate the variable. This question arose when I was looking at some C# Class code for serial ports. example: private int SomeClassMember; and private enum TransmissionType{TEXT,HEX} ? Where do the enum statements appear in a Class definition?


Do-It-Yourself project suggestions to sharpen programming skills or learn a new language

Since the best way to learn is to work on projects, what are some good software to try making yourself with a purpose of sharpening certain programming skills or learning a new language?


Can one become good programmer by self learning or a mentor is needed?

I am a self taught programmer. I have only 1+ year of experience in development. Majority of my knowledge is gained by reading books and from little bit from the engineering degree. Currently I have no go to guy or person to discuss ideas / solution. I am their go to guy and they are not interested in the idea of the solution they just want it to work. So can people who are already there have they done it on there on i.e using internet and books or they have been cultured into the role?


Writing proprietary and possibly closed source software while avoiding license infractions

I am starting a software project that I want to have the option to keep it proprietary. However, since I generally use a Linux environment, I want to know: How do people write proprietary software in Linux and not violate the GPL/LGPL/etc licenses that seem to restrict uses of libraries needed to build the project? Also, does using an unmodified LGPL library in my code require releasing it as open-source (I understand that open-source and proprietary are different beasts)? And I know I'm going to be branded a heathen for asking, but can I use unmodified open-source libraries in my project but still keep the code that is mine closed-source?


What to do if the interviewer does not give you enough time to answer?

I had an interview with a well known company. After completing the first round of interview, I was confident that I would be short-listed for the second round. But little did I know that my second round would be a disaster. The second round started and the interviewer asked me to tell him about my profile. Once this was done he told me that he was going to get a pen and a paper (unfortunately I only had a pen) and he returned only after 15 minutes. Once he came back he started shooting questions at me without giving me a chance to think about the question and answer. I really mean it, 5 seconds after the first question he would shoot me another question, irrespective of whether I was answering the first question or not. I also told him politely in between to give me a chance to answer, but no luck. After the interview was over, I felt like, he took a 15 minute break to memorise these questions and was emitting it in front of me before he forgot and ran out of questions. What can be done in such a case?


Is there a good way to team develop using different MySQL Instances?

This may be a noob question but a colleague and I are working on a project. Some background about our situation is:   * We control versions using a centralized git server inside our office.   * We code in PHP, so we try our code offline in a local apache instance.   * We use local MySQL instances at work. Our client is a bit of a demanding person, and has changed the requirements more than twice. The main problem is that if we need to change something in the database, we have to make clean dumps on other servers (the other teammate's computer, the central server..., and the client's server of course) to make other instances work, too. **My question is, is there a way to synchronize our local databases** (I don't care about the client's one at this moment) **with git or another utility to make my colleague, the git server and my database be up to date when we push changes?** If that is not possible, do you know of any better way to work with MySQL databases stored locally? Thanks in advance. PS: Using only one central database is not a valid solution for us, as we test different features and have different elements stored there.


Why SQL is not so widespread in large desktop applications?

As a software developer, I've worked on projects ranging from tiny home-made apps to medium-size enterprise applications. **In nearly every project I used a database** or regretted choosing not to use it from the beginning. Now, I am wondering a few things about the databases and their usage in general applications:   * Why Windows itself doesn't use any "central" SQL database? For example:      * Errors Reporting data is stored in a bunch of files,     * Windows Update stores everything in flat files,     * Icons cache is stored in a very strange single file which doesn't seem to be accessed through SQL, etc.   * Why so many large applications avoid using databases? For example, wouldn't Microsoft Outlook gain by using a real database instead of reinventing the wheel by having its own format for .pst files and storing some data in registry? If database adds an additional layer of an overall complexity and a tiny performance loss, it is a price of a huge advantage of making the code simpler in most circumstances, especially when it comes to the storage of small organized chunks of data instead of large binary streams. So why so few products are actually using databases? Probably the only application I know which actually uses Sqlite database is Firefox, and maybe Microsoft Exchange (but the last one is not a desktop application)? Also, wouldn't _a set_ of applications, like Microsoft Office or Microsoft Expression, benefit from having an _unified SQL database_ , making it easier to deploy the applications, to update/upgrade the data, to share data between those applications, to make backups, etc.?


Sub routing in a SPA site

I have a SPA site that I'm working on, I have a requirement that you can have subroutes for a page view model. Im currently using this 'pattern' for the site               MyApp.FooViewModel = MyApp.define({         meta: {             query: MyApp.Core.Contracts.Queries.FooQuery,             title: "Foo"         },         init: function (queryResult) {              },         prototype: {                        }     });      In the master view model I have a route table               this.navigation(new MyApp.RoutesViewModel({         Home: {             model: MyApp.HomeViewModel,             route: String.empty         },         Foo: {             model: MyApp.FooViewModel         }     }));      The meta object defines which query should populate the top level view model when its invoked through sammyjs, this is all fine but it does not support sub routing My plan is to change the meta object so that it can (optional offcourse) look like this               meta: {         query: MyApp.Core.Contracts.Queries.FooQuery,         title: "Foo",         route: {             barId: MyApp.BarViewModel         }     }      When sammyjs detects a barId in the query string the Barmodel will be executed and populated through its own meta object. Is this a good design? **edit:** Hmm, just noticed that above design is not always enough, the parent view model might need to do some processing when the subRoute triggers, so I added a object to the definition sent into MyApp.define like               meta: {         query: MyApp.Core.Contracts.Queries.FooQuery,         title: "Foo",         route: {             barId: MyApp.BarViewModel         }     },     onRoute: {        barId: function(barViewModel) {           //act on bar route        }     }


github team workflow - to fork or not?

We're a small team of web developers currently using subversion but soon we're making a switch to github. I'm looking at different types of github workflows, and we're not sure if the whole forking concept in github for each developer is such a good idea for us. If we use forks, I understand each developer will have his own private remote & local repositories. I'm worried it will make pushing changesets hard and too complex. Also, my biggest concern is that it will force each developer to have 2 remotes: origin (which is the remote fork) and an upstream (which is used to "sync" changes from the main repository). Not sure if it's such a easy way to do things. This is similar to the workflow explained here: https://github.com/usm-data- analysis/usm-data-analysis.github.com/wiki/Git-workflow If we don't use forks, we can probably get by fine by using a central repo creating a branch for each task we're working on, and merge them into the development branch on the same repository. It means we won't be able to restrict merging of branches and might be a little messy to have many branches on the central repository. Any suggestions from teams who tried both workflow?


Buy vs. Build - FTP Service

We have a need to FTP files that are generated by our system, so we're trying to decide whether we should spend the time to build something that meets our criteria (relatively easy, .NET has FTP functionality built in, among other more advanced libs from 3rd parties). Or if we should buy something off the shelf. Our requirements are roughly:   * Must be able to trigger a file send programmatically   * Needs to retry _N_ number of times (configurable)   * Queryable status of FTP requests   * Callback on completion or fail of an FTP request I don't need to be sold on the relative simplicity of building something like that for myself. However I do want to do the due diligence of seeing what products are available ... because if something does exist that matches the requirements above, I wouldn't mind paying for it :-) Any thoughts or links would be greatly appreciated. Thanks!


Should I create a new database for a public website when the data already exists?

I am looking for advice on how to create my data schema for a public web site. Currently, we have an Intranet website where our agents create the data needed for reservations. The data includes tables like Establishments, products, prices per periods, and a typical Users table. This intranet is already in production. I've been tasked to create a public web site, where anonymous Joe and Jane will be able to book a reservation without calling one of our agent. The site will offer registration and will display the data available from the Intranet, albeit as read-only. The public site itself will have some data of its own. I am a bit reluctant to combine the data from the public site into the same database than our intranet, but most of the information that will be displayed on the public site will come from the pre-entered data from the intranet. Are there any best practices concerning the separation and sharing of information between a public and a private website?


How should we develop the project with different members with different skill level?

We are developing a project with three members. I am the permanent member, we hired a contractor from a company to be a team lead and one very junior coder. Now the contractor is doing the server side coding with classes and modules while the junior member and I are doing front client. The problem we face is that the junior member and I are finding it very hard to understand the contractor's code. Our skills are not at his level and he is using all sorts of advanced function and write very concise code with very little documentation. When we ask for help, he gets angry and says that we don't know that. I have raised this issue, but it comes out every now and then. I can understand only 50% of his code and the junior understands only 10% of it. What should be done int his scenario? We can't force him because we need him, but its difficult for us to proceed. What should we do? And also every time we do our part of coding he can always pick errors and tell how to do it better. It is good, but it also means that do we have to check every line of code with him. I was confused that if we have genius coder in team of 5 then that genius will always write better code. So does it mean that   1. he needs to check code for every junior member and change it   2. he leave some loopholes and ignore them because the senior member will always have better way to do the job?


In general, is it ethical to make a copy of work source code and take it home as reference?

Is it ethical to make a copy of my work's source code, for the sole purpose of my own reference? By reference, I mean as reference where I can refer to it about how I (and my teammates) implemented various design patterns, architecture, etc. It does not contain any trade secret, product, secret algorithm or anything like that. Note that I wrote many parts of the source code, and also the added value from me studying the code will also indirectly benefit the company I am working on.


Computer Graphics: Principles and Practice in C ( in Python? )

I am attending a Computer graphics course after the summer. I have read lots of good things about the book "Computer Graphics: Principles and Practice in C" for people who are willing to put in some work. My school does not focus on C/C++ until next year, so I have decided to learn Python this summer and get good at Python this following year. How language dependent is this book? Can I work through it in Python?


Software Patents: can I license the use of an existing patent?

I know the software patent is a hot topic and is very frustrating. But as I live in the US I don't think I have any choice but to deal with it. What I'm wondering is if there are actually companies or a site where I can look up what patents might apply to my idea. Then, be able to license the appropriate use of the idea even if the patent is vague and ambiguous. Then, if a troll comes after me I can argue that I'm protected under the use of patent#XYX.


How to manage and improve web application with 50 customers?

First of all, sorry for my English. We've developed a Web Application using ASP.NET and Sql Server. We've started selling it and of course are still continually improving and developing it. The question is, how do we go about updating each client's version of the site? We have, maybe, 50 customers. 50 different folders and 50 different db's sounds like a bad idea. Is there any known method for solving this kind of scenario? `For Explain:` We are developing a Crm, for 50 companies. They will have 10 users maybe. It makes 500 users and their customers and products.


Do you think F# and Python might rule the future market?

I am seeing that Microsoft is concentrating too much on F#. What type of language it is going to be and will it replace the C# user base? In the last few months I am noticing Ruby posts in some forums going down whereas Python forums are going up. If Microsoft had not stepped back from IronPython, do you think Python would have ruled C#?


How to provide value?

Before I became a consultant all I cared about was becoming a highly skilled programmer. Now I believe that what my clients need is not a great hacker, coder, architect... or whatever. I am more and more convinced every day that there is something of greater value. Everywhere I go I discover practices where I used to roll my eyes in despair. I saw the software industry with pink glasses and laughed or cried at them depending on my mood. I was so convinced everything could be done better. Now I believe that what my clients desperately need is finding a balance between good engineering practices and desperate project execution. Although a great design can make a project cheap to maintain thought many years, usually it is more important to produce quick fast and cheap, just to see if the project can succeed. Before that, it does not really matters that much if the design is cheap to maintain, after that, it might be too late to improve things. They need people who get involved, who do some clandestine improvements into the project without their manager approval/consent/knowledge... because they are never given time for some tasks we all know are important. Not all good things can be done, some of them must come out of freewill, and some of them must be discussed in order to educate colleagues, managers, clients and ourselves. Now my big question is. What exactly are the skills and practices aside from great coding that can provide real value to the economical success of software projects? (and not the software architecture alone)


Programming beginner: Options for small program interfaces?

I have been a Rails developer for a year now, and I really want to start diving in to Ruby and pure programming without using a framework. However I am having trouble conceptualizing little programs I can build on my own. I guess it's because I'm so used to having a GUI (the web browser) to interact with the classes that I write that I don't really get how I would interact with classes without clicking, going to different pages, etc. In terms of pure Ruby (without Rails), I've only built a blackjack game you play through the console through typing Y/N for hitting and staying. I would like to know what types of interfaces you guys use for your small programs? Are they all just ran once from your console using something like `ruby myclass.rb`? I have the motivation but I don't know what I would do after writing a few classes. All I do is have a separate file that requires all my other classes, instantiate my classes like so:               myclass = MyClass.new     myclass.part = ClassPart.new(1,2,3)     myclass.do_something # puts "value of instance_variable = #{@instance_variable}"      And then what? The program finishes. It's not interactive. It doesn't do much. I don't see myself building anything cool/powerful like that. Can anyone enlighten me?


How important is it to learn makefiles?

I work in c++ mostly as a hobby (I'm still in school and therefor don't have a real job). The IDEs generate the makefile for me and so I'm wondering if it's worth learning how to make them myself. By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++? Is learning them going to be really necessary? If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?


Can we use `a <= x <= b` to check if `x` is between `a` and `b`?

How to give conditions for geographical directions based on degrees? for COMPASS API Reference... I have tried this...but not working                if((0 <= a <= 22.4) || (337.6 <= a <= 360)){                  alert("YOU ARE IN NORTH DIRECTION");             }             else if((22.5 <= a <= 44.9) || (45 <= a <= 67.4)){                 alert("NORTH-NORTHEAST");             }             else if((67.5 <= a <= 89.9) || (90 <= a <= 112.4)){                 alert("East");             }             else if((112.5 <= a <= 134.9) || (135 <= a <= 157.4)){             alert("SouthEast");             }             else if((157.5 <=a <= 179.9) || (180 <= a <= 202.4)){             alert("South");             }             else if((202.5 <= a <= 224.9) || (225 <= a <= 247.4)){             alert("SouthWest");             }             else if((247.5 <= a <= 269.9) || (270 <= a <= 292.4)){             alert("West");             }             else if((292.5 <= a <= 314.9) || (315 <= a <= 337.4)){             alert("NorthEast");             }             else if(337.5 <= a <= 360){             alert("North");             }             else{}      Is this Correct?