答:
You could do something like what git project does with the "pu" branch.

In git (the project) development is done on topic branches. While in development, these branches are often rebased on latest master or, if they depend on other recent development, next. And each time they are rebased, they are all merged together to a branch called pu. The branch is always deleted and created by again merging all the topics. Than when the feature is tested, it is merged to "next", which is never rebound and that is finally integrated to "master". So you can have one test server showing this "pu" (development) and possibly another showing the "next" (preproduction).

Title: Collaboration using github and testing the code

Body:
The procedure in my team is that we all commit our code to the same development branch. We have a test server that runs updated code from this branch so that we can test our code on the servers. This test server is exposed on the internet so that we can test callbacks from third-party services like sendgrid. (where you specify a url for sendgrid to update you on the status of emails sent out)

The problem is that if we want to merge the development branch to the master branch in order to publish new features to our production servers, some features that may not have been ready will be applied to the production servers.

So we're considering having each developer work on a feature/topic branch where each of them work on their own features and when it's ready, merge it into the development branch for testing, and then into the master branch.

However, because our test server only pulls changes from the development branch, the developers are unable to test their features. While this is not a huge issue as they can test it on their local machine, the only problem I foresee is if we want to test callbacks from third-party services using our test server during the course of developing a feature.

How can we handle this problem?

Note: We're not advanced git users. We use the Github app for MacOSX and Windows to commit our work.

Setup: It is a PHP project. We do not have any form of CI setup and do not have the knowledge to do so. Eventually we want to use Jenkins but right now we're just focusing on getting our minimum viable product out.


问:
Should I encrypt data in database?
I have a client, for which I'm going to do an Web application about patient care, managing patients, consults, history, calendars, everything about that basically.

The problem is that this is sensitive data, patient history and such.

The client insists on encrypting the data at the database level, but I think this is going to deteriorate the performance of the web app. ( But maybe I shouldn't be worried about this )

I've read the laws about data protection on health issues ( Portugal ), but isn't very specific about this ( I just questioned them about this, I'm waiting for their response ).

I've read the following link, but my question is different, should I encrypt the data in the database, or not.

One problem that I foresee in encrypting data, is that I'm going to need a key, this could be the user password, but we all know how user passwords are ( 12345 etc etc ), and generating a key I would have to store it somewhere, this means that the programmer, dba, whatever could have access to it, any thoughts on this?

Even adding an random salt to the user password isn't going to solve the problem since I can always access it, and therefore decrypt the data.

答:
If you develop the web application carefully using an effective MVC framework like CakePHP. Zend or Rails, then you should be able to enable/disable encryption at the data Modal level.

CakePHP for example has a few examples of Behaviors for Modal's that encrypt data. Making the process transparent to the Controllers and Views.

Ignoring issues about indexing and other technical database issues when doing this. It should be possible to have this as a configurable option.

Additionally, I would turn encryption on at either a later time or only on the production server. Encrypted data is difficult to debug and work with while developing, and can only be done on certain columns.

ContentLicense: CC BY-SA 3.0

Title: Should I encrypt data in database?


答:
I would personally check the laws on this.  If the data needs to be encrypted, then it needs to be encrypted.

If you don't receive any guidance though, I would aim to protect the link between the patient, and their data.  I.e. you most likely have a PatientID that's used in tables throughout the database.  PatientID does not identify a patient, only the patient's medical history etc...  However, to identify the PatientID as Joe Bloggs living at Rua de São Bernardo Lisbon, I'd keep this in a separate DB if I can.  Use TDE for the patient's personal details and consider encrypting it on-top of that using keys in your web application.

Whilst theft of that medical data without the means to identify the patients will be extremely embarrassing, it is unlikely to be anything beyond that.  There are literally online competitions that use this anonymised medical data.

With the separation of the medical data from the patient's personal details.  Use a robust set of roles to limit staff to only what they need.  With the exception of medical staff that require to deal with the patient directly (front line nurses & doctors), no one should have access to both.  Receptionists only need Patient's personal details, lab staff only need the medical record and PatientID, surgical nurses only currently medical condition and first name.

When you've identified each set of roles, aim to not only implement them in your web application, but also in the database as well as an extra layer of security.

Title: Should I encrypt data in database?

Body:
I have a client, for which I'm going to do an Web application about patient care, managing patients, consults, history, calendars, everything about that basically.

The problem is that this is sensitive data, patient history and such.

The client insists on encrypting the data at the database level, but I think this is going to deteriorate the performance of the web app. ( But maybe I shouldn't be worried about this )

I've read the laws about data protection on health issues ( Portugal ), but isn't very specific about this ( I just questioned them about this, I'm waiting for their response ).

I've read the following link, but my question is different, should I encrypt the data in the database, or not.

One problem that I foresee in encrypting data, is that I'm going to need a key, this could be the user password, but we all know how user passwords are ( 12345 etc etc ), and generating a key I would have to store it somewhere, this means that the programmer, dba, whatever could have access to it, any thoughts on this?

Even adding an random salt to the user password isn't going to solve the problem since I can always access it, and therefore decrypt the data.


问:
I am trying to figure out the best way to understand how to cache domain objects
I've always done this wrong, I'm sure a lot of others have too, hold a reference via a map and write through to DB etc..

I need to do this right, and I just don't know how to go about it. I know how I want my objects to be cached but not sure on how to achieve it. What complicates things is that I need to do this for a legacy system where the DB can change without notice to my application.

So in the context of a web application, let's say I have a WidgetService which has several methods:

```<code>Widget getWidget();
Collection<Widget> getAllWidgets();
Collection<Widget> getWidgetsByCategory(String categoryCode);
Collection<Widget> getWidgetsByContainer(Integer parentContainer);
Collection<Widget> getWidgetsByStatus(String status);
</code>```

Given this, I could decide to cache by method signature, i.e. getWidgetsByCategory("AA") would have a single cache entry, or I could cache widgets individually, which would be difficult I believe; OR, a call to any method would then first cache ALL widgets with a call to getAllWidgets() but getAllWidgets() would produce caches that match all the keys for the other method invocations. For example, take the following untested theoretical code.

```<code>Collection<Widget> getAllWidgets() {
    Entity entity = cache.get("ALL_WIDGETS");
    Collection<Widget> res;
    if (entity == null) {
        res = loadCache();
    } else {
        res = (Collection<Widget>) entity.getValue();
    }
    return res
}

Collection<Widget> loadCache() {
    // Get widgets from underlying DB
    Collection<Widget> res = db.getAllWidgets();
    cache.put("ALL_WIDGETS", res);
    Map<String, List<Widget>> byCat = new HashMap<>();
    for (Widget w : res) {
        // cache by different types of method calls, i.e. by category
        if (!byCat.containsKey(widget.getCategory()) {
            byCat.put(widget.getCategory(), new ArrayList<Widget>);
        }
        byCat.get(widget.getCatgory(), widget);
    }
    cacheCategories(byCat);
    return res;
}

Collection<Widget> getWidgetsByCategory(String categoryCode) {
    CategoryCacheKey key = new CategoryCacheKey(categoryCode);
    Entity ent = cache.get(key);
    if (entity == null) {
        loadCache();
    }
    ent = cache.get(key);
    return ent == null ? Collections.emptyList() : (Collection<Widget>)ent.getValue();
}
</code>```

NOTE: I have not worked with a cache manager, the above code illustrates cache as some object that may hold caches by key/value pairs, though it's not modelled on any specific implementation.

Using this I have the benefit of being able to cache all objects in the different ways they will be called with only single objects on the heap, whereas if I were to cache the method call invocation via say Spring It would (I believe) cache multiple copies of the objects.

I really wish to try and understand the best ways to cache domain objects before I go down the wrong path and make it harder for myself later. I have read the documentation on the Ehcache website and found various articles of interest, but nothing to give a good solid technique.

Since I'm working with an ERP system, some DB calls are very complicated, not that the DB is slow, but the business representation of the domain objects makes it very clumsy, coupled with the fact that there are actually 11 different DB's where information can be contained that this application is consolidating in a single view, this makes caching quite important.

答:
To be useful a cache must provide access to data faster than it can be retrieved from the database. Given that most database calls involve a network roundtrip it makes sense to cache whenever it is known that the output (value) will not change for the same input (key) over a known dimension (time, size, etc).

Thus if the inputs are unpredictable, or undecipherable, so cannot be bound to a single key then caching may not be the best solution - you'll just end up trying to write (and maintain) a poor quality database. Invest the money in a faster network instead.

It doesn't really matter if your cache contains more than one copy of a particular object so long as the key is useful to a downstream consumer. The objective of the cache is to improve performance for different consumers of the data which may approach the underlying dataset from different standpoints (say Customer-centric or Invoice-centric).

In terms of implementation at a small scale, you might want to look at the Cache classes in the Guava library instead of EhCache. A typical example of a self-populating cache would be:

```<code>LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .removalListener(MY_LISTENER)
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });
</code>```

As you can see it is very straightforward to work with and Guava provides a wide variety of cache eviction strategies (size, reference, age etc). The Guava library also provides a wealth of useful utility classes that augment those found in the JDK so your overall codebase will benefit.

Thus your approach of decorating your DAO methods with a class that combines a dedicated cache and the DAO resultset with a derived key is sound. Each call to the method causes an initial local key lookup before returning which is what you appear to be looking for. Couple this with an appropriate eviction strategy tuned for each method and you have a simple to understand and maintain solution that should scale well.

Body:
To be useful a cache must provide access to data faster than it can be retrieved from the database. Given that most database calls involve a network roundtrip it makes sense to cache whenever it is known that the output (value) will not change for the same input (key) over a known dimension (time, size, etc).

Thus if the inputs are unpredictable, or undecipherable, so cannot be bound to a single key then caching may not be the best solution - you'll just end up trying to write (and maintain) a poor quality database. Invest the money in a faster network instead.

It doesn't really matter if your cache contains more than one copy of a particular object so long as the key is useful to a downstream consumer. The objective of the cache is to improve performance for different consumers of the data which may approach the underlying dataset from different standpoints (say Customer-centric or Invoice-centric).

In terms of implementation at a small scale, you might want to look at the Cache classes in the Guava library instead of EhCache. A typical example of a self-populating cache would be:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .removalListener(MY_LISTENER)
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });

As you can see it is very straightforward to work with and Guava provides a wide variety of cache eviction strategies (size, reference, age etc). The Guava library also provides a wealth of useful utility classes that augment those found in the JDK so your overall codebase will benefit.

Thus your approach of decorating your DAO methods with a class that combines a dedicated cache and the DAO resultset with a derived key is sound. Each call to the method causes an initial local key lookup before returning which is what you appear to be looking for. Couple this with an appropriate eviction strategy tuned for each method and you have a simple to understand and maintain solution that should scale well.


问:
Azure website that talks to third party services
I have website that crawls data from many third party services when user browse to webpage. This can be really slow because I hit third party server and process returned data before showing it to user. I am hosting website on Azure (shared mode). I am thinking to improve my implementation. Here is what I am thinking...

Run a service that crawls data from third party services, process it and then store it in database. when user browse to my site, my site pulls data from database and display them to user.

But above solution is not clear to me. Should I have normal service or wcf service? If wcf service then should website talk to database or wcf service (that can access data from database)? If normal service then how can I deploy on Azure?

答:
Your idea is a step in the right direction. Unless the data absolutely has to be presented in real time, you should always do the crawling via a background service and display the most recent data from the database (or even better, a cache). How you implement that service is entirely up to you, though.

Some recommendations:

Use a background process or windows service. WCF is meant for integration, not background processing..

Either plan on having a dedicated worker role for this process, or engineer a way to ensure that only one web role instance runs the service at any given time. You don't want multiple instances updating the same data simultaneously, not to mention the wasted resources of crawling the data from multiple instances at the same time.

If you decide to go with a dedicated worker role (you can use a single extra small instance, most likely, which costs only $0.02 / hour), look into overriding OnRun in your RoleEntryPoint class. There's no need to actually create / install a true windows service here.


问:
Try/Catch or test parameters

Possible Duplicate:

  Arguments for or against using Try/Catch as logical operators

  Efficient try / catch block usage?

I was recently on a job interview and I was given a task to write simple method in C# to calculate when the trains meet.  The code was simple mathematical equation.
What I did was that I checked all the parameters on the beginning of the method to make sure, that the code will not fail.

My question is: Is it better to check the parameters, or use try/catch?

Here are my thoughts:

Try/catch is shorter

Try/catch will work always even if you forget about some condition

Catch is slow in .NET

Testing parameters is probably cleaner code (Exceptions should be exceptional)

Testing parameters gives you more control over return values

I would prefer testing parameters in methods longer than +/- 10 lines, but what do you think about using try/catch in simple methods just like this – i.e. return (a*b)/(c+d);

There are many similar questions on stackexchnage, but I am interested in this particular scenario.

答:
The general rule is indeed to test for fail conditions before continuing (possibly throwing an exception if the test fails).

Pretty much for the reasons you quoted above.

In terms of implementation, you can also cleanly separate the validation from the implementation (this is done very often in BCL code).

Title: Try/Catch or test parameters


问:
How do developers find the time to stay on top of latest technologies?
I was a freelance web developer until circa 2004 when I started going down the management route but have decided to try to get back into development again (specifically JavaScript and HTML5 web/mobile web apps) and I really get the impression to be truly good at these and similar fast moving technologies a constant amount of time is required to be set aside to invest in getting better at existing skills in addition to learning new skills.

I understand right now since I am getting back into things there is a pretty steep learning curve, but seeing how good many guys are out there - the only way I see of getting up there is putting in a serious amount of time.

For those working as fulltime developers, what I am trying to understand is this - on most days, how much time in the office is spent actually grinding out code compared to learning/research. I could easily spend 2-4 hours daily getting on top of the best ways to go about doing things.

Do most good developers who are employed full time invest significant hours outside of work sharpening their skills?

Or maybe I'm looking at all of this completely wrong?

答:
Technology is moreover passion, regardless of time and effort it takes, it makes craze in self and when addicted feels like void to self. Best to update yourself is using online reader, as previously stated. Mostly I usually spend like 1-2 hrs on different news feeds though I have no access physically to the technology. Its hard earned technology for me but thank to feeds that least I can sense it beyond my touch.
Knowing technology is not just a way to have things known for self rather a way of paying tribute to the innovaters</p>


问:
In what ways can I test an image slideshow javascript code?
I have a slideshow of images (and links) on a page. These images are part of a JSON response to a request sent after the page loads. The slideshow is set to play at an interval of 2 seconds. The slideshow can be paused, played over, and all other controls a normal slideshow would have.

As a Rails dev, I proposed cucumber but the javascript guys in the team are not comfortable with ruby. I saw some cucumber for javascript libraries coming up, still in experimental stage.

I checked out jasmine and related tutorials but all I could get from them is how I can carry out any internal functional testing such as credit-cart validation, etc. - which I think could actually be handled in unit testing?

(Screw the research I did and) How should I go about testing this and similar components?

答:
It looks like a task for web testing tools:

http://en.wikipedia.org/wiki/Web_testing

http://en.wikipedia.org/wiki/List_of_web_testing_tools

Check these, for example:

http://en.wikipedia.org/wiki/Selenium_%28software%29

http://en.wikipedia.org/wiki/Watir


问:
What is the right HTTP method for upvoting?
From a RESTful point of view, what is the most appropriate HTTP method for the action of upvoting a forum post (like on StackExchange)?

I would say POST for voting and DELETE for canceling vote, but since users are only allowed to cast one vote per message, voting can be considered an idempotent operation so PUT can also be possible.

答: I would argue you PUT your vote, or DELETE it. You don't actually edit the forum post, so POST would be inappropriate.


问:
Has the term "Service Oriented Architecture" become meaningless jargon?
I was asked today if I had experience with "Service Oriented Architecture" and although I think I do. The concept, to me, seems so muddled I don't know how you could honestly answer that question anymore.

I resorted to Googling the term in an effort to get a concise definition of the concept and how it differs from other architectures. After reading a number of articles on it, the only common thread I seem to be able to find is a system with multiple components that talk to each other over some kind of interface, with perhaps a slight preference for XML/SOAP.

It seems like almost any application could be defined as SOA, especially a web application. Has this term fallen into the "Web 2.0" trap and become a term meaning whatever you want it to mean?

Am I way off base here? When you guys hear the term does it mean anything specific to you? If so I'd love a concise definition that clearly demonstrates what is and what specifically is NOT SOA.

答:
I've had the miss-fortune to work on a couple of corporate systems where management has been sold on SOA. As a developer I look at the systems and I see a bunch of software behind a web service that does stuff. It could have been written in a variety of languages and architectures, non of which would matter or be relevant to the clients calling the services and non of which actually have the acronym "SOA" anywhere in their documentation.

But management want "SOA"!!! So they've bought really expensive servers from a certain large company that have "SOA" stickers applied on top of the previous "Web Service" stickers which have been applied on top of the previous "JEE" stickers which have been applied on top of .... you get the idea. And as a result, we as developers sit around dragging and dropping itty-bitty icons around a screen to create "SOA" "COMPONENTS" which work half as well as if we had done it with something simple such as EBJ3 beans, spring components etc.

So my advice is if you get asked about SOA, say "Yes I've done SOA, I've written many systems that make use of a Service Orientated Architecture to do things. Which SOA technology are you asking about?". And if they start talking with glowing eyes and wistful looks about a SOA COMPONENTS, DRAG AND DROP, and how it makes developing easier. Back away slowly and avoid making eye contact!

ContentLicense: CC BY-SA 2.5


答:
PUT /posts/323223/votes

A vote can be seen as an resource I would try that. I would not do any action agains the post (/posts/323223) since that is another resource. Then you would need to have an additional method and it starts getting complex.

Title: What is the right HTTP method for upvoting?

Body:
From a RESTful point of view, what is the most appropriate HTTP method for the action of upvoting a forum post (like on StackExchange)?

I would say POST for voting and DELETE for canceling vote, but since users are only allowed to cast one vote per message, voting can be considered an idempotent operation so PUT can also be possible.


问:
How to handle notifications to several partial views of the same model?
I am working on refactoring an old simulation of a Turing machine.

The application uses a class that contains the state and the logic of program execution, and several panels to display the tape representation and show the state, messages, and the GUI controls (start, stop, program listing, ...).

I would like to refactor it using the MVC architecture that was not used originaly: the Frame is the only way to get access to the different panels and there is also a strong coupling between the "engine" class and the GUI updates in the way of frame.displayPanel.state.setText("halted"); or frame.outputPanel.messages.append("some thing");

It looks to me that I should put the state related code into an observable model class and make the different panels observers.

My problem is that the java Observable class only provides a global notification to the Observers, while I would prefer not to refresh every Observers everytime, but only when the part that specificaly observe has changed.

I am thinking of implementing myself several vectors of listeners (for the state / position, for the output messages, ...) but I feel like reinventing the wheel.

I though also about adding some flags that the observers could check like isNewMessageAvailable(), hasTapeMoved(), etc but it sounds also approximative design.

BTW, is it ok to keep the fetch / execute loop into the model or should I move it in another place? We can think in a theorical ideal way as I am completely revamping this small application.

答: the java Observable/Observer classes allow you to add an object to get passed to the Observers' update method. You can then use that to differentiate what has changed (no generic version unfortunately)</p>


答:
It mainly depends of what you consider to be your actual target object.

If your target object is the vote, then you should probably POST the vote to the system because you are actually changing the state of your target object (its internal vote counter).

Despite this, it is much more likely that you consider the forum post to be the target object of your operation and, in this case, most likely a PUT/DELETE operation set is more consistent with the REST phylosophy because you are not changing/editing your forum post. You are just putting/deleting a token into a counter. So, I would support the suggestion of Vain Fellowman.

The fact that voting should be an idempotent operation is another clue that should lead you in this direction. Think to this as a ADD/REMOVE operation over the "vote" member variable of your "forumPost" class/object.

Regarding how to tell if your real target object is the forum post or the vote, I think you should look at your code. The "object" (maybe a JSP page + a Java Controller + some Java Entity that refers to some DB table) that receives and handles this HTTP request is representing a forum post or a vote?


问:
Grouping classes by subject or dependencies?
Our project consists of user application and server application. The server application prepares data files that the user application consumes. Because the data is huge, it is stored in custom format. So the project includes many classes related to reading and writing the data. The user application does not need the writing side, so we don't want to have the code there both because it might run on resource-limited devices and because it prolongs compilation (C++ is not known for having fast compilers).

So say I have two classes (I have tens of such pairs):

DataReader

DataWriter

These classes both operate on the same thing, the serialized data. But the first is only needed in the user application and the second is only needed in the server application. Would you suggest keeping such classes

Together; in say

common/data/DataReader

common/data/DataWriter

Separate like

userapp/data/DataReader

serverapp/data/DataWriter

With this goes the compilation. The common stuff lives in common and is compiled into a library linked to both. So the first option further splits into two:

Together in common/data and linked to common.a or

Together in common/data directory, but each linked to the target that needs it.

Now each has it's advantages and disadvantages:

They are closely related, so it makes sense to keep them together. But

having both in one library makes that library larger and compile longer

compiling each separately means directory layout does not correspond to project layout, which is rather confusing and complicates the build scripts

Keeping them separate makes the build structure more logical and avoids unnecessary work for the compiler, but when updating them, components far apart need to be modified (both applications are maintained by the same team, so it's not like someone wouldn't be aware of the other part)

We currently have mixture between the approaches (some classes are separate, others not and the common library contains a lot of stuff that should be in the individual projects), which I would like to clean up.

Is there any usual recommendation for such situation? Or some useful experience with similar cases?

答:
Keep them together: any format changes will require editing them together, and unit testing the format is easiest done using your existing reader & writer code together.

However, just because the source files are stored together, doesn't mean they have to compile compile together. You could set it up so that (UNIX filename conventions for illustration only):

```<code>userapp depends on libreader.a depends on DataReader.o
</code>```

while

```<code>serverapp depends on libwriter.a depends on DataWriter.o
</code>```

and then there's no reason to build libwriter at all when you're only compiling the client.

Body:
Keep them together: any format changes will require editing them together, and unit testing the format is easiest done using your existing reader & writer code together.

However, just because the source files are stored together, doesn't mean they have to compile compile together. You could set it up so that (UNIX filename conventions for illustration only):

userapp depends on libreader.a depends on DataReader.o

while

serverapp depends on libwriter.a depends on DataWriter.o

and then there's no reason to build libwriter at all when you're only compiling the client.


问:
Using which technique does facebook and pininterest show images?
If anybody has ever noticed that when you open a image in Facebook something like this happens:-

suppose you are at your homepage on Facebook:-
the URL is
https://www.facebook.com/

now if you open a image it gets opened in new modal like window and URL changes to:-
https://www.facebook.com/photo.php?fbid=10151125374887397&set=a.338008237396.161268.36922302396&type=1&theater

As far as I know in any common case a modal overlay would have kept the url in the address bar the same , My question is how does facebook / pintrest achieve this behaviour of not re-loading the whole page but still achieving the change in the address bar.

Is there any jquery or javascript plugin for this?

答:
They use the HTML5 history API to update the URL shown in the address bar without actually navigating to a different page.

Further information:

http://diveintohtml5.info/history.html

https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries

Since this API is not available in all browsers (older ones, especially IEs, don't have it) it's usually a good idea to use a wrapper such as History.js which either turn the calls in no-ops in those browsers or emulate them by using the hash part (after #) of the URL.


答:
They load a single page javascript application on page load, which takes care of all your requests within the app if you don't refresh the page. All dynamic data is retrieved using AJAX and showed to the user using the application functions. For images, the application creates a lightbox kind of gallery.

Now, usually you goto the home page and facebook loads the application and shows you the home page.

But if you goto another page like a photo page, either the page can be rendered server side, which has the white background. But they can also load the javascript app and show the image in the white background also.

Now the reason the url changes is, they use the HTML5 history api to change the url using javascript.

Title: Using which technique does facebook and pininterest show images?

Body:
If anybody has ever noticed that when you open a image in Facebook something like this happens:-

suppose you are at your homepage on Facebook:-
the URL is
https://www.facebook.com/

now if you open a image it gets opened in new modal like window and URL changes to:-
https://www.facebook.com/photo.php?fbid=10151125374887397&set=a.338008237396.161268.36922302396&type=1&theater

As far as I know in any common case a modal overlay would have kept the url in the address bar the same , My question is how does facebook / pintrest achieve this behaviour of not re-loading the whole page but still achieving the change in the address bar.

Is there any jquery or javascript plugin for this?


问:
how do early stage startups hire ninja programmers
I am programmer who just started working on a startup idea. At the moment I want to bring onboard at least one programmer. This programmer should be a ninja - a 10x engineer.

Since early days are probably the most risky for a startup, I want to make sure I approach this problem the best I can.

How do I find these people? and How do I convince them to come onboard?

I would love to hear from people who started their own companies and what their thoughts are about hiring

Update: I would like to get the ninja as a co-founder so besides being a ninja (ie. great programmer with computer science background) he/she has to have a healthy appetite for risk (for great programmers this is not a big deal because they can be hired anytime into mainstream jobs if the startup doesn't work)

答:
It's a market. Since a really perfect programmer will be worth millions of dollars, just offer to pay him a million a year.

Well, you don't have a million. So, you have to settle for a less than perfect programmer. This is where you have to figure out what you really need, and trade if off for qualities that you don't really need.

For example, the person might not have good company political skills, thus isn't doing well with a typical company. Or, he might have poor social skills, be older and thus a burden on the health care premiums for the company, etc. etec.

He might be a verbal klutz, meaning he comes off poorly in interviews.

You will have to figure out what you really need, what you can offer, and what you can put up with, and find the best deal for your resources.

It's like asking "how do I marry a supermodel genius super people person girl" Unless you're you're young, handsome, rich, brilliant, and charming, the odds are against you. But, do you really need all those qualities for a happy marriage? Probably not.


答:
Try catch if you are relying on something external eg another service or a DB server.

Solely check the parameters if it's something internal as in the example.

Title: Try/Catch or test parameters

Body:
Possible Duplicate:

  Arguments for or against using Try/Catch as logical operators

  Efficient try / catch block usage?

I was recently on a job interview and I was given a task to write simple method in C# to calculate when the trains meet.  The code was simple mathematical equation.
What I did was that I checked all the parameters on the beginning of the method to make sure, that the code will not fail.

My question is: Is it better to check the parameters, or use try/catch?

Here are my thoughts:

Try/catch is shorter

Try/catch will work always even if you forget about some condition

Catch is slow in .NET

Testing parameters is probably cleaner code (Exceptions should be exceptional)

Testing parameters gives you more control over return values

I would prefer testing parameters in methods longer than +/- 10 lines, but what do you think about using try/catch in simple methods just like this – i.e. return (a*b)/(c+d);

There are many similar questions on stackexchnage, but I am interested in this particular scenario.


问:
Tips/Process for web-development using Django in a small team
We're developing a web app using Django and we're a small team of 3-4 programmers — some doing the UI stuff and some doing the Backend stuff. I'd love some tips and suggestions from the people here. This is our current setup:

We are using Git as as our SCM tool and following this branching model.

We are following the PEP8 for your style guide.

Agile is our software development methodology and we're using Jira for that.

We are using the Confluence plugin for Jira for documentation and I'm going to be writing a script that also dumps the PyDocs into Confluence.

We are using virtualenv for sandboxing

We are using zc.buildout for building

This is whatever I can think of off the top of my head. Any other suggestions/tips would be welcome. I feel that we have a pretty good set up but I'm also confident that we could do more.

答:
Actually, I am not convinced that the branching model is that good for working with Git. I was once excited by the branching model as it resembled the one that we used earlier (CVSNT). However, it goes (a kind of) against the Git ideas. It makes things more complicated than neccessary. The commit point is more important in Git than the branch is. It is more apparent if you think about a branch as about the pointer to the last commit point in the branch.

But it may not be your opinion. Anyway, you can introduce or leave the branching model any time, so you can start with whatever model you choose and you will hardly loose anything.

It may be a good idea to read the Pro Git book by Scott Chacon, Chapter 3. Git Branching.


问:
self referencing tables, good or bad?
Representing geographical locations within an application, the design of the underlying data model suggests two clear options (or maybe more?).

One table with a self referencing parent_id column
uk - london (london parent id = UK id)

or two tables, with a one to many relationship using a foreign key.

My preference is for one self-refercing table as it easily allows to extend into as many sub regions as required.

IN general do people veer away from self referencing tables, or are they A-OK ?

答:
Nothing wrong with self-referencing tables.

It is the common database design pattern for deeply (infinity?) nested hierarchies.

Title: self referencing tables, good or bad?


问:
As a programmer, are you required to do timesheets?
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?

答:
I have filled out time sheets, both as a full time employee as well as a contractor, for nearly a decade, in 4 different jobs, so find little friction in using then, however I don't believe in getting too caught up in the minutia of tasks. The most granular I will ever go is 1/4 hr, and that's rare.

Recently, however, I have been using Grindstone to keep track of what I am doing (thankfully my current position allows me to submit my own timesheet, rather than being forced to fill in a home grown intranet based system).

I would recommend it to anyone finding their timesheet maintenance is either taking too long or is irritating


问:
Can I sell forked GPL code?
I know that it is possible to sell GPL code, but I wanted to know if it was possible to sell GPL code that has been forked and modified. The forked and modified code will still be available to use, modify, and redistribute.</p>

答: Yes, that is allowed, but you still have to meet all of the requirements of the license. Whoever you sell it to must be allowed to use, modify and redistribute it as allowed by the GPL.</p>

Title: Can I sell forked GPL code?


答:
Yes, go for it, noting that the license says you have to make the source available to anyone you distribute the software to. That aspect is NOT optional. You also need to understand that you can't stop your users from giving the software to other people (the FSF link below explains these points).

Here's the FSF's page on selling GPL software, basically 'yea, you can do that, but you still have to obey the license'.

One thing to be careful of - there are a lot of people who associate the GPL with free (as in beer) software, not just in freedom to do what you want with the software you get. If there's a large community around the software, you may get unfortunate push back when you do try to sell your forked version. One reaction is likely to be that you are trying to make money off the hard work of others.

If you can, make your source generally available. Where appropriate, you may also want to consider pushing some of your changes up-steam to the original project. This may not make sense for your business plan, but if you can swing it, it would go a long way to shutting up anyone who thinks you are just leaching off the community.

Title: Can I sell forked GPL code?

Body: I know that it is possible to sell GPL code, but I wanted to know if it was possible to sell GPL code that has been forked and modified. The forked and modified code will still be available to use, modify, and redistribute.</p>


答:
The Free Software Movement has always clearly differenciated between Free of charge and Freedom of usage/modification/redistribution. The GPL is clearly about the latter. The only fundamental issue is full compliance with all the terms of the license. Apparently you intend to do just that so it shouldn't be a problem.

In summary: Nothing in the GPL prevents you from charging for the program.

The only issue that might arise is independent from the GPL and is simply a matter of logic/psychology: if the modified program is freely redistribuable and thus available then why might anyone pay for it. It still doesn't make it undoable.

Title: Can I sell forked GPL code?


答:
You shouldn't do anything with GPL code until you've read and fully understand the license. Specifically, the third paragraph of the preamble to the GNU Public License version 3 says this:

When we speak of free software, we are referring to freedom, not
  price. Our General Public Licenses are designed to make sure that you
  have the freedom to distribute copies of free software (and charge for
  them if you wish), that you receive source code or can get it if you
  want it, that you can change the software or use pieces of it in new
  free programs, and that you know you can do these things.

That'd seem to answer the question, but section 5 specifically covers Conveying Modified Source Versions:

You may convey a work based on the Program, or the modifications to
  produce it from the Program, in the form of source code under the
  terms of section 4, provided that you also meet all of these
  conditions...

And section 10 explains essentially that while you can charge for the code, you have to keep the license intact and you can't charge someone for exercising their rights under the GPL.

Title: Can I sell forked GPL code?


问:
How to avoid big and clumsy UITableViewController on iOS?
I have a problem when implementing the MVC-pattern on iOS. I have searched the Internet but seems not to find any nice solution to this problem.

Many UITableViewController implementations seems to be rather big. Most examples I have seen lets the UITableViewController implement <UITableViewDelegate> and <UITableViewDataSource>. These implementations are a big reason why UITableViewControlleris getting big. One solution would be to create separate classes that implements <UITableViewDelegate> and <UITableViewDataSource>. Of course these classes would have to have a reference to the UITableViewController. Are there any drawbacks using this solution? In general I think you should delegate the functionality to other "Helper" classes or similar, using the delegate pattern. Are there any well established ways of solving this problem?

I do not want the model to contain too much functionality, nor the view. I believe that the logic should really be in the controller class, since this is one of the cornerstones of the MVC-pattern. But the big question is:

How should you divide the controller of a MVC-implementation into smaller manageable pieces? (Applies to MVC in iOS in this case)

There might be a general pattern for solving this, although I am specifically looking for a solution for iOS. Please give an example of a good pattern for solving this issue. Please provide an argument why your solution is awesome.

答:
People do tend to pack a lot into the UIViewController/UITableViewController.

Delegation to another class (not the view controller) usually works out fine. The delegates don't necessarily need a reference back to the view controller, since all delegate methods get passed a reference to the UITableView, but they will need access somehow to the data they're delegating for.

A few ideas for reorganisation to reduce length:

if you're constructing the table view cells in the code, consider loading them instead from a nib file or from a storyboard. Storyboards allow prototype and static table cells -- check out those features if you're not familiar

if your delegate methods contain a lot of 'if' statements (or switch statements) that's a classic sign that you can do some refactoring

It always felt a bit funny to me that the UITableViewDataSource was responsible for getting a handle on the correct bit of data and configuring a view to show it. One nice refactoring point might be to change your cellForRowAtIndexPath to get a handle on the data that needs displaying in a cell, then delegate the creation of the cell view to another delegate (e.g. make a CellViewDelegate or similar) which gets passed in the appropriate data item.


问:
Should I encrypt data in database?
I have a client, for which I'm going to do an Web application about patient care, managing patients, consults, history, calendars, everything about that basically.

The problem is that this is sensitive data, patient history and such.

The client insists on encrypting the data at the database level, but I think this is going to deteriorate the performance of the web app. ( But maybe I shouldn't be worried about this )

I've read the laws about data protection on health issues ( Portugal ), but isn't very specific about this ( I just questioned them about this, I'm waiting for their response ).

I've read the following link, but my question is different, should I encrypt the data in the database, or not.

One problem that I foresee in encrypting data, is that I'm going to need a key, this could be the user password, but we all know how user passwords are ( 12345 etc etc ), and generating a key I would have to store it somewhere, this means that the programmer, dba, whatever could have access to it, any thoughts on this?

Even adding an random salt to the user password isn't going to solve the problem since I can always access it, and therefore decrypt the data.

答:
Yes, you should encrypt the database.

Since this is personal and sensitive information, I definitely believe it should.

From the password, you can derive an encryption key which you only store for the session. That way, it isn't stored anywhere and nobody (including DBAs) can know it since nobody can know the password either. Anyone attempting to view the DB directly will be looking at gibberish. The only way to corrupt this is via session hijacking but I'm assuming here that sessions are secure as well.

Title: Should I encrypt data in database?


问:
What's special about currying or partial application?
I've been reading articles on Functional programming everyday and been trying to apply some practices as much as possible. But I don't understand what is unique in currying or partial application.

Take this Groovy code as an example:

```<code>def mul = { a, b -> a * b }
def tripler1 = mul.curry(3)
def tripler2 = { mul(3, it) }
</code>```

I do not understand what is the difference between tripler1 and tripler2. Aren't they both the same? The 'currying' is supported in pure or partial functional languages like Groovy, Scala, Haskell etc. But I can do the same thing (left-curry, right-curry, n-curry or partial application) by simply creating another named or anonymous function or closure that will forward the parameters to the original function (like tripler2) in most languages (even C.)

Am I missing something here? There are places where I can use currying and partial application in my Grails application but I am hesitating to do so because I'm asking myself "How's that different?"

Please enlighten me.

EDIT:
Are you guys saying that partial application/currying is simply more efficient than creating/calling another function that forwards default parameters to original function?

答:
There are two key points about partial application. The first is syntactic/convenience -- some definitions become easier and shorter to read and write, as @jk mentioned.  ( Check out Pointfree programming for more about how awesome this is! )

The second, as @telastyn mentioned, is about a model of functions and is not merely convenient.  In the Haskell version, from which I'll get my examples because I'm not familiar with other languages with partial application, all functions take a single argument.  Yes, even functions like:

```<code>(:) :: a -> [a] -> [a]
</code>```

take a single argument; because of the associativity of the function type constructor ->, the above is equivalent to:

```<code>(:) :: a -> ([a] -> [a])
</code>```

which is a function that takes an a and returns a function [a] -> [a].

This allows us to write functions like:

```<code>($) :: (a -> b) -> a -> b
</code>```

which can apply any function to an argument of the appropriate type.  Even crazy ones like:

```<code>f :: (t, t1) -> t -> t1 -> (t2 -> t3 -> (t, t1)) -> t2 -> t3 -> [(t, t1)]
f q r s t u v = q : (r, s) : [t u v]

f' :: () -> Char -> (t2 -> t3 -> ((), Char)) -> t2 -> t3 -> [((), Char)]
f' = f $ ((), 'a')  -- <== works fine
</code>```

Okay, so that was a contrived example.  But a more useful one involves the Applicative type class, which includes this method:

```<code>(<*>) :: Applicative f => f (a -> b) -> f a -> f b
</code>```

As you can see, the type is identical similar to $ if you take away the Applicative f bit, and in fact, this class describes function application in a context.  So instead of normal function application:

```<code>ghci> map (+3) [1..5]
[4,5,6,7,8]
</code>```

We can apply functions in an Applicative context; for example, in the Maybe context in which something may be either present or missing:

```<code>ghci> Just map <*> Just (+3) <*> Just [1..5]
Just [4,5,6,7,8]

ghci> Just map <*> Nothing <*> Just [1..5]
Nothing
</code>```

Now the really cool part is that the Applicative type class doesn't mention anything about functions of more than one argument -- nevertheless, it can deal with them, even functions of 6 arguments like f:

```<code>fA' :: Maybe (() -> Char -> (t2 -> t3 -> ((), Char)) -> t2 -> t3 -> [((), Char)])
fA' = Just f <*> Just ((), 'a')
</code>```

As far as I know, the Applicative type class in its general form would not be possible without some conception of partial application.  (To any programming experts out there -- please correct me if I'm wrong!) Of course, if your language lacks partial application, you could build it in in some form, but ... it's just not the same, is it?  :)

Body:
There are two key points about partial application. The first is syntactic/convenience -- some definitions become easier and shorter to read and write, as @jk mentioned.  ( Check out Pointfree programming for more about how awesome this is! )

The second, as @telastyn mentioned, is about a model of functions and is not merely convenient.  In the Haskell version, from which I'll get my examples because I'm not familiar with other languages with partial application, all functions take a single argument.  Yes, even functions like:

(:) :: a -> [a] -> [a]

take a single argument; because of the associativity of the function type constructor ->, the above is equivalent to:

(:) :: a -> ([a] -> [a])

which is a function that takes an a and returns a function [a] -> [a].

This allows us to write functions like:

($) :: (a -> b) -> a -> b

which can apply any function to an argument of the appropriate type.  Even crazy ones like:

f :: (t, t1) -> t -> t1 -> (t2 -> t3 -> (t, t1)) -> t2 -> t3 -> [(t, t1)]
f q r s t u v = q : (r, s) : [t u v]

f' :: () -> Char -> (t2 -> t3 -> ((), Char)) -> t2 -> t3 -> [((), Char)]
f' = f $ ((), 'a')  -- <== works fine

Okay, so that was a contrived example.  But a more useful one involves the Applicative type class, which includes this method:

(<*>) :: Applicative f => f (a -> b) -> f a -> f b

As you can see, the type is identical similar to $ if you take away the Applicative f bit, and in fact, this class describes function application in a context.  So instead of normal function application:

ghci> map (+3) [1..5]
[4,5,6,7,8]

We can apply functions in an Applicative context; for example, in the Maybe context in which something may be either present or missing:

ghci> Just map <*> Just (+3) <*> Just [1..5]
Just [4,5,6,7,8]

ghci> Just map <*> Nothing <*> Just [1..5]
Nothing

Now the really cool part is that the Applicative type class doesn't mention anything about functions of more than one argument -- nevertheless, it can deal with them, even functions of 6 arguments like f:

fA' :: Maybe (() -> Char -> (t2 -> t3 -> ((), Char)) -> t2 -> t3 -> [((), Char)])
fA' = Just f <*> Just ((), 'a')

As far as I know, the Applicative type class in its general form would not be possible without some conception of partial application.  (To any programming experts out there -- please correct me if I'm wrong!) Of course, if your language lacks partial application, you could build it in in some form, but ... it's just not the same, is it?  :)


问:
What to do when a project is too difficult to continue developing?
As a developer, can you tell your project manager that an application is unworkable? Or, if you're a project manager, how would you need this presented to you in order to be compelled? This isn't about "how to work on a poor project", it's assuming you cannot.

I can provide an example of the situation if anyone thinks it's important, but I'm trying to avoid proposed solutions to "plodding through".

EDIT, 8 years later:

I still think this is valid question and generally agree with @dagnellies, but I understand what everyone else was drawing at. As @mattnz pointed out, nothing is impossible, but I think it may have been impossible for me to succeed, by myself, on any reasonable timeline.

A team of 2-3 engineers, some more senior, armed with a solid plan for acceptance testing, refactoring, and unit testing probably could have succeeded.

I couldn't fathom a solution because I was working alone, not very experienced, and had no support from my manager. In the end, those problems were just as important as the tech debt.

答:
When I read responses, I have the feeling many people underestimate how bad and unmaintainable a codebase can be.

Just to illustrate this, I'm working at place where the whole Project originated from one "main" file of hundreds of thousands of LOC. ...the worst part is that the beast got bigger and bigger over time:

methods having tens of thousands of LOC

more than 15 levels of indentation

GOTOs spread over them, breaking the loops

pointer arithmetic, void* casted everywhere

lots of "two letter" variable names

lots of code nobody has an idea what it does

nobody actually knows how the whole thing even works ...but it works and make millions

duplicated code everywhere with a couple of lines changed here and there

obscure WINAPI stuff

non-deterministic behavior because of uninitialized variables, buffer overflows, wrong pointers...

no doc, no spec

Before I started working, I didn't imagine something so catastrophic could exist. The costs for maintenance are of course astounding and everything is done to attempt to minimize the changes.

On the side, because everybody knows this is a nightmare, a new software "2.0" is made, but it's so big it represents at least a dozen of man years.

I think, what you should simply talk about it to your manager. Talking makes wonders. What is important for them is to understand what the actual state is. That maintenance is really extremely difficult, time consuming, error prone, all of it because of the bad code. Moreover, continuing working on it usually even increases its technical debt because we add piles of crap based on other piles of crap. ...but in the meantime, since it is productive crap which earns the company's money, we have to deal with it, even if it's hard and unproductive.

The other funny thing is that any idiot can turn a normal source code into a pile of crap. However, the crappier the code, the smarter the one dealing with it has to be. The bad side of it is that the idiot looked productive since he added features, and the brilliant one unproductive since he has to deal with its predecessor's mess. Only good managers with technical expertise can understand what's going on though.

ContentLicense: CC BY-SA 4.0


答: Sure, you can sell GPL software whose copyright is held in full or in part by someone else. Doing so is just like distributing it for free, and subject to exactly the same limitations. It's just that the group you're distributing to is "people who pay me $10 first."</p>

Title: Can I sell forked GPL code?


问:
Why do old programming languages continue to be revised?
This question is not, "Why do people still use old programming languages?" I understand that quite well. In fact the two programming languages I know best are C and Scheme, both of which date back to the 70s.

Recently I was reading about the changes in C99 and C11 versus C89 (which seems to still be the most-used version of C in practice and the version I learned from K&R). Looking around, it seems like every programming language in heavy use gets a new specification at least once per decade or so. Even Fortran is still getting new revisions, despite the fact that most people using it are still using FORTRAN 77.

Contrast this with the approach of, say, the typesetting system TeX. In 1989, with the release of TeX 3.0, Donald Knuth declared that TeX was feature-complete and future releases would contain only bug fixes. Even beyond this, he has stated that upon his death, "all remaining bugs will become features" and absolutely no further updates will be made. Others are free to fork TeX and have done so, but the resulting systems are renamed to indicate that they are different from the official TeX. This is not because Knuth thinks TeX is perfect, but because he understands the value of a stable, predictable system that will do the same thing in fifty years that it does now.

Why do most programming language designers not follow the same principle? Of course, when a language is relatively new, it makes sense that it will go through a period of rapid change before settling down. And no one can really object to minor changes that don't do much more than codify existing pseudo-standards or correct unintended readings. But when a language still seems to need improvement after ten or twenty years, why not just fork it or start over, rather than try to change what is already in use? If some people really want to do object-oriented programming in Fortran, why not create "Objective Fortran" for that purpose, and leave Fortran itself alone?

I suppose one could say that, regardless of future revisions, C89 is already a standard and nothing stops people from continuing to use it. This is sort of true, but connotations do have consequences. GCC will, in pedantic mode, warn about syntax that is either deprecated or has a subtly different meaning in C99, which means C89 programmers can't just totally ignore the new standard. So there must be some benefit in C99 that is sufficient to impose this overhead on everyone who uses the language.

This is a real question, not an invitation to argue. Obviously I do have an opinion on this, but at the moment I'm just trying to understand why this isn't just how things are done already. I suppose the question is:

What are the (real or perceived) advantages of updating a language standard, as opposed to creating a new language based on the old?

答:
This is a bit like a consideration of spoken language.

In the past there where words that weren't used as often as they are now (or used for a different meaning).

eg.
nice :  in (very old) english has the almost inverse meaning to that which we use today, especialy when used to describe someones character.

Bad : not very long ago bad only had a single meaning, now it can mean something that is "super amazing" (it is used in a fesicous way (i've probably miss spelt fesicous)!

another new development is mobile phone 'Text speak' for written languages.

I don't personally see why a programming language isn't going to develop in a similar way, words and funcions have specified meanings / actions, and it is required to change so as to incorporate new ideas, new methodologies.

I know people who speak many different languages, and they often suggest that after the 3rd or 4th it becomes easier to learn a new one.

I don't know if there are programmers who have a similar experience, I wouldn't be surprised if there were.

I know that I feel happies programming in JAVA (much as I feel happies speaking in english) This doesn't mean I can't communicate in 'american english' or 'australian english' although there are some 'gotchas' to watch out for. Much like going from Java to PHP to Perl, the constructs are similar, but there are little gotchas to catch me out and make me bash my head against the wall.

This is different to moving from English to French, or Java to SAS. these are so different it takes quite a while to become proficient at them.

Anyway that is my take on this.


问:
Why is the sudden increase in number of Git submitters on Debian popcon graph in 2010-01?
Almost every article I've read 1 comparing Git and Mercurial it seems like Mercurial has a better command line UX with each command being limited to one idea only (unlike say git checkout).

But at some point Git suddenly became looking super popular and number of Git submitters on Debian popcon graph (see graph image below) literally exploded.

Source: Debian

What happened in 2010-01 that things suddenly changed. Looks like GitHub was founded earlier than that - 2008.

答:
I was using Darcs for my own projects for a little while. I switched to git during the rapid ascension that your graph is referring to, so here is my observation:

Distributed source control systems at about that time were a bleeding edge thing. The so-called alpha programmers were using them on the side, but they fell outside of the radar of most professional software developers. The CVS/SVN/SourceSafe/TFS way of looking at the world was one that programmers in general were more or less happy with and most people assumed that the issues that spawned the distributed source control system could be fixed with better tooling. Just as you got an improvement by going from CVS -> SVN that there would someday be something that would allow you to go SVN -> SVN++. How else would you manage source control?

Then came git. What forced git onto everyone's radar was that there was a huge, public project that immediately adopted it. Git got a lot of users for free--if you were going to do serious kernel hackage, you used git. While I can't be 100% sure, I would wager that at that point in time no other DVCS had such a large user base.

Then it worked. It worked well. It worked well in public. It also, for its initial warts, was more stable than most concurrent DVCS at the time. Darcs, for example, could be put into an inconsistent state that required an absurdly complex (quadratic? factorial? Can't recall for sure, but it was bad) utility to fix. Git has always been more stable.

From its large userbase it just sort of bled out.

Every project, commercial or open source, needs that critical mass. Darcs didn't get it. Neither did Mercurial. Think back. Lots of smaller projects use it. There are probably even a number of commercial users. But what is your big success story?

"If it's good enough for the Linux kernel, it's good enough for you" is a very convincing argument.

So, to summarize, it was a good product that came along at the right time and got a large, devoted userbase.

OwnerDisplayName: Jungle Hunter


问:
Is it safe to modify sources in repository while git svn dcommit is in progress?
I have a big repository and git svn dcommit takes pretty big time.

Will my repo be in consistent state if I'll modify sources (without any git operations) while dcommit is in progress?

答:
I'd advise against making changes while a dcommit is in progress, although that may work if you're always pushing out your HEAD commit and it goes cleanly.

When HEAD is being dcommitd, the process ends with doing git reset --mixed against the new commit which reflects the current state of the svn repository. If you'd instead push some older commit, the process would end by attempting to rebase your current branch on top of the new commit that was fetched from svn; this would abort if there are uncommitted changes.

You're also likely to have problems if dcommit would run into a conflict while pushing the changes to svn, which you would then need to resolve manually. Having unrelated changes in the working tree is likely to mess this up.

You could create a separate clone of your git svn repository, do all your actual work there, and use the git svn repository only for interacting with the svn repository. Then it would of course be safe to make any changes in your working repository while the other one was processing a dcommit operation. But you would, of course, need to be pushing and/or pulling commits between those repositories.


问:
How properly perform passing operation result to View
I'm developing web site on self made MVC engine.
I have actionController that handles operations like register, login, post submit and etc. actionController receives operation name and parameters.
Of course it mast handle errors such user with same nick already exists or password is to short about which action handler have to notify user. The question is which is the best way to organize errors, such that View could easily get localized user notification message.

I see two ways

First one:
define error constants like

```<code>ERR_NICK_BUSY = '1'
ERR_NICK_INVALID = '2'
...
</code>```

and localization map

```<code>local[ERR_NICK_BUSY] = 'User with the same nick already registered'
local[ERR_NICK_INVALID ] = 'Nick, you entered is invalid'
...
</code>```

And second one:
define abstract constants like

```<code>ERR_FIELD_BUSY = '1'
ERR_FIELD_INVALID = '2'
...
</code>```

and pass them with field name. In this case localization looks like

```<code>local['nick_'+ERR_FIELD_BUSY] = 'User with the same nick already registered'
...
</code>```

I don't like both this methods. Can you advise something else?

答:
How about extending the Exception class and throwing your own exceptions.

You could have a yml file with the error code, type, default message.

```<code>try {

/* some code */

} catch(MyException $e) {

    echo $e->getError(2)['message'];

}

class MyException extends Exception{

function getError($code){

/* the parsed errors from the yml file */

    return $this->error[$code];

}

}

The yml file should be something like this

600:
    type: 'Internal Error'
    message: 'An internal error occurred'
    code: 600
</code>```

Cache the parsed yml if it gets to big

Body:
How about extending the Exception class and throwing your own exceptions.

You could have a yml file with the error code, type, default message.

try {

/* some code */

} catch(MyException $e) {

    echo $e->getError(2)['message'];

}

class MyException extends Exception{

function getError($code){

/* the parsed errors from the yml file */

    return $this->error[$code];

}

}

The yml file should be something like this

600:
    type: 'Internal Error'
    message: 'An internal error occurred'
    code: 600

Cache the parsed yml if it gets to big


问:
OOD: All classes at bottom of hierarchy contain the same field
I am creating a class diagram for what I thought was a fairly simple problem. However, when I get to the bottom of the hierarchy, all of the classes only contain one field and it is the same one.

This to me looks very wrong, but this field does not belong in any of the parent classes. I was wondering if there are any suggested design patterns in a situation like this?

A simplified version of the class diagram can be found below.

Note, fields named differently cannot belong to any other class

```<code>                        +------------------+
                        |   NoteMapping    |
                        |------------------|
                        | String noteId    |
                        | String content   |
                        |                  |
                        +---------+--------+
                                  |
                  +---------------+----------------+
                  |                                |
         +--------|--------+              +--------|--------+
         |     UserNote    |              |    AdminNote    |
         |-----------------|              |-----------------|
         | String userId   |              | String adminId  |
         |                 |              |                 |
         +--------+--------+              +--------+--------+
                  |                                |
                  |                                |
         +--------|--------+              +--------|--------+
         |  UserBookNote   |              |  AdminBookNote  |
         |-----------------|              |-----------------|
         | String bookId   |              | String bookId   |
         |                 |              |                 |
         +-----------------+              +-----------------+
</code>```

ASCII tables drawn using http://www.asciiflow.com/

Edit

I have added some class and field names to the class diagram above.

The reason bookId cannot exist in any of the parent classes is because it is used to create a OneToOne relationship with another class - which is not something that we always want to do.

答:
I'd just put String five in ObjectAA or ObjectAB or even ObjectA, then just accept that it will be blank or null most of the time.  I might not do this if I suspected ObjectAAA and ObjectABA were going to get enhanced in the future, or if it really made the logic much easier to follow.  I guess the bottom line is, which way is easiest to understand?

There are really three ways a class stands apart from others.

It may have different data stashed in it, which is pretty much what we are discussing here.

Or it's methods might do different things--same name, but different code.  If that applies here, then I wouldn't worry about duplicate fields.  You should use different classes if they do different things even though they contain no new fields.

Or it just might mean something different to the programmer.  This is usually a function of fields, methods, and future intent.  If it makes more sense, go with it.  (But if two classes are identical in fields and methods--or even close--you might want to ask yourself if the two different concepts behind them are really one and the same.)


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
Development Time

Processing and storage is cheap. Your time is not.

Just to note:

This doesn't mean do a bad job of writing code just to finish it quickly. It means write the code in a fashion that facilitates quick development. It also depends entirely on your use cases. If this is a simple, two or three page web site with a contact form you probably don't need to use a PHP framework. A couple of includes and a mailer script will speed development. If the plan is instead to create a flexible platform on which to grow and add new features it's worth taking the time to lay it out properly and code accordingly because it will speed future development.

In the direct comparison to processing time and storage, I lean towards a faster development time. Is using the collectionutils subtract function the fastest and most memory efficient method of subtracting collections? No! But it's faster development time. If you run into performance or memory bottlenecks you can resolve those later. Optimizing before you know what needs to be optimized is a waste of your time and that is what I'm advocating against.

Title: What do you optimize for?


答:
Well, IMHO, distributed VCS's like Hg and Git are inherently better than a centralised VCS - so SVN was always going to lose out to one of them.

And git, as has already been observed, had the huge advantage over Hg that it was used by the largest and most successful open-source project on the planet - that's a hell of a track record, right from the start.

As to why the sudden explosion in early 2010, my guess is fairly prosaic. Git is brilliant, but it's not massively intuitive for a beginner.

The best Git book, IMHO, is Pro Git, which was published in Sep 2009. The second-best (IMHO again), O'Reilly's Git book, was published in Jun 2009.

So the reason Git usage exploded in early 2010 could be as simple as the fact that that was when really good resources for learning how to use it became available.

Title: Why is the sudden increase in number of Git submitters on Debian popcon graph in 2010-01?

Body:
Almost every article I've read 1 comparing Git and Mercurial it seems like Mercurial has a better command line UX with each command being limited to one idea only (unlike say git checkout).

But at some point Git suddenly became looking super popular and number of Git submitters on Debian popcon graph (see graph image below) literally exploded.

Source: Debian

What happened in 2010-01 that things suddenly changed. Looks like GitHub was founded earlier than that - 2008.


答:
Just to make clear, this graph show the installation of git on debian systems.

Around the time the spike happens the Debian package was renamed from git-core to git. Maybe people found the package easier now that the name reflected the software.


答:
The package "gnuit" (GNU Interactive Tools, a file browser/viewer and process viewer) was called "git" in Debian up until 2009-09-09, while git was called "git-core".

Therefore, a better graph to look at is:

Which shows that the popularity did not rise dramatically (take the green line for the left part until they cross, then take the red line).


问:
How lookaheads are propagated in "channel" method of building LALR parser?
The method is described in Dragon Book, however I read about it in ""Parsing Techniques" by D.Grune and C.J.H.Jacobs".

I start from my understanding of building channels for NFA:

channels are built once, they are like water channels with current

you "drop" lookahead symbols in right places (sources) of the channel, and they propagate with "current"

when symbol propagates, there are no barriers (the only sufficient things for propagation are presence of channel and direction/current); i.e. lookahead cannot just die out of the blue

Is that right?

If I am correct, then eof lookahead should be present in all states, because the source of it is the start production, and all other production states are reachable from start state.

How the DFA is made out of this NFA is not perfectly clear for me -- the authors of the mentioned book write about preserving channels, but I see no purpose, if you propagated lookaheads. If the channels have to be preserved, are they cut off from the source if the DFA state does not include source NFA state? I assume no -- the channels still runs between DFA states, not only within given DFA state.

In the effect eof should still be present in all items in all states. But when you take a look at DFA presented in book (pdf is from errata):

DFA for LALR (fig. 9.34 in the book, p.301)

you will see there are items without eof in lookahead.

The grammar for this DFA is:

```<code>S -> E
E -> E - T
E -> T
T -> ( E )
T -> n
</code>```

So how it was computed, when eof was dropped, and on what condition?

Update

It is textual pdf, so two interesting states (in DFA; # is eof):

State 1:

```<code>S--- >•E[#]
E--- >•E-T[#-]
E--- >•T[#-]
T--- >•n[#-]
T--- >•(E)[#-]
</code>```

State 6:

```<code>T--- >(•E)[#-)]
E--- >•E-T[-)]
E--- >•T[-)]
T--- >•n[-)]
T--- >•(E)[-)]
</code>```

Arc from 1 to 6 is labeled (.

答:
I think I got it.

There are barriers. When you think about NFA (and DFA, but then think about items, not states), there closure transitions and shift transitions, right?

For example -- when you have T -> . ( E ) (state 1, last item in the pdf file) to T -> ( . E ) (state 6, first item) this is shift transition, and all lookahead symbols (# and -) are flowing happily.

However, initial closure transition kills all lookaheads (x) -- you have to compute them from scratch. Continuing closure transition does not kill lookaheads.

Take a look at state 6 -- all except the first item, are effects of closure transitions. The second gets ) from the top one, and - from itself. The third no matter which transition you consider gets ) and -. And for the last 2 ones, continuing closure transition gives also ) and -.

(x) There is an exception -- if the pointer sits next to last symbol in production, you copy the lookaheads. Example A -> B . C, when you create closure for C you copy the lookaheads from A, because C in such case has to end with the same stuff as A.

To sum up -- you have shift transition, copy all lookaheads.

You have closure:

as from X -> A B C D . E, in such case copy lookaheads as for shift transition

as from X -> A . B C D E, compute FIRST for C D E (mind you, not just C) and use it (copy) as lookaheads for B closure, if entire chain can be empty (C D E) copy lookaheads as for shift too


答:
The git package in Debian was formerly known as git-core. In April 2010 the package was renamed to git. More details can be found in this blog post by Julius Plenz or this commit in Debian.

Here is a graph that shows the number installs of both git and git-core over time:


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
That writing software is easy.

How else do you explain all these projects that run over time and over budget and people (politicians, the media etc.) are still surprised, and customers complain when you tell them that their "small website" (or whatever) will actually take 6 months to develop and cost several thousand dollars (pounds, Euros, [insert currency of choice])

With fuzzy and ever changing requirements I sometimes think that it's amazing that any software ever gets finished!

I know it's a bit more complicated than that ;)


问:
Efficient way to check for changes to the contents of folders
I am creating an application that maintains a database of files of a certain type in a given folder (and all subfolders)   Initially the program will recurse the folders and add any file it finds of that type to the database.

I want the application to have the ability to re-scan the folder and add any files that were not there the last time the folders were scanned.

It can't use the date created property of the file because there is a high chance of a file being added to the folders that isn't a new file.

I am wondering what the most efficient way of doing this is, and if there is a way that doesn't involve checking each file is in the database already (which, if there are 5000 files would mean 5000 queries of a list 5000 items in size, or 25 million 'checks' for the sql engine to perform)

I suppose a more specific question to acheive the same goal would be - is there a property of a file (in Microsoft Windows) that will reliably tell you when that file arrived in that folder.

Edit:  The app would not be running all the time,  so monitoring the folder for change events is not an option.  A typical scenario might be.  Run the app.  get new files.  close the app.  A week later (after normal computer usage and files being added to the folder) run the app again,  look for changes since the app was last used.

答:
Looking on your profile on StackOverflow, seems you're (or were) a C++ Builder developer, so I suggest to use the Shell API to get notified of modifications on given folder. If you go down this path, creating an service-like (or even a real windows service) program would be my path.

Edit: another way is getting a "hash"/"signature" calculated from the name of the files and some other attribute. So you calculate it each time you scan and compare with one you saved on DB.


答:
I was a late adopter - switching from Mercurial to Git in around 2010.

The reason I believe Git became so popular is because of sites such as GitHub you had a network effect in version control tools. This was previously not seen, as you would share code on a project or company basis.

I specifically remember switching to Git and Github because all the projects that I was interested in following and contributed to had done the same, as well as developers that I associate with.

That is a network effect.

GitHub was the most popular web based collaboration layer built on DVCS and Git ended up being 'good enough'. Mercurial was certainly easier to learn and use, Git has many nuances, but had a solid brand because of Linus.

Just because GitHub launched in '08 and the growth begins in '10 doesn't mean GitHub isn't responsible. If you look at competitive growth charts in other areas such as social networking and the growth of Facebook the line is very similar.

You don't see growth charts like that without a viral loop / network effect.

For eg. compare to a chart of Facebook growth

Update: I know the source above may not have been accurate, but there are plenty of data sources that demonstrate that Git has been growing exponantially in the past few years.

Graph 1: Mentions of Git in job ads

And the Eclipse survey which shows that Git market share went from 13% in 2011 to 27% in 2012. Amazing growth.

This post makes a much better explanation of Git growth and network effects than what I have done here.


问:
Why should a class be anything other than "abstract" or "final/sealed"?
After 10+ years of java/c# programming, I find myself creating either:

abstract classes: contract not meant to be instantiated as-is.

final/sealed classes: implementation not meant to serve as base class to something else.

I can't think of any situation where a simple "class" (i.e. neither abstract nor final/sealed) would be "wise programming".

Why should a class be anything other than "abstract" or "final/sealed" ?

EDIT

This great article explains my concerns far better than I can.

答:
I agree with your view. I think that in Java, by default, classes should be declared "final". If you don't make it final, then specifically prepare it and document it for extension.

The main reason for this is to ensure that any instances of your classes will abide to the interface you originally designed and documented. Otherwise a developer using your classes can potentially create brittle and inconsistent code and, on its turn, pass that on to other developers / projects, making objects of your classes not trustable.

From a more practical perspective there is indeed a downside to this, since clients of your library's interface won't be able to do any tweaking and use your classes in more flexible ways that you originally thought of.

Personally, for all the bad quality code that exists (and since we are discussing this on a more practical level, I would argue Java development is more prone to this) I think this rigidity is a small price to pay in our quest for easier to maintain code.


答:
Choosing a version control system is a social decision. The team all needs to use the same solution. As opposed to a text editor, which is a personal decision-- different developers can use different editors and easily collaborate.

So there are network effects to choosing a version control system, causing systems  that may be a little better or a little more popular to become even more popular.

For example, I prefer darcs for open source projects, but found that more of my potential contributors were familiar with git, and I received more contributions more readily for projects hosted with git instead of darcs. So, I end using git a lot instead darcs. Then, because I use it and publish code on Github, it appears that I endorse it or may even prefer it, which could influence others to use it.

Developers don't want to learn a new source control system for each project they contribute to, so it benefits the overall community to have a standard that is "good enough" and widely popular, then to have every team and project choose the "best" solution in a vacuum.

Github only added fuel to fire of the network effect.


答:
Looking at the corrected graph in Michael's answer, showing both git-core and git on Debian systems, the question seems to be why git started to become popular in 2006 on Debian systems and why it grew exponentially between 2006-2012.

The reason could be the strong adoption of Debian-based Linux distributions, like Ubuntu,  which started to become popular around 2005-2006 and became the #1 distro up until around 2011, when Mint, also Debian-based, became #1. In the end of 2012, Mint is still #1 and Ubuntu #3 according to DistroWatch.

GitHub, founded in 2008, provided free git hosting, and between 2008 and 2012 became the #1 source repository service in the world with ~2.5 million users and ~4.5 million projects, according to Wikipedia in late 2012.

Rails and many other projects switched from Rubyforge to GitHub in the late 2000s. In addition, Bundler was introduced around the time originally in question (late 2009) with support for installing/updating gems via a :git option in the Gemfile, and Bundler was included as a dependency of Rails 3. Projects in Python, Javascript, C, C++, Java, CSS, etc. also migrated to or started on GitHub.

Those that wanted to contribute to the projects on GitHub needed to fork the project in GitHub, use a local git client to clone the repository before making amendments and pushing them back into GitHub and doing a pull request. This was much simpler than other methods used before and arguably was a significant reason that it was adopted by the projects that moved to GitHub or decided to start there. This meant git-core/git needed to be installed in the Debian-based distros so that developers could use GitHub.

So, I believe that it was a combination of Debian-based distros becoming more popular and growing git adoption because of GitHub's growth in users and projects, which likely stems from GitHub's free hosting and user experience.


答:
I tend to slant towards limiting memory consumption and allocations.  I know it's old school, but:

Most of the non-throwaway code I write is heavily parallel.  This means that excessive memory allocation and garbage collection activity will serialize a lot of otherwise parallelizable code.  It also means there will be a lot of contention for a shared memory bus.

My primary language is D, which doesn't have good 64-bit support yet (though this is being remedied).

I work with fairly large datasets on a regular basis.

Title: What do you optimize for?

Body:
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.


答:
The scenario you described probably means that there is an element (the field you are worrying about) that actually cames from a different hierarchy. This seems to be the typical use-case for multiple inheritance, as jwernerny already said in a comment.

Think to this: all existing cars derive (inherit) from an abstract "car" of some type. You can draw a tree that links all of them (a family tree). In which point of the family tree would you put the GPS navigator that you can see inside every modern car?

Most likely, you would end with a field named "GPS navigator" in each bottom (most modern) class of your tree. This happens because the GPS navigator comes from a different world (electronics) and does not have anything to share with cars.

Is this your situation?

Title: OOD: All classes at bottom of hierarchy contain the same field

Body:
I am creating a class diagram for what I thought was a fairly simple problem. However, when I get to the bottom of the hierarchy, all of the classes only contain one field and it is the same one.

This to me looks very wrong, but this field does not belong in any of the parent classes. I was wondering if there are any suggested design patterns in a situation like this?

A simplified version of the class diagram can be found below.

Note, fields named differently cannot belong to any other class

```<code>                        +------------------+
                        |   NoteMapping    |
                        |------------------|
                        | String noteId    |
                        | String content   |
                        |                  |
                        +---------+--------+
                                  |
                  +---------------+----------------+
                  |                                |
         +--------|--------+              +--------|--------+
         |     UserNote    |              |    AdminNote    |
         |-----------------|              |-----------------|
         | String userId   |              | String adminId  |
         |                 |              |                 |
         +--------+--------+              +--------+--------+
                  |                                |
                  |                                |
         +--------|--------+              +--------|--------+
         |  UserBookNote   |              |  AdminBookNote  |
         |-----------------|              |-----------------|
         | String bookId   |              | String bookId   |
         |                 |              |                 |
         +-----------------+              +-----------------+
</code>```

ASCII tables drawn using http://www.asciiflow.com/

Edit

I have added some class and field names to the class diagram above.

The reason bookId cannot exist in any of the parent classes is because it is used to create a OneToOne relationship with another class - which is not something that we always want to do.


问:
How do you keep track of a requirements document on an agile team?
I understand that User Stories dominate the agile world, but how are these artifacts stored, so that new developers who join the team can come up to speed with the requirements?

What if the User Story changes later, how is it updated and kept as an artifact? I've seen many teams just open a new ticket/feature request/bug report instead of keeping track of the original story.

答:
First off, almost nothing in @DXM's answer matches my experience with Agile, and especially not with Scrum.

The Agile Manifesto states that while comprehensive documentation is valuable, working software is MORE valuable.  So, documentation is certainly not a bad thing, but it should truly be in service to creating working software.

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

That is, while there is value in the items on the right, we value the
  items on the left more.

Nailing down every detail before beginning to code has proven wasteful again and again, so documentation is generally dealt with in a JIT (just in time) manner.  That is, you document what you are actually going to code.

One of the popular ways of doing Scrum is to use User Stories, which are maintained by the Product Owner and kept in the Product Backlog.  The Product Backlog is a fairly high-level list of all the stuff that a solution needs to do, and a User Story is generally a nicely sized way to describe each thing on the list.  User Stories aren't mandatory, but they do seem to be a good way to not overdo the details and inspire collaboration instead.

So, anyway, when a story is done--the team has created, tested, and deployed something that meets the acceptance criteria, the story is not CHUCKED, it is simply marked done on the backlog--so the backlog does have some indication of what was done in each sprint--stories and the points associated with them.  This is what allows you to calculate velocity, and is valuable documentation in and of itself.

All that said, a User Story may be all the documentation needed to understand a requirement, but more likely, it is something to generate a conversation between the customer and the development team.  As such, there are any number of things you can do around that conversation.  If it's a face-to-face ad hoc thing, as it often is, the analyst/developers can (and possibly, depending on your organization, should) write down whatever decisions were made and save it somewhere, such as a Wiki or a documentation repository.  If it's an email conversation, you can save the emails.  If it's a whiteboard session, take a picture of the board with your mobile and save it.  The point is, these things are what are helping you get the code done, and might be able to help you later if you need to figure out how or why you did it the way you did.

Another method of capturing requirements is to immediately embed them into test cases (which I believe is what DXM was getting at).  This can be really efficient, in that you need to test for each requirement anyway.  In this case, you can effectively store your requirements in your testing tool.

If a story is completed (and accepted) and then the user changes his need, well, then you probably need to create a new story.  If you use a wiki for your documentation, you can link the new story back to the original, and likewise link that original story forward to the new stuff so that someone looking at it knows that things changed.  That's the nice thing about wikis -- it's easy and fairly painless to link stuff. If you are doing the test driven approach, you'd either update the test case to deal with the change, or create new test cases for the new story if the new and old aren't mutually exclusive.

In the end, it depends on what your need is.  If the main thing is to get folks up to speed quickly, it's probably a good idea for someone to write an onboarding document to help them out.  So have someone do that.  As I mentioned, Wiki's are a great tool for keeping this sort of thing, so you might consider Atlassian's solutions which can integrate the Confluence Wiki with Jira and Greenhopper for tracking your stories/tasks/defects and managing your project in general.  There's lots of other tools out there to choose from as well.