问:
Computing integration with the Trapezoidal Rule
I am trying to implement the trapezoidal rule programmatically but am having trouble finding a good way to input the function of x and then have a loop which will iterate through for each sub-interval finding the area of the trapezium and adding the results and returning it.

Any help would be awesome.

答:
The python example from wikipedia does pretty well:

```<code>#!/usr/bin/env python
from __future__ import division

def trapezoidal_rule(f, a, b, n):
    """Approximates the definite integral of f from a to b by
    the composite trapezoidal rule, using n subintervals"""
    h = (b - a) / n
    s = f(a) + f(b)
    for i in xrange(1, n):
        s += 2 * f(a + i * h)
    return s * h / 2

print trapezoidal_rule(lambda x:x**9, 0.0, 10.0, 100000)
# displays 1000000000.75
</code>```

This example uses two very useful features in python: anonymous/passed functions and iteration over ranges. Similar solutions exist in other languages. A foreach loop would be typical in most. You'd need to produce something equivalent to a first-class function in order to easily generate the "f" parameter.

Body:
The python example from wikipedia does pretty well:

#!/usr/bin/env python
from __future__ import division

def trapezoidal_rule(f, a, b, n):
    """Approximates the definite integral of f from a to b by
    the composite trapezoidal rule, using n subintervals"""
    h = (b - a) / n
    s = f(a) + f(b)
    for i in xrange(1, n):
        s += 2 * f(a + i * h)
    return s * h / 2

print trapezoidal_rule(lambda x:x**9, 0.0, 10.0, 100000)
# displays 1000000000.75

This example uses two very useful features in python: anonymous/passed functions and iteration over ranges. Similar solutions exist in other languages. A foreach loop would be typical in most. You'd need to produce something equivalent to a first-class function in order to easily generate the "f" parameter.


问:
If you favor "T *var", do you ever write "T*"?

Possible Duplicate:

  int* i; or int *i; or int * i;

Thinking about where we place our asterisks; how do those that prefer to keep the "pointerness" away from the type and with the identifier (int *i) write code when the identifier is missing?

```<code>void f(int*); // 1
void f(int *); // 2
</code>```

The former seems much more common, no matter what your preference when with the identifier.  Is this a special case?  What makes it an exception?

However, the first still isn't universal, because I have seen the latter style.  Besides consistency along the lines of "there's always a space with the identifier, so we have one without", are there any other reasons to prefer it?

What about casts or array and function types?  How would you re-write these:

```<code>(void*)var /*or*/ (void *)var

int[3] /*or*/ int [3]
// more relevant in C++ than C: Example<int[3]>

void(int) /*or*/ void (int)
// more relevant in C++ than C: std::function<void(int)>
</code>```

The latter two would rarely, if ever, be used in C, but are seen with C++ templates.

答:
It is definitely NOT about style, or readability, or maintainability, or anything aesthetic.

The syntax of C, and therefore also C++, require it.

Here's an example:

```<code>int *a, *b, *c;
</code>```

That makes three pointers.

However:

```<code>int* a, b, c;
</code>```

That makes a pointer, and two ints.

OwnerDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5

Body:
It is definitely NOT about style, or readability, or maintainability, or anything aesthetic.

The syntax of C, and therefore also C++, require it.

Here's an example:

int *a, *b, *c;

That makes three pointers.

However:

int* a, b, c;

That makes a pointer, and two ints.

ContentLicense: CC BY-SA 3.0


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答: Fast inverse square root. How someone can come up with something like that is completely beyond me.</p>


问:
Scrum Board for a distributed team
I am looking for recommendations on a digital Scrum Board which can be shared over the internet. I imagine something like a big tablet on which you can draw and which remote users can access, too.

I dislike Scrum software because I think one major benefit of a Scrum Board is its physical presence. It should be hard to ignore.

The best solution would be two big tablets on which you can draw and which can be synchronized.

Has anyone got product recommendations for something like this? Or would you rather use a software?

Kind regards,
Falcon

答:
Give Boardsync a go if you love physical task boards but need to work in a distributed environment.

Take a photo every day and boardsync updates and synchronises a very simple software board.

Title: Scrum Board for a distributed team


问:
What is the nicest (user-friendliest) way to tell a user about "Access Denied" error?
Our software implements a layer of role-based security to secure data access, in the form of access control lists. Whenever a user tries to do something that isn't allowed, the software layer will receive an "access denied" error code or exception.

Having seen how our customers react to such "access denied" messages, and their negative impression to our software as a result, I've been thinking about how we should modify that message to make it less stressful.

I understand that the best way to reduce such frustration is to simply hide the UI actions that a user is not authorized to do. However, our UI is very feature-rich and it is not always possible to predict whether a UI action will result in access-denied error.

From a user's point of view, it would be nice if the user can be told "what went wrong", i.e. explained in the same way that a human IT administrator would explain.

My question

From a user-friendliness standpoint, what is the best way to present an "access denied" message without offending or frightening the user?

From a software design standpoint, what design methodologies can be used to reduce the chance of a user seeing an access-denied situation?

Some thoughts

If there is a security rule that says someone is forbidden from viewing a piece of data, then:

If the user has low trust (e.g. general public), no explanation for the "access denied" should be given because any partial information could be used against the security.

If the user has partial trust (e.g. an employee in the customer's organization whose rank is not high enough, or works in a different department), perhaps some explanation can be given to the user so that the user knows what security rule is being enforced?

However, occasionally some security setup is based on "denied by default", meaning that in the absence of a rule granting access, nobody can access anything.

In this case, it is much harder for a software system to explain to the user why the "access denied" occurred. Maybe it is a configuration error (a human error)? Maybe a security rule is indeed being enforced in the way of the lack of a "access granting rule"?

Related:

Methodologies for Managing Users and Access?

答:
The best solution in this case (and it is mentioned in the question) is simply to remove, or even better, to disable the UI elements that lead to "Access denied" actions. This way, the user will know that they can't do this action. Additionally, some hints can be displayed on these elements that to explain: "Disabled, because this action requires more privileges." or something similar.

The statement

"our UI is very feature-rich"

is a stupid excuse not to use this method. Any other solution will cause annoyance to the user, regardless of how politely you phrase the reason in the error message.

Well, OK, I will write about another acceptable method:

Instead of error message, the program must give the user chance to raise their privileges on such actions. Some dialog box that says: "You need additional privileges in order to perform this action. Please, provide your username/password." and corresponding user/password edits (or whatever controls you are using for authentication).

Also, OK/Cancel buttons. If the user presses "Cancel" no additional action is provided. If the user presses OK without acceptable user/password - provide error message "Access denied for specified user" or "Wrong password" or other consistent message and go back to the dialog for second try.

This way, the user will cancel the action himself, so the user will be less annoyed.


问:
Equivalence class for this requirement
The automated bell system of Stateless University should ring every hour during Mondays, Wednesdays, and Fridays. It should ring every 90 minutes during Tuesdays and Thursdays, and does not ring at all during weekends

So the equivalence classes for these are:

Mondays, Wednesdays, Fridays

Tuesdays and Thursdays

Saturdays and Sundays

90 minutes

60 minutes

Am i right?? or am i missing something?

答:
Using equivalent class on discrete values seems not be to a good idea. This is event more risky if the number of possible discrete values is small (like days).

The reason is the following:
If you define an equivalent class, for let say {Mondays, Tuesdays, Wednesdays}, you hope that testing only 1 of these days will be sufficient to test the software behaviour, and that you won't have to test the 2 others.

The risk comes from developper choice:

(1) If the developper write a test like '  if (Mondays <= day) && (day <= Wednesdays)', equivalent class would work, because every day in the range will behave the same way.

(2) Unfortunatly if the developper write a test for every day, testing only 1 day with the following does not completly test the implementation: ' if (Mondays == day) || (Tuesdays== day) || (Wednesdays== day)'
The reason being that you didn't test every condition.

The real case I have in mind is the following:

We had a software component doing a discrete delay, of 1 to 8 samples.
The test case was written using equivalent class on the numberOfSample variable, which values are in the range [1..8]. Thus tests were made with 1, 3 and 8 (plus 0 and 9 for robustness testing).

The problem is the following: For performance reason the developper wrote a price of code for each 1 to 8 case, with a switch case in front. Thus some part of the code were not tested, and the structural coverage for this component was below 50%.
I had to explain the implementation choice, and test case now tests every value from 1 to 8, and we applied the same principle for every similar variable.

Coming back to your example:

If the software implementation has a very discrete input, with a limited number of possible values, don't try equivalent class (Moreover, you should really not do it if values are not continous).

If the software have an almost continous input, like for example, the number of seconds since the begining of the week, there is many chances that the software behaviour will be the same for the range of a few continous days. If not, the behaviour should be consistent at least within a single day (you will test at 0:00, 0:01, 15:34, 23:59, for every given day).

Title: Equivalence class for this requirement


答: I'm not sure that this counts really...but the fellow that developed ruby.  I just can't get past the elegance of the language.  And I believe it was the first language to support dynamic typing, although I am not the guy that started with punchcards and writing assembly so I could be mistaken.</p>

Title: Whats the greatest most impressive programing feat you ever witnessed?

Body:
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?


问:
Rules for doctypes
After going through a lot of articles and this post, i know Why doctypes are used for and also about the different modes triggered by the browser like standards, quirks etc.

I downloaded the a strict doctype from this url - http://www.w3.org/TR/html4/strict.dtd but couldn't understand a thing of what is written inside it.

My question is, if i want to write a page with html and css which is going to have a doctype that will trigger standards mode, where can i get a clear and simple to understand list of all the rules(for instance, elements and attributes that i should avoid) that my html and css code should adhere to?

答:
From the specification itself: http://www.w3.org/TR/html401/ The DTD itself is harder to read because it's written in a spec language, Backus–Naur Form, and not plain English. Backus-Naur is worth learning if you truly want to be sure of the exact meaning of the spec.

It's OK to move on to the newer version of the doctype <!DOCTYPE html> as it sets all browsers to standards mode and also makes the validator aware should you start using the new HTML5 elements. (Do not think of it as a "HTML5 doctype".)

There isn't anything you should avoid if it's in the spec except those marked, there, as "deprecated". If you want to future proof yourself, here is the list of differences with HTML5.

For that matter, here is the HTML5 "living standard".

Title: Rules for doctypes


问:
Taking an audio file, automatically transcribing it, taking the output, and matching it to a transcript
We have transcripts of around 8000 videos.  However, these transcripts do not have any timed text (ie: they are not time coded to the video)

We are trying to ascertain whether software exists, or what approach to take to automatically time code the transcript to its associated video.

Does software exist to do this?

If not, what software approach would you use to accomplish this feat?

答:
I'm not aware of any completely automatic software solution, but this Paper (SyncTS: Automatic synchronization of
speech and text documents) gives a possible approach.

ABSTRACT

In this paper, we present an automatic approach for aligning speech signals to corresponding text documents.
For this sake, we propose to first use text-to-speech synthesis (TTS) to obtain a speech signal from the textual
representation. Subsequently, both speech signals are transformed to sequences of audio features which are
then time-aligned using a variant of greedy dynamic time-warping (DTW). The proposed approach is both
efficient (with linear running time), computationally simple, and does not rely on a prior training phase as
it is necessary when using HMM-based approaches. It benefits from the combination of a) a novel type of
speech feature, being correlated to the phonetic progression of speech, b) a greedy left-to-right variant of
DTW, and c) the TTS-based approach for creating a feature representation from the input text documents.
The feasibility of the proposed method is demonstrated in several experiments.


问:
Is there an established software taxonomy that's based on the type of software?
I'm researching engineering approaches to software development based on the type of software, for example:

Custom one-off software (e.g. space shuttle software)

Whitebox application requiring customised (e.g. Apache Ofbiz ERP - source code is usually downloaded and customized for each implementation)

Blackbox application without extension points

Blackbox application with extension points for customisation (e.g. MS Word, SAP)

...

Is there an established taxonomy of different types of software based on how the software is implemented?

答: There isn't a widely accepted taxonomy used in industry, but there are some academic attempts to create one. One example is by Forward and Lethbridge (ACM subscription required). Some software repositories, such as Sourceforge, provide a categorization scheme for the projects stored within them. At the very least, these schemes may provide a starting point.</p>


答:
In my degree class my classmate created an OS (albeit very basic but it booted from a floppy and did the necessary routines) as a project requirement in under 30 days. The duration is inclusive of both the necessary reading/research and actual coding.

I remember os.com mailing lists guys discouraging him saying he wouldn't be doing it in that few days and I also have seen him walking through the dorm at 5 am in the morning in a semi conscious state talking gibberish. :-)

He is an awesome programmer.


问:
How should you TDD a Yahtzee game?
Let's say you're writing a Yahtzee game TDD style. You want to test the part of the code that determines whether or not a set of five die rolls is a full house. As far as I know, when doing TDD, you follow these principles:

Write tests first

Write the simplest thing possible that works

Refine and refactor

So an initial test might look something like this:

public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(1, 1, 1, 2, 2);

    Assert.IsTrue(actual);
}
```

<p>When following the "Write the simplest thing possible that works", you should now write the <code>IsFullHouse</code> method like this:</p>

<pre class="lang-csharp prettyprint-override"><code>public bool IsFullHouse(int roll1, int roll2, int roll3, int roll4, int roll5)
{
    if (roll1 == 1 && roll2 == 1 && roll3 == 1 && roll4 == 2 && roll5 == 2)
    {
        return true;
    }

    return false;
}
</code>```

This results in a green test but the implementation is incomplete.

Should you unit test every possible valid combination (both of values and positions) for a full house? That looks like the only way to be absolutely sure that your IsFullHouse code is completely tested and correct, but it also sounds quite insane to do that.

How would you unit test something like this?

Update

Erik and Kilian point out that using literals in the initial implementation to get a green test might not be the best idea. I'd like to explain why I did that and that explanation does not fit in a comment.

My practical experience with unit testing (especially using a TDD approach) is very limited. I remember watching a recording of Roy Osherove's TDD Masterclass on Tekpub. In one of the episodes he builds a String Calculator TDD style. The full specification of the String Calculator can be found here: http://osherove.com/tdd-kata-1/

He starts with a test like this:

public void Add_with_empty_string_should_return_zero()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("");

    Assert.AreEqual(0, result);
}
```

<p>This results in this first implementation of the <code>Add</code> method:</p>

<pre class="lang-csharp prettyprint-override"><code>public int Add(string input)
{
    return 0;
}
</code>```

Then this test is added:

public void Add_with_one_number_string_should_return_number()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("1");

    Assert.AreEqual(1, result);
}
```

<p>And the <code>Add</code> method is refactored:</p>

<pre class="lang-csharp prettyprint-override"><code>public int Add(string input)
{
    if (input.Length == 0)
    {
        return 0;
    }

    return 1;
}
</code>```

After each step Roy says "Write the simplest thing that will work".

So I thought I would give this approach a try when trying to do a TDD-style Yahtzee game.

答:
I can think of two major ways I'd consider while testing this;

Add "some" more test cases (~5) of valid full-house sets, and the same amount of expected falses ({1, 1, 2, 3, 3} is a good one. Remember that 5 ones for example could be recognized as "3 of the same plus a pair" by an incorrect implementation). This method assumes the developer is not just trying to pass the tests, but actually implement it correct.

Test all possible sets of dice (there are only 252 different ones). This of course assumes you have some way to know what the expected answer is (in testing this is known as an oracle.) This could be a reference implementation of the same function, or a human being. If you want to be really rigorous it could be worth it to manually code each expected outcome.

As it happens, I've written a Yahtzee AI once, which of course had to know the rules. You can find the code for the the score-assessing part here,
please note that the implementation is for the Scandinavian version (Yatzy), and our implementation assumes the dice are given in sorted order.

Title: How should you TDD a Yahtzee game?


答:
Testing for five particular literal values in a particular combination is not "simplest" to my fevered brain. If the solution to a problem really is obvious (count whether you have exactly three and exactly two of any value), then by all means go ahead and code that solution, and write some tests that would be very, very unlikely to satisfy accidentally with the amount of code you wrote (i.e. different literals and different orders of the triples and doubles).

TDD maxims really are tools, not religious beliefs. Their point is to get you to write correct, well-factored code rapidly. If a maxim obviously stands in the way of that, just jump ahead go on to the next step. There will be plenty of non-obvious bits in your project where you can apply it.

Title: How should you TDD a Yahtzee game?

Body:
Let's say you're writing a Yahtzee game TDD style. You want to test the part of the code that determines whether or not a set of five die rolls is a full house. As far as I know, when doing TDD, you follow these principles:

Write tests first

Write the simplest thing possible that works

Refine and refactor

So an initial test might look something like this:

public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(1, 1, 1, 2, 2);

    Assert.IsTrue(actual);
}
```

<p>When following the "Write the simplest thing possible that works", you should now write the <code>IsFullHouse</code> method like this:</p>

<pre class="lang-csharp prettyprint-override"><code>public bool IsFullHouse(int roll1, int roll2, int roll3, int roll4, int roll5)
{
    if (roll1 == 1 && roll2 == 1 && roll3 == 1 && roll4 == 2 && roll5 == 2)
    {
        return true;
    }

    return false;
}
</code>```

This results in a green test but the implementation is incomplete.

Should you unit test every possible valid combination (both of values and positions) for a full house? That looks like the only way to be absolutely sure that your IsFullHouse code is completely tested and correct, but it also sounds quite insane to do that.

How would you unit test something like this?

Update

Erik and Kilian point out that using literals in the initial implementation to get a green test might not be the best idea. I'd like to explain why I did that and that explanation does not fit in a comment.

My practical experience with unit testing (especially using a TDD approach) is very limited. I remember watching a recording of Roy Osherove's TDD Masterclass on Tekpub. In one of the episodes he builds a String Calculator TDD style. The full specification of the String Calculator can be found here: http://osherove.com/tdd-kata-1/

He starts with a test like this:

public void Add_with_empty_string_should_return_zero()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("");

    Assert.AreEqual(0, result);
}
```

<p>This results in this first implementation of the <code>Add</code> method:</p>

<pre class="lang-csharp prettyprint-override"><code>public int Add(string input)
{
    return 0;
}
</code>```

Then this test is added:

public void Add_with_one_number_string_should_return_number()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("1");

    Assert.AreEqual(1, result);
}
```

<p>And the <code>Add</code> method is refactored:</p>

<pre class="lang-csharp prettyprint-override"><code>public int Add(string input)
{
    if (input.Length == 0)
    {
        return 0;
    }

    return 1;
}
</code>```

After each step Roy says "Write the simplest thing that will work".

So I thought I would give this approach a try when trying to do a TDD-style Yahtzee game.


答:
As a disclaimer, this is TDD as I practice it and, as Kilian aptly points out, I'd be wary of anyone who suggested that there is one right way to practice it.  But maybe it will help you...

First of all, the simplest thing you could do to get your test to pass would be this:

```<code>public bool IsFullHouse(int roll1, int roll2, int roll3, int roll4, int roll5)
{
    return true;
}
</code>```

This is significant because not because of some TDD practice, but because hard-cording in all of those literals isn't really a good idea.  One of the most difficult things to wrap your head around with TDD is that it isn't a comprehensive testing strategy -- it's a way to guard against regressions and mark progress while keeping the code simple.  It's a development strategy and not a testing strategy.

The reason I mention this distinction is that it helps guide what tests you should write.  The answer to "what tests should I write?" is "whatever tests you need to get the code the way you want it."  Think of TDD as a way to help you tease out algorithms and reason about your code.  So given your test and my "simple green" implementation, what test comes next?  Well, you've established something that is a full house, so when isn't it a full house?

```<code>public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(1, 2, 3, 4, 5);

    Assert.IsFalse(actual);
}
</code>```

Now you have to figure out some way to differentiate between the two test cases that's meaningful.  I personally would tack on a bit of clarifying information to the "do the simplest thing to make the test pass" and say "do the simplest thing to make the test pass that furthers your implementation."  Writing failing tests is your pretext to alter the code, so when you go to write each test, you should be asking yourself "what doesn't my code do that I want it to do and how can I expose that deficiency?"  It can also help you make your code robust and handle edge cases.  What do you do if a caller inputs nonsense?

```<code>public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(-1, -2, -3, -4, -5);

    //I dunno - throw exception, return false, etc, whatever you think it should do....
}
</code>```

To sum up, if you're testing every combination of values, you're almost certainly doing it wrong (and likely to wind up with a combinatorial explosion of conditionals).  When it comes to TDD, you should write the minimum amount of test cases necessary to get the algorithm you want.  Any further tests that you write will start green and thus become documentation, in essence, and not strictly part of the TDD process.  You'll only write further TDD test cases if the requirements change or a bug is exposed, in which case you'll document the deficiency with a test and then make it pass.

Update:

I started this as a comment in response to your update, but it started getting pretty long...

I'd say that the problem isn't with the existence of literals, period, but with the 'simplest' thing being a 5-part conditional.  When you think about it, a 5-part conditional is actually pretty complicated.  It will be common to use literals during the red-to-green step and then to abstract them to constants in the refactor step or else generalize them in a later test.

During my own journey with TDD, I came to realize that there is an important distinction to be made -- it's not good to confuse "simple" and "obtuse".  That is, when I started out, I watched people do TDD and I thought "they're just doing the dumbest thing possible to make the tests pass" and I mimicked that for a while, until I realized that "simple" was subtly different than "obtuse".  Sometimes they overlap, but often not.

So, apologies if I gave the impression that the existence of literals was the problem -- it isn't.  I'd say the complexity of the conditional with the 5 clauses is the problem.  Your first red-to-green can just be "return true" because that is truly simple (and obtuse, by coincidence).  The next test case, with the (1, 2, 3, 4, 5) will have to return false, and this is where you start to leave "obtuse" behind.  You have to ask yourself "why is (1, 1, 1, 2, 2) a full house and (1, 2, 3, 4, 5) isn't?"  The simplest thing you could come up with might be that one has last sequence element 5 or second sequence element 2 and the other doesn't.  Those are simple, but they're also (needlessly) obtuse.  What you're really wanting to drive at is "how many of the same number do they have?"  So you might get the second test to pass by checking to see whether or not there is a repeat.  In the one with a repeat, you have a full house, and in the other you don't.  Now the test passes, and you write another test case that has a repeat but isn't a full house to further refine your algorithm.

You may or may not do this with literals as you go, and it's fine if you do.  But the general idea is growing your algorithm 'organically' as you add more cases.

Title: How should you TDD a Yahtzee game?

Body:
As a disclaimer, this is TDD as I practice it and, as Kilian aptly points out, I'd be wary of anyone who suggested that there is one right way to practice it.  But maybe it will help you...

First of all, the simplest thing you could do to get your test to pass would be this:

public bool IsFullHouse(int roll1, int roll2, int roll3, int roll4, int roll5)
{
    return true;
}

This is significant because not because of some TDD practice, but because hard-cording in all of those literals isn't really a good idea.  One of the most difficult things to wrap your head around with TDD is that it isn't a comprehensive testing strategy -- it's a way to guard against regressions and mark progress while keeping the code simple.  It's a development strategy and not a testing strategy.

The reason I mention this distinction is that it helps guide what tests you should write.  The answer to "what tests should I write?" is "whatever tests you need to get the code the way you want it."  Think of TDD as a way to help you tease out algorithms and reason about your code.  So given your test and my "simple green" implementation, what test comes next?  Well, you've established something that is a full house, so when isn't it a full house?

public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(1, 2, 3, 4, 5);

    Assert.IsFalse(actual);
}

Now you have to figure out some way to differentiate between the two test cases that's meaningful.  I personally would tack on a bit of clarifying information to the "do the simplest thing to make the test pass" and say "do the simplest thing to make the test pass that furthers your implementation."  Writing failing tests is your pretext to alter the code, so when you go to write each test, you should be asking yourself "what doesn't my code do that I want it to do and how can I expose that deficiency?"  It can also help you make your code robust and handle edge cases.  What do you do if a caller inputs nonsense?

public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(-1, -2, -3, -4, -5);

    //I dunno - throw exception, return false, etc, whatever you think it should do....
}

To sum up, if you're testing every combination of values, you're almost certainly doing it wrong (and likely to wind up with a combinatorial explosion of conditionals).  When it comes to TDD, you should write the minimum amount of test cases necessary to get the algorithm you want.  Any further tests that you write will start green and thus become documentation, in essence, and not strictly part of the TDD process.  You'll only write further TDD test cases if the requirements change or a bug is exposed, in which case you'll document the deficiency with a test and then make it pass.

Update:

I started this as a comment in response to your update, but it started getting pretty long...

I'd say that the problem isn't with the existence of literals, period, but with the 'simplest' thing being a 5-part conditional.  When you think about it, a 5-part conditional is actually pretty complicated.  It will be common to use literals during the red-to-green step and then to abstract them to constants in the refactor step or else generalize them in a later test.

During my own journey with TDD, I came to realize that there is an important distinction to be made -- it's not good to confuse "simple" and "obtuse".  That is, when I started out, I watched people do TDD and I thought "they're just doing the dumbest thing possible to make the tests pass" and I mimicked that for a while, until I realized that "simple" was subtly different than "obtuse".  Sometimes they overlap, but often not.

So, apologies if I gave the impression that the existence of literals was the problem -- it isn't.  I'd say the complexity of the conditional with the 5 clauses is the problem.  Your first red-to-green can just be "return true" because that is truly simple (and obtuse, by coincidence).  The next test case, with the (1, 2, 3, 4, 5) will have to return false, and this is where you start to leave "obtuse" behind.  You have to ask yourself "why is (1, 1, 1, 2, 2) a full house and (1, 2, 3, 4, 5) isn't?"  The simplest thing you could come up with might be that one has last sequence element 5 or second sequence element 2 and the other doesn't.  Those are simple, but they're also (needlessly) obtuse.  What you're really wanting to drive at is "how many of the same number do they have?"  So you might get the second test to pass by checking to see whether or not there is a repeat.  In the one with a repeat, you have a full house, and in the other you don't.  Now the test passes, and you write another test case that has a repeat but isn't a full house to further refine your algorithm.

You may or may not do this with literals as you go, and it's fine if you do.  But the general idea is growing your algorithm 'organically' as you add more cases.


问:
Are there any existing standard software design guidelines?
My team of about 70 programmers is developing C and C++ code for embedded, multiprocessor, image-processing project. We have a coding standard, and hold design and code reviews. The problem is that we don't have solid design review checklist.

Currently we have scattered design checklists, but most of them are vague. For example, you might find statements like these:

Component design should be extendable.

Coupling should be reduced between modules.

The problem of these statements is that they are totally subjective and not measurable. Extendable design for me might means something else for another one.

Is there some kind of widely accepted or proven checklist or design rules that can serve as a basis for our design reviews, especially for our object-oriented C++ code base?

答:
I don't think it is possible to create one set of definitive rules that tell you if your design is good or not. There is just too much variability in what is considered a good design.

However, bad designs do have some level of commonality. These common elements are described in a similar fashion as design patterns and called anti-patterns. You can use then to avoid bad designs from becoming reality.

That said, I don't think you should use a design review to rubber-stamp a design as good or bad. In my opinion, a design review should be more like a brainstorm session where one designer presents his initial ideas on how to tackle a particular feature and his co-workers ask critical questions and give their views on the issue, so that you identify the trouble-spots in the design.


问:
Node.js API Architecture
I am currently working on  a web app and want to design the interface between nodejs / mongoose and the backbone app.

A short description of the app:
A user signs up to the application and gets a user account where he can create an organization (e.g. footballclub). Within these organizations you can set up projects. Within these projects you can define tasks you could assign to somebody)

I want to have a RESTful api for the app. My problem is: A user could have more than one organization, if i have an api for projects like

GET /projects/

POST /projects/

GET /projects/:id

PUT /projects/:id

DELETE /projects/:id

How do i determine to which organization the project belongs? Do i add a parameter to the api or do i send an extra field containing the id of the organization? Any help is appreciated!

答:
GET /organizations/projects/:id

Gets a  list of projects for an organization.

POST /projects/:id

Updates a specific project.

GET /projects/:id

Gets a specific project.

DELETE /projects/:id

Deletes a specific project.

DELETE /organizations/:id

Deletes an organization and all it's projects.

POST /organizations/:id

Updates a specific organization.

GET /organizations

Gets a list of all organizations

Title: Node.js API Architecture


问:
Is it a good idea to register views and view models as singletons in an IOC container?
I understand the benefits of injecting dependencies into objects, but have not found much guidance on the types of objects to inject and when to make them singletons.

If we take as as example an application with the following types of objects:

Services (including repositories and business services such as calculateprice)

Views

ViewModels

Services

Injecting services is the typical example given and it is clear these are not registered as singletons in the container as they are statelesss.

Was it the original intention that only services should be injected by containers?

Views/ViewModels & other stateful long lasting objects

The general way to access a long lasting object in several places has been to use a registry (or similar), assuming we cannot pass it around as a parameter. Now we have the option to register the object as a singleton in a container and inject it where needed.

I can't see any problem using the singleton in a container approach beyond the issue of removing the object from the container when its lifecycle ends (not sure how easy that is going to be - I use Unity).

Would be interested to hear of any problems others can forsee.

As an interesting aside, the MVVM Light framework uses a ViewModelLocator rather than injecting viewmodels.

答:
Well, it depends on what you need. If you'll never ever have two or more views of the same type, then I guess it's ok to register them as singletons.

But then, what if you have a view composed of two other views (and their view models), for instance, if you are comparing some data? You'll can't use the same instance, since you need to populate those with different data.

Also if you have many views, and some type of navigation, where each view gets created when you get to it, then those singleton views would linger on somewhere when you navigate away from them. The container would be keeping a reference, and they would never get collected.

EDIT: With regard to your comment, I think you wouldn't have any issues if you registered the view as a singleton. Having said that, I wouldn't do it. I usually use "singletons" for stateless (or statefull, but where the state can't be changed after it's set when instantiated the first time) objects like repositories, or objects that absolutely have to be single instances during the whole application lifetime. In MVVM that would be some controller which is responsible for managing views (for navigation). I'd leave the views themselves, and their view models as normal objects, even if at first I'll be using just one of them. This is just my preference, though.

PS: I don't have experience with MVVM Light, but using the container as a service locator is generally considered an anti-pattern by many, as you are introducing a dependency to the container. Your views and view models (and domain models) should be as free as possible of the "infrastructure" constructs such as the container. When your code gets to the view model, it should just have all that it needs, and not look for it using the container.


问:
Best arguments for/against introducing ORM technology into a companies dev process
I have started using ORM technology in the last few years. My first exposure was NHibernate. I then moved onto Linq 2 Sql, and Entity Framework.

The issue I have however is, there are some organisations where I have found strong opposition to introducing ORM tools.

They usually have a number of reasons:

they have a lot of built up SQL skills in the team, and are worried about the underlying SQL that ORM's generate.

they have DBA's who like to be able to see the SQL an app uses in order that can review it for best practice.

they are worried about performance (some people have "heard" the ORM's aren't as performant but have no real proof themselves - there may well be some truth in this! :).

So, I'm looking for the best or most convincing arguments that you have put forward FOR the use of ORM tools.

Equally, I would be interested in the against arguments too.

Note: this is NOT a discussion over which ORM I should use.

答:
As far as I am concerned, the only legitimate reason I have heard for using object relational mapping (ORM) is if a switch to a different database engine is probable (not just possible).  MySQL to Oracle would be an example (although I don't know why anyone would desire to make that particular change unless they absolutely had to).  And even in that case an ORM may not be the best decision.

I heard one reference that bothered me that suggested that it is less competent programmers that are against ORM.  One could just as easily say that it is programmer incompetent in SQL that are in favor of ORM.  So lets not make that type of argument.

Reasons I am against ORM is that I believe it takes away from transparency and makes it difficult to make the inevitable ongoing tweaks that are a major part of all development cycle.  If a developer is not fluent in a particular ORM and is hired and needs to make a database change, a task that would othersize take an hour could take many hours.  So "rapid" application develop becomes "crippling" application maintenance.

I also believe that complex design patterns where one language automatically writes another language should be generally avoided.  ORM isn't the only example of this, of course.  Another example is PHP that writes out XHTML.  Note every line of code we write needs to be be or should be object oriented.  Embedding our markup language and query syntax rather than having our programming language "automagically" do it makes the application more transparent (easier to understand), debug, and maintain.  Also, some may say that an ORM "frees" projects from the constraints of a particular database engine.  But what about the constraints of your new "fadish" ORM engine?  You can pretty much guarantee that the major database engines will be supported longer than most ORMs.

I would also like emphasize that ORM is not VMC, although a lot of VMCs are bundled with ORMs.  It is perfectly valid, and I think desirable in most circumstances, to create models that contain hand crafted methods with hand written SQL.

I would also like to dispell one other myth--that ORM are connected to RAD or rapid application development.  I do not buy this because in my personal experience I only spend about 10% of my time writing SQL and crafting models for CRUD.  So even if ORM cut this time in half (and I don't think it does) then it would only be a 5% increase in my development time (which it isn't).  And I'm not an SQL expert or DBA either--just a developer with average SQL skills.  SQL is just not a big time sink as long are the DRY principle is followed and models are created with intention.

I personally believe there is a lot of "group think" around ORM--that developers say it should be used because everybody else says it should it be used; it's considered a "hot" technology that one can pad a resume with.  Put it on your resume if you feel you must, but but don't use in an important project just because you feel you "should."


答:
Erik's answer is great, but I thought I might share a trick in test writing.

Start with this test:

```<code>[Test]
public void FullHouseReturnsTrue()
{
    var pairNum = AnyDiceValue();
    var trioNum = AnyDiceValue();

    Assert.That(sut.IsFullHouse(trioNum, pairNum, trioNum, pairNum, trioNum));
}
</code>```

This test gets even better if you create a Roll class instead of passing 5 params:

```<code>[Test]
public void FullHouseReturnsTrue()
{
    var roll = AnyFullHouse();

    Assert.That(sut.IsFullHouse(roll));
}
</code>```

That gives this implementation:

```<code>public bool IsFullHouse(Roll toCheck)
{
    return true;
}
</code>```

Then write this test:

```<code>[Test]
public void StraightReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}
</code>```

Once that is passing, write this one:

```<code>[Test]
public void ThreeOfAKindReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}
</code>```

After that, I bet you don't need to write any more (maybe two pairs, or maybe yahtzee, if you think it isn't a full house).

Obviously, implement your Any methods to return random Rolls that meet your critieria.

There are a few benefits to this approach:

You don't need to write a test whose sole purpose is to stop you from getting stuck on specific values

The tests communicate your intent really nicely (the code of the first test screams "any full house returns true")

it gets you quickly to the point of working on the meat of the problem

sometimes it will notice cases you didn't think of

Title: How should you TDD a Yahtzee game?

Body:
Erik's answer is great, but I thought I might share a trick in test writing.

Start with this test:

[Test]
public void FullHouseReturnsTrue()
{
    var pairNum = AnyDiceValue();
    var trioNum = AnyDiceValue();

    Assert.That(sut.IsFullHouse(trioNum, pairNum, trioNum, pairNum, trioNum));
}

This test gets even better if you create a Roll class instead of passing 5 params:

[Test]
public void FullHouseReturnsTrue()
{
    var roll = AnyFullHouse();

    Assert.That(sut.IsFullHouse(roll));
}

That gives this implementation:

public bool IsFullHouse(Roll toCheck)
{
    return true;
}

Then write this test:

[Test]
public void StraightReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}

Once that is passing, write this one:

[Test]
public void ThreeOfAKindReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}

After that, I bet you don't need to write any more (maybe two pairs, or maybe yahtzee, if you think it isn't a full house).

Obviously, implement your Any methods to return random Rolls that meet your critieria.

There are a few benefits to this approach:

You don't need to write a test whose sole purpose is to stop you from getting stuck on specific values

The tests communicate your intent really nicely (the code of the first test screams "any full house returns true")

it gets you quickly to the point of working on the meat of the problem

sometimes it will notice cases you didn't think of


答:
First off, you should gather the scattered design checklists and associated pieces so that they are in a single place for reference.

Second, the leads of your various teams need to review the components that have been pulled together.  Note what looks:

good and universal (for your organization)

needing work but still universal

good, but specific to particular teams

needing work, and not clear if anyone can use

Third, start using the first category with everyone in their reviews.  Next, start revising the middle two categories so they can be used and it's clearly understood who they apply to.  Finally, ditch the ones in the last category.

Congratulations, you have the basis for your organizations guidelines.

That's probably not going to be sufficient for everything you need.  Start taking a look into external resources like:

Google's C++ Style Guide

C++ Coding Standards by Sutter & Alexandrescu

This SO Question: Coding Style ...

Or this Microsoft link which has additional links below

Title: Are there any existing standard software design guidelines?

Body:
My team of about 70 programmers is developing C and C++ code for embedded, multiprocessor, image-processing project. We have a coding standard, and hold design and code reviews. The problem is that we don't have solid design review checklist.

Currently we have scattered design checklists, but most of them are vague. For example, you might find statements like these:

Component design should be extendable.

Coupling should be reduced between modules.

The problem of these statements is that they are totally subjective and not measurable. Extendable design for me might means something else for another one.

Is there some kind of widely accepted or proven checklist or design rules that can serve as a basis for our design reviews, especially for our object-oriented C++ code base?


答: You can always refer to standard texts on good and bad software design patterns to decide with more certainty as to what is good or bad design. Basically referencing a standard text might help your team identify shortcomings that could cause problems in the future, in terms of for e.g. extensibility, scalability etc. Basically this way you can leverage others' experience. </p>


问:
Data structure for fast StartsWith filtering of a dictionary
I have a list of english words. I'm trying to come up with a data structure that allows me to do fast StartsWith filtering, like:

```<code>var words = dictionary.StartsWith("foo");
</code>```

I was thinking of creating a data structure like this:

But I wanted to ask first:

a) Does the above data structure already have a name?

b) Is this the fastest way to implement what I'm looking for?

Edit: The data structure will be built at the beginning and not change. I'll only need to do the equivalent of StartsWith and Contains.

答:
This isn't identical to, but very similar to a B-tree. It's a generalization on a binary search tree. A binary search tree stores one value at each node, and has two children, with the left subtree guaranteed less than that node, and the right subtree guaranteed greater. With a B-tree, you store k values in sorted order at each node, and allow k+1 children based on in between which two children it lies. This is basically the same thing, except that you have equality instead of inequality (since there are only 26 possible choices at each step). Also, note how in your case you aren't actually storing data at each node, each node just uses the same letters a-z to determine which child to follow down. So you'd likely store children at the leaves. I'm not sure exactly how balance would work out; you'd need to create new nodes whenever you inserted a word that shared the same prefix as another words in terms of nodes you already had.

In your case, you need to give more details so we can answer b). If your list of words is fixed and doesn't change, your best bet might actually be just a simple array. Just sort it once. Then to find all words starting with "foo", you simply do binary search to find "foo" and "fop", or the close possible matches (rounded in the appropriate directions). You then return all the words between them. This will give you logN + numResults in time complexity. It's also likely to have very good constants as you don't have to follow a lot of pointers around. Also has virtually zero space overhead. Obviously, if you are adding words to your dictionary on a regular basis this is not a good solution as adding a word costs O(N), whereas tree solutions will probably cost O(logN) to add a word.


答:
Check ternary search tries: http://en.wikipedia.org/wiki/Ternary_search_tree

It has very effective (probably the most effective) algorithm for word lookups including partial match.

If this is close to auto-complete implementation case then check this: http://igoro.com/archive/efficient-auto-complete-with-a-ternary-search-tree/

Title: Data structure for fast StartsWith filtering of a dictionary

Body:
I have a list of english words. I'm trying to come up with a data structure that allows me to do fast StartsWith filtering, like:

```<code>var words = dictionary.StartsWith("foo");
</code>```

I was thinking of creating a data structure like this:

But I wanted to ask first:

a) Does the above data structure already have a name?

b) Is this the fastest way to implement what I'm looking for?

Edit: The data structure will be built at the beginning and not change. I'll only need to do the equivalent of StartsWith and Contains.


问:
Is it fair to require copyright assignments from contributors of an OS project?
As a follow up to Does a BSD-licensed project need a signed statement from each contributor?:

There are several reasons why an open source project might want to get copyright assignments from its contributors. For example:

To allow the project author to sue for infringement (as only the copyright holder can do so). This is also why FSF requires such an assignment.

To prevent future problems with the contributors, such as they claiming later that they didn't release their contribution under the same OS license.

Another reason is if a company releases its software under (L)GPL and also sells it under a commercial license. Then a copyright assignment is necessary so that the company can include contributions under the commercial license. If the contributors are informed beforehand, this is fair.

But if the company has the copyright to everything, it can do basically anything with the sources, something that the contributors wouldn't agree on. It can switch to another license, like from (L)GPL to a non-copyleft license, or even stop releasing the project as open-source and switch to proprietary licensing only. This has reportedly happened with SourceForge.

So what is a fair way to handle the problem? If the project owner doesn't get copyright assignments, (s)he can get into problems in the future. If (s)he does, the work of the contributors can lose its license or open-source status. Is there a solution to this dilemma that is fair to both sides?

As I'm not a native speaker, I might used wrong legal terms. Please feel free to correct the question.

Related:

How to get contributors assign copyright for copyright holder?.

Copyright assignment on open source projects

答:
Fair is a value judgement, and a little tricky to judge.

BUT:

As long as the intention is clear beforehand then it is probably understandable even if they go overboard to some persons viewpoint.

If they go back on their word or stated intention, there might be a case to answer.

And there are other avenues available.

If the original was open sourced, then it is always available at that version as an open source project. And can be easily forked from that point (see numerous examples i.e. XFree86).


答:
It isn't really a taxonomy: it's a set of orthogonal properties. Some of the most important ones are:

Open source vs. proprietary

Publicly available vs. in-house only

Extensible API or not?

Plugin support?

Platform (i.e. what infrastructure does it depend upon)

Extent of specific customisation for user / company

Scriptability (i.e. embeds own programming language for users)

Client type (web vs. desktop GUI vs. console app vs. REST API etc.)

Monolithic structure vs. composable components?

Support for distribution (clustering, redundancy failover etc.)

Stable vs. experimental (in development)

You can have pretty much any combination of the above.... so trying to build it into a tree structure would be fairly pointless as all the branches would need to be duplicated.

Title: Is there an established software taxonomy that's based on the type of software?

Body:
I'm researching engineering approaches to software development based on the type of software, for example:

Custom one-off software (e.g. space shuttle software)

Whitebox application requiring customised (e.g. Apache Ofbiz ERP - source code is usually downloaded and customized for each implementation)

Blackbox application without extension points

Blackbox application with extension points for customisation (e.g. MS Word, SAP)

...

Is there an established taxonomy of different types of software based on how the software is implemented?


答:
This problem really comes down to the intended lifecycle/scope of your instances.

Is there going to be a single instance of your class for the duration of the application? Then a "singleton" is fine. I've quoted singleton because it's really the application scope it's referring to.

A good overview of how scopes are nested and dependency injection works with that, see the PicoContainer introduction (I'm not suggesting you use PicoContainer, just read the intro to get a grip on this stuff).

Title: Is it a good idea to register views and view models as singletons in an IOC container?

Body:
I understand the benefits of injecting dependencies into objects, but have not found much guidance on the types of objects to inject and when to make them singletons.

If we take as as example an application with the following types of objects:

Services (including repositories and business services such as calculateprice)

Views

ViewModels

Services

Injecting services is the typical example given and it is clear these are not registered as singletons in the container as they are statelesss.

Was it the original intention that only services should be injected by containers?

Views/ViewModels & other stateful long lasting objects

The general way to access a long lasting object in several places has been to use a registry (or similar), assuming we cannot pass it around as a parameter. Now we have the option to register the object as a singleton in a container and inject it where needed.

I can't see any problem using the singleton in a container approach beyond the issue of removing the object from the container when its lifecycle ends (not sure how easy that is going to be - I use Unity).

Would be interested to hear of any problems others can forsee.

As an interesting aside, the MVVM Light framework uses a ViewModelLocator rather than injecting viewmodels.


答:
I would add that our Vaadin views maintain state on the server, chiefly the controls that form them. If your views are in a similar situation in a multi-user environment, you can't use singletons. You could use something close, like a Prototype, to carve out new instances out of a template. You could reuse views for the same user for different iterations of the same workflow, for which you'd probably employ Flyweight, or else you'll need to reset the view state at the beginning of each reuse, which is probably not worth it.

In any case, hiding the detail behind a registry will give you the option to switch between the two models if you find issues down the road.


问:
Effective design analysis
Our team redesigns the legacy software and there are a lot of design meetings going on. Many of them are not very effective and lack good analysis of the proposed design. Is there any formal way to approach this kind of discussions to make them more effective? I heard about SWOT for example, but afaik it is used more for business projects.</p>

答:
Might I suggest Martin Fowler's agile, if heretic, StranglerApplication, a method that reminds one of BranchByAbstraction.

What you probably want is to define a set of interfaces that speak your business story, all the while ignoring the existing code, plug them in with a minimum rewrite, and then slowly reimplementing more and more of these interfaces. The formality in the process ends there, but I hope its practicality is obvious.

Title: Effective design analysis


问:
What are the criteria for evaluating an ORM for.NET?
I'm looking at evaluating ORMs.

I've used SubSonic, Linq-to-SQL and Entity Framework. I've got a team of developers ranging from juniors to seniors.

What are the criterias for evaluating an ORM for.NET?

答: ORM Comparison and Benchmarks on ORMBattle.NET


问:
Visitor stability vs instanceof flexibility
I am working on a GUI application which generates a configuration file. I have a class hierarchy for the configuration model and I use an object tree of that hierarchy in several different contexts. Currently, I use the Visitor pattern to avoid polluting my model classes with context specific code.

```<code>interface IConfigurationElement {
    void acceptVisitor(IConfigurationElementVisitor visitor);
}
</code>```

In an earlier version I used chains of instanceof conditions instead of the Visitor. Comparing the two approaches I see the following tradeofs.

Visitor

It is easier and safer to add new IConfigurationElement. Just add a new declaration to IConfigurationElementVisitor and the compiler generates errors for all visitor implementations. With instanceof chains you have to remember all the places you have to extend with the new configuration element. Basically instanceof violates the DRY principle as it duplicates logic in several places.

The visitor pattern is more efficient than a chain of instanceofconditions

instanceof

The great advantage of instanceof is its flexibility. For example instanceof  allows me to define special solutions for different subsets of IConfigurationElement implementations which need to be handled similarilly in some cases. In contrast, Visitor forces me to implement a method for each implementation class every time.

Is there a common solution for this kind of problem? Can I adapt the Visitor somehow, so I can provide a common solution for some cases?

答:
Well, yes, you could. Capture the commonalities of the many configuration elements by assigning roles to them. You may end up with instanceof, but not in a way that violates the DRY principle, but rather as a way around Java's static typing.

```<code>class ConfigurationElementA implements IConfigurationElement, ICommittable {
}

class ConfigurationElementB implements IConfigurationElement, IVerifiable {
}

class Visitor {
    void accept(IConfigurationElement element) {
        if (element instanceof ICommittable) {
            // ...
        }

        // Note: not a chain of instanceofs.

        if (element instanceof IVerifiable) {
            // ...
        }
    }
}
</code>```

In other words, you let the visitor accept configuration elements generically, and act on groups of implementations via roles. Note that you can go as specific as you need by modeling your configuration elements accordingly.

You may recognize here Martin Fowler's RoleInterface pattern.

Body:
Well, yes, you could. Capture the commonalities of the many configuration elements by assigning roles to them. You may end up with instanceof, but not in a way that violates the DRY principle, but rather as a way around Java's static typing.

class ConfigurationElementA implements IConfigurationElement, ICommittable {
}

class ConfigurationElementB implements IConfigurationElement, IVerifiable {
}

class Visitor {
    void accept(IConfigurationElement element) {
        if (element instanceof ICommittable) {
            // ...
        }

        // Note: not a chain of instanceofs.

        if (element instanceof IVerifiable) {
            // ...
        }
    }
}

In other words, you let the visitor accept configuration elements generically, and act on groups of implementations via roles. Note that you can go as specific as you need by modeling your configuration elements accordingly.

You may recognize here Martin Fowler's RoleInterface pattern.


答:
As stated by @Andrew - fair is a value statement.

However, provided the conditions are clearly stated up front for all to see, it is fair - you have the choice to make if you wish to participate under those conditions, you participate, if not, you don't - what can be considered unfair about that?

As far as full assignment - is it fair for a contributor who made a tiny, insignificant contribution to prevent the major contributor changing the direction of the product? In the case is it fair and reasonable to expect the major contributor to track down every  small contributor (maybe decades later, long after they have lost interest), to make a small change to the licensing?

So the question to ask with copyright assignment is not "is it fair" but "Is it practical not to"

Title: Is it fair to require copyright assignments from contributors of an OS project?

Body:
As a follow up to Does a BSD-licensed project need a signed statement from each contributor?:

There are several reasons why an open source project might want to get copyright assignments from its contributors. For example:

To allow the project author to sue for infringement (as only the copyright holder can do so). This is also why FSF requires such an assignment.

To prevent future problems with the contributors, such as they claiming later that they didn't release their contribution under the same OS license.

Another reason is if a company releases its software under (L)GPL and also sells it under a commercial license. Then a copyright assignment is necessary so that the company can include contributions under the commercial license. If the contributors are informed beforehand, this is fair.

But if the company has the copyright to everything, it can do basically anything with the sources, something that the contributors wouldn't agree on. It can switch to another license, like from (L)GPL to a non-copyleft license, or even stop releasing the project as open-source and switch to proprietary licensing only. This has reportedly happened with SourceForge.

So what is a fair way to handle the problem? If the project owner doesn't get copyright assignments, (s)he can get into problems in the future. If (s)he does, the work of the contributors can lose its license or open-source status. Is there a solution to this dilemma that is fair to both sides?

As I'm not a native speaker, I might used wrong legal terms. Please feel free to correct the question.

Related:

How to get contributors assign copyright for copyright holder?.

Copyright assignment on open source projects


问:
Library design: provide a common header file or multiple headers
There are essentially two camps of library designers concerning the design of the final header  file inclusion:

Provide a single header file that includes every other header file that makes up the public API. For example, GTK+ dictates that only gtk.h shall be included. This does not mean that everything is explicitly written into that common header file.

Have the user include the header file whose functionality he is most interested in. The most prominent example would be the standard library where he has to include stdio.h for I/O, string.h for string manipulation etc., instead of a common std.h

Is there a preferred way? libabc gives no advice on that matter, whereas an answer to a similar question suggests to keep them separated but does not specifies why.

答:
Having all headers in one single is great and better, it's easier for others to include one single header than including different headers.

One issue of this sort of design, in big headers such as windows.h, gtk.h still small comparing to window.h, the building process can get slow. In windows.h we get around this issue by defining WIN32_LEAN_AND_MEAN to exclude some uncommon headers such as windows sockets and cryptography API to speed up building process, read more here Using the Windows Headers.

Also by the time when your library grow, there are many headers and it can be hard to work with it, you will have to make a lot of macros, lots, and endup with complex header to not break backward compatibility.

Even though, I personally prefer single header design.

OwnerDisplayName: matthias

ContentLicense: CC BY-SA 4.0


答:
Design in general is always "the art to balance contradicting goals".

Here, you have these goals:

The framework should be simple to use. If your API is 15 header files, then users will always struggle which ones to include and which ones to omit.

All common functionality should be in a single header file. So file I/O shouldn't be in string.h but you also don't want 3 string.h header files.

Dependencies are bad, so you want to reduce them to the smallest amount possible

Reading huge (amounts of) header files is slow

Each feature in your header file will raise the risk that you need to include another header file to make it compile.

gtk.h makes sense since you want to build a user interface for your application (point #2). You could argue that people should include each widget individually but then, your framework will become slightly harder to use (point #1).

If you look at old X11/Motif code, you will see dozens of #include statements at the top of each C source file. It compiles a little bit faster but it takes hours of manual work to maintain these lists.

OTOH, if you put too many features in your header files, you will have too many dependencies in there and one of them might kill you (for example, when this dependency requires another framework with a certain version -> dependency hell).

I hope you understand by now that there is no solution; the problem is too complex and needs to be addressed again every time a new framework is started.

EDIT

But then there must be a pretty good reason that GTK+ actively prevents including single headers via macro checks. – matthias

For GTK, the #include statements are part of the public API. With these macros, they are free to rearrange the header files, their content, names and include order, in any way they like at any time without breaking a single existing project.

Title: Library design: provide a common header file or multiple headers

Body:
There are essentially two camps of library designers concerning the design of the final header  file inclusion:

Provide a single header file that includes every other header file that makes up the public API. For example, GTK+ dictates that only gtk.h shall be included. This does not mean that everything is explicitly written into that common header file.

Have the user include the header file whose functionality he is most interested in. The most prominent example would be the standard library where he has to include stdio.h for I/O, string.h for string manipulation etc., instead of a common std.h

Is there a preferred way? libabc gives no advice on that matter, whereas an answer to a similar question suggests to keep them separated but does not specifies why.

OwnerDisplayName: Aaron Digulla


答:
The FSF assignment grants back an irrevocable and unlimited license to your contribution, so you may continue to use your code as you wish.  Additionally, it places constraints upon the FSF requiring them to keep the source open.

I think copyright assignment can definitely be made fair presuming the right language is put into the assignment not only to protect the assignee's rights but also the assignor.  I had no qualms signing the FSF assignment for two projects.

Many open source projects don't do copyright assignment because they think it's unlikely they'll need it and the paperwork does impose a barrier to entry. But RMS did run into the need (with code from Gosling Emacs) and that's where the FSF requirements come from.


答: Adobe Premiere Pro will allow you to attach transcripts to video clips and will attempt to align them. It does a text-to-speech on the video using the transcript as training material.  It's better than nothing..... Unfortunately, you do this manually and with 8k clips that would not be very pleasant.</p>

Title: Taking an audio file, automatically transcribing it, taking the output, and matching it to a transcript

Body:
We have transcripts of around 8000 videos.  However, these transcripts do not have any timed text (ie: they are not time coded to the video)

We are trying to ascertain whether software exists, or what approach to take to automatically time code the transcript to its associated video.

Does software exist to do this?

If not, what software approach would you use to accomplish this feat?


问:
Good practices to implement mappers in a multi-tier application
When you are working with a multi-tier application very often you run into task of converting objects in one layer to objects in another layer. This could be converting database objects into domain objects, service objects into domain objects, domain object into view models, etc.

I've seen it being done in multiple ways, those include:

In-line conversion

Creating a translator class with static helper methods

Using extension methods to simplify conversion

Overriding cast operators

Creating sepearate mapper classes for every possible translation

Utilizing solutions such as automapper

What would be the "proper" way to handle it. The application I currently work with utilizes separate mapper class for every possible translation, and although it has benefits of testability we are using dependency injection and we have to pass all those mappers as dependencies in the constructor.

Has anybody figured out a better way to do it?

UPDATE

I am using .NET stack here (EF +Business Layer + MVC)

答:
The answer is, the solution that best solves your problem domain. Below is another solution that you didn't mention.

Use the same type for all models. Most objects you are using to store data can be viewed as a hashmap or a dictionary. The name of the property is the key and returned value is the value. Clojure is an excellent example of a language that supports this line of thinking with the use of keywords. Keywords are a word or phase that begin with a colon and can be used as a descriptive identifier. In Clojure, a map is a function that can take a key as an argument and return its paired value.

```<code>(def my-data-model { :name "Joe" :age 25 })
(my-data-model :name) => "Joe"
</code>```

If your domain model looks like this:

```<code>(def domain-model { :id 1 :value "my data" })
</code>```

Your view model might just be the same thing with the :id key/value pair removed. With this approach, all of your "models" are the same type and there is no need to translate between them.

Body:
The answer is, the solution that best solves your problem domain. Below is another solution that you didn't mention.

Use the same type for all models. Most objects you are using to store data can be viewed as a hashmap or a dictionary. The name of the property is the key and returned value is the value. Clojure is an excellent example of a language that supports this line of thinking with the use of keywords. Keywords are a word or phase that begin with a colon and can be used as a descriptive identifier. In Clojure, a map is a function that can take a key as an argument and return its paired value.

(def my-data-model { :name "Joe" :age 25 })
(my-data-model :name) => "Joe"

If your domain model looks like this:

(def domain-model { :id 1 :value "my data" })

Your view model might just be the same thing with the :id key/value pair removed. With this approach, all of your "models" are the same type and there is no need to translate between them.


问:
Would md5 hashes allow detection of synced files?
We have to develop our own file management system in Java web application. We need to sync files between our main server and client severs and find out whether all the client server has all the latest version of files.

Our files are in pdf, doc and xls format they changes every now and then as and when it is required.

What we are thinking of using MD5 checksum to find out hashcode of files on Main server and store it in database. Same would be there in Client Servers database. After comparing records on database we would come to know whether client servers are synced or not.

Please suggest if there are any better ways to do the same.

答:
About your new wheel design concept - it's been done: rsync

utility software and network protocol for Unix-like systems (with ports to Windows) that synchronizes files and directories from one location to another while minimizing data transfer by using delta encoding when appropriate...

The recipient splits its copy of the file into fixed-size non-overlapping chunks and computes two checksums for each chunk: the MD5 hash, and a weaker 'rolling checksum'... It sends these checksums to the sender...


答: It might be easier to just remember when the files were last synced. Calculating a hash for a large file could be expensive. If the modification date is after the sync date on either machine, the file needs to be synced again. Comparing dates is cheap and doesn't depend on file size.</p>

Title: Would md5 hashes allow detection of synced files?

Body:
We have to develop our own file management system in Java web application. We need to sync files between our main server and client severs and find out whether all the client server has all the latest version of files.

Our files are in pdf, doc and xls format they changes every now and then as and when it is required.

What we are thinking of using MD5 checksum to find out hashcode of files on Main server and store it in database. Same would be there in Client Servers database. After comparing records on database we would come to know whether client servers are synced or not.

Please suggest if there are any better ways to do the same.


问:
Should Controller know about View & Model? or vice versa?
I'm conceptually trying to understand if I should be doing this:

```<code>item = Model()
screen = View()
brain = Controller(item, screen)
</code>```

or this..

```<code>brain = Controller()
item = Model(brain)
screen = View(brain)
</code>```

or this..

```<code>class Controller():
    def __init__(self):
        item = Model(self)
        screen = View(self)
</code>```

or something else entirely?

答:
MVC was originally defined to ease the programming of desktop applications.  The view subscribed to model events, updating the presentation when the model changed.  The controller merely translated user interface events (e.g. a button press) into calls to the model.  So the controller and view depended on the model, but were independent of each other.  The model was independent of both.  This allowed multiple views and controllers to work on the same model.

The "MVC" architecture used for web 1.0 applications (full page refresh, no AJAX) is somewhat different.  A web request is dispatched to a controller.  The controller somehow modifies the model state, then sends one or more models to be rendered by a view.  The controller and view both depend on the model, but the controller also depends on the view.

With web 2.0 applications, we are returning to the classic MVC architecture, on the client side.  The model, view, and controller all reside on the client side as Javascript objects.  The controller translates user events to model actions.  The model actions may or may not result in an AJAX request to the server.  Again, the view subscribes to model events and updates the presentation accordingly.


问:
What's a good math textbook to have on my desk while studying Haskell?
I just started learning Haskell and it seems like you can't get too far in the language without being comfortable ( or at least exposed ) to certain branches of mathematics. Unfortunately I have major holes in such areas and am wondering what is a good introductory textbook that covers all the concepts Haskell uses?

For what it's worth, I have an undergraduate engineering degree ( not comp-sci or EE ), though the math I was exposed to was of the hand-wave and memorize variety. I also took an intro to comp-sci course where we did a few weeks of oCaml.

答: "Basic Category Theory for Computer Scientists" by Benjamin C. Pierce is a pretty good introduction to elementary category theory. It's been a while seen I've looked through it but I think the code examples are in Haskell. If you're trying to learn the fundamentals of Haskell then you don't need any category theory. Knowing some basic type theory is enough.</p>


答:
Yes, MD5 is almost guaranteed to detect any change in files you produce. Collision attacks (methods to create different files with identical hash sums) are possible, but that is only a concern when you are fighting an attacker who is actively trying to produce them. In normal operation this is not a concern; your hardware failing is much, much more likely than an accidental collision.

So, mathematically, using MD5 for sync algorithms is fine. But as others have pointed out, there may be ready-made solutions that make more sense for you, or it may be too expensive to scan the full content of every file regularly - that depends on your particular situation..


问:
Which self balancing binary tree would you recommend?
I'm learning Haskell and as an exercise I'm making binary trees. Having made a regular binary tree, I want to adapt it to be self balancing. So:

Which is most efficient?

Which is easiest to implement?

Which is most often used?

But crucially, which do you recommend?

I assume this belongs here because it's open to debate.

答:
A very simple balanced tree is an AA tree. It's invariant is simpler and thus easier implement. Because of its simplicity, its performance is still good.

As an advanced exercise, you can try to use GADTs to implement one of the variants of balanced trees whose invariant is enforced by the type system type.


问:
Is there an established software taxonomy that's based on the type of software?
I'm researching engineering approaches to software development based on the type of software, for example:

Custom one-off software (e.g. space shuttle software)

Whitebox application requiring customised (e.g. Apache Ofbiz ERP - source code is usually downloaded and customized for each implementation)

Blackbox application without extension points

Blackbox application with extension points for customisation (e.g. MS Word, SAP)

...

Is there an established taxonomy of different types of software based on how the software is implemented?

答:
This is ancient but still useful:

http://www.joelonsoftware.com/articles/FiveWorlds.html

I think there are five worlds here, sometimes intersecting, often not.
  The five are:

Shrinkwrap

Internal

Embedded

Games

Throwaway

When you read the latest book about Extreme Programming, or one of
  Steve McConnell's excellent books, or Joel on Software, or Software
  Development magazine, you see a lot of claims about how to do software
  development, but you hardly ever see any mention of what kind of
  development they're talking about, which is unfortunate, because
  sometimes you need to do things differently in different worlds.


问:
What to do with a not well organized application?
I'm a newly graduate programmer and just got hired before my graduation. In the office, I used to create and revise modules of some applications developed by other programmers in our company. The problems I encountered with their applications are:

Unnormalized database at it's best, they've broken all the rules of database normalization, Codd must be angry.

50% of the content of the database is literally NULL (they should have default value I swear).

One stored procedure is used in all database transactions, full of "if-else" statements.

They are reinventing the application settings in .NET WinForms, they create their own file which contains everything they want. I think they are very fan of VB6 or maybe they don't study really, they're guessing how to achieve something.

No error handling! Clients sometimes report "Exceptions" which they shouldn't be seeing.

Web files and Windows Forms are not organized or grouped according to their use.

Naming convention, there are Camel case, pure lower case, with and without underscores and abbreviations.

Bad programming practices like database transaction in each iteration of a loop.

They developed website with SQL injection in mind, they welcome them.

HTML elements were not used according to their sematics.

CSS are not optimized for different browsers.

They include several versions of jQuery in one HTML!

.
.
.

N. Many more!

The worst thing is, I felt being blamed for it's fragility. I mean, when I add code, there are times that it ends up with error, sometimes because they did not create constraints or they allowed duplicate data. The system is so fragile and dependent to one another, it's like walking in a field with landmines! (THIS HAPPENS SOMETIMES, THIS IS NOT THE REAL ISSUE)

What should I do?

答:
When the code looks right, the logic is right.

The process of reformatting and refactoring code you are charged with fixing/changing is an effective technique for catching logic errors and unhandled corner-cases. 'Facading' code that your code depends on (see Gaga's answer, point f, for details), is a practical approach to cleaning up code for the current use. Creating wrappers or even a parallel API layer can be a reliable way to evolve the code base while maintaining backward compatibility for dependant code that can't be changed yet.

On mainframe and other "legacy" systems where downtime is not an option, where the most modern tools and languages are often not available, and where new hires often find themselves while they "learn the ropes," code-maintenance techniques like these can be vital to success.

(extensively revised from original based on feedback below)


答:
I personally would be much happier assigning copyright to a properly constituted not-for-profit foundation than to a company or a person.

On the other hand, if the project has a sound Open Source License and publicly available source code, then a company or individual can't kill a vibrant project.  They cannot take away the community's ability to fork.

(You will note that I'm don't find it particularly concerning that the copyright assignee can turn a profit from my contributions ... or do other things with the code-base that I would find distasteful, etcetera.  1) I didn't contribute to make a buck, and 2) other people's bad actions are not my moral responsibility.  Of course, if you didn't share my view then you would have more reasons to hesitate about assigning copyright at all.)


问:
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.

答: Keyboarding form is related to programming ability.  Seriously, one of the teachers at my high school told me, "You can't code quickly if you can't type quickly."  My response was, "That's like saying I can only write the Great American Novel if I do it in cursive."</p>


问:
How can I apply Six Sigma in a software development environment?
I am a Java developer, but I was asked to learn about applying Six Sigma with the goal of increasing our organization's profits. I have read that Six Sigma can be applied in all environments, but I'm interested in the nuances of applying it to software development.

Which concepts of Six Sigma can be applied to a software development environment and how can I effectively apply them?

My understanding is that Six Sigma focuses on:

identifying and removing root causes of defects

minimizing variability in applying manufacturing or business processes

It appears to me that these concepts could be applied to software development, but can that be applied effectively to an Software Development Lifecycle (SDLC)?

答:
Applying six sigma in software development is called software six sigma. Six Sigma is basically developed for manufacturing, in manufacturing process it helps companies to improve the delivery, quality of the product at a low cost. Whereas the same can applied to the software development too.

Applying six sigma in software development creates sustained improvement in the development of a software. Applying six sigma in software development results in speedy integration and testing of the software, helps to create a bug free software and it helps is more efficient program management.

However, software six sigma being a new concept you need the training from right people. An efficient six sigma training program can help you here. For online six sigma training on software development environment I would suggest http://www.6sigma.us/. I suggest them based on the recommendation I received from another firm.


问:
Differences in If... Else... statement
When I first started to learn programming I remember having an argument with my teacher about If Else statements. I was arguing that:

```<code> if {
      ...
 } else if {
      ...
 } ...
</code>```

is basically the same as:

```<code> if {
      ...
 else {
      if {
           ...
      } else {
           if {
                ...
           } else {
                ...
           }
      }
 }
</code>```

but he said they were completely different. After a while of arguing I accepted they are different. Now, over the years I have come back to this and looked over them to see the apparent major difference but for the life of me I cannot see it.

Can someone please clarify why exactly they  are different (apart from the obvious nesting)

答:
They are logically equivalent and achieve the same thing, it's just a different way to format the code. The difference generally comes down to readability of your code. I find nested if statements harder to read personally and try to avoid them.

These statements are the same:

```<code>if (condition1)
  //block 1
else if (condition2)
  //block 2

if (conditon1)
   //block 1
else
    if (condition2)
        //block 2
</code>```

Another difference comes into play (readability wise, remember - they're the same once compiled) is where you have nested ifs without elses, as they then become equivalent to and statements:

```<code>if (condition1)
    if(condition2)
       //do something
</code>```

Is the same as:

```<code>if (condition1 && condition2)
    //do something
</code>```

Title: Differences in If... Else... statement

Body:
They are logically equivalent and achieve the same thing, it's just a different way to format the code. The difference generally comes down to readability of your code. I find nested if statements harder to read personally and try to avoid them.

These statements are the same:

if (condition1)
  //block 1
else if (condition2)
  //block 2

if (conditon1)
   //block 1
else
    if (condition2)
        //block 2

Another difference comes into play (readability wise, remember - they're the same once compiled) is where you have nested ifs without elses, as they then become equivalent to and statements:

if (condition1)
    if(condition2)
       //do something

Is the same as:

if (condition1 && condition2)
    //do something


答:
Logically the two if-else statements are equal. They will have the same result.

The difference is in their semantics. By writing

```<code> if(condition 1) {
 ...
 } else if(condition 2) {
 ...
 else if(condition n) {
 ...
 }
</code>```

you mean that condition 1, ... condition n are equal (they refer to the same condition or state).

Statements like

```<code> if(condition) {
 ...
 } else {
 // nested if-else statements here
 ...
 }
</code>```

assume that condition has only two equivalent states (for example if(x > 0) { } else {}).

When you need two choose between the two, the priority should be readability, and the second statement is rarely preferable.

Title: Differences in If... Else... statement

Body:
When I first started to learn programming I remember having an argument with my teacher about If Else statements. I was arguing that:

```<code> if {
      ...
 } else if {
      ...
 } ...
</code>```

is basically the same as:

```<code> if {
      ...
 else {
      if {
           ...
      } else {
           if {
                ...
           } else {
                ...
           }
      }
 }
</code>```

but he said they were completely different. After a while of arguing I accepted they are different. Now, over the years I have come back to this and looked over them to see the apparent major difference but for the life of me I cannot see it.

Can someone please clarify why exactly they  are different (apart from the obvious nesting)

Body:
Logically the two if-else statements are equal. They will have the same result.

The difference is in their semantics. By writing

 if(condition 1) {
 ...
 } else if(condition 2) {
 ...
 else if(condition n) {
 ...
 }

you mean that condition 1, ... condition n are equal (they refer to the same condition or state).

Statements like

 if(condition) {
 ...
 } else {
 // nested if-else statements here
 ...
 }

assume that condition has only two equivalent states (for example if(x > 0) { } else {}).

When you need two choose between the two, the priority should be readability, and the second statement is rarely preferable.


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答: Linus Trovalds writing Linux</p>

Body: Linus Trovalds writing Linux


答:
If you do this, I would recommend comparing the size in bytes prior to the MD5 (or other) hash.

If the size is different between the two machines, you know the file is different. No need to waste time calculating a hash. And for most file types - certainly including those that you mentioned - it is extremely unlikely that a change will leave you with exactly the same file size.