问:
What is the best way to store a table in C++
I'm programming a decision tree in C++ using a slightly modified version of the C4.5 algorithm. Each node represents an attribute or a column of your data set and it has a children per possible value of the attribute.

My problem is how to store the training data set having in mind that I have to use a subset for each node so I need a quick way to only select a subset of rows and columns.

The main goal is to do it in the most memory and time efficient possible (in that order of priority).

The best way I have thought of is to have an array of arrays (or std::vector), or something like that, and for each node have a list (array, vector, etc) or something with the column,line(probably a tuple) pairs that are valid for that node.

I now there should be a better way to do this, any suggestions?

UPDATE: What I need is something like this:

In the beginning I have this data:

```<code>Paris    4    5.0    True
New York 7    1.3    True
Tokio    2    9.1    False
Paris    9    6.8    True
Tokio    0    8.4    False
</code>```

But for the second node I just need this data:

```<code>Paris    4    5.0
New York 7    1.3
Paris    9    6.8
</code>```

And for the third node:

```<code>Tokio    2    9.1
Tokio    0    8.4
</code>```

But with a table of millions of records with up to hundreds of columns.

What I have in mind is keep all the data in a matrix, and then for each node keep the info of the current columns and rows. Something like this:

```<code>Paris    4    5.0    True
New York 7    1.3    True
Tokio    2    9.1    False
Paris    9    6.8    True
Tokio    0    8.4    False
</code>```

Node 2:

```<code>columns = [0,1,2]
rows = [0,1,3]
</code>```

Node 3:

```<code>columns = [0,1,2]
rows = [2,4]
</code>```

This way on the worst case scenario I just have to waste

```<code>size_of(int) * (number_of_columns + number_of_rows) * node
</code>```

That is a lot less than having an independent data matrix for each node.

答:
Last time I tried to understand C4.5, I failed, but I have implemented a variant of ID3 - originally out of curiosity, but it eventually got used as part of an overkill multiple-dispatch code generator. This never deals with large data sets, though, and it's a good job. You wouldn't do well to imitate most of what I did, but maybe with a few exceptions, and of course I learned a bit from the mistakes.

I tend to think in terms of building a decision tree for an expert system, so I tend to use the following terms - sorry if that's confusing...

```<code>Column = Question ..... A question the expert system might ask
Row    = Conclusion ... A possible conclusion the expert system might reach
Cell   = Answer ....... For the question and conclusion, what answer should
                        the user be expected to give
</code>```

Actually, in my case, I made the conclusion into another column - similar to a truth table for a logic gate. Row numbers were therefore just row numbers. This allowed me to handle XOR-style problems which can't even be represented if the same conclusion cannot appear on several rows. I'm not sure if this is relevant to you or not. In any case, I'm ignoring this below - it doesn't really make a lot of difference unless until you look at the details of choosing which question to ask next anyway. For data mining, you probably don't have a particular piece of information to treat as the target conclusion anyway - the "conclusion" is just whatever is left when you decide to stop asking questions.

So - for each decision tree node derived so far, you have a set of outstanding questions (columns) and a set of not-yet-eliminated conclusions (rows). That's what I did. The only point worth adding is I used bit-vectors.

IIRC, the C++ std::vector<bool> and std::array<bool> may be implemented as bit-vectors, but you're still reliant on the STL algorithms for set operations, which operate one item at a time. I used my own bit-vector class which has been gradually built up over a period of time, and which uses bitwise operators on the underlying std::vector<CHUNK> (where CHUNK is an unsigned int type, usually 32 bits wide).

There may be a better bit-vector option in C++11 or in Boost, and there must be some good libraries out there some where - there's plenty of kinds of program where you end up working with sets of unsigned integers. I just don't know much about them because I've been too lazy to switch from using my own.

However, bit-vectors are at there best when sets are mostly dense. In this case, the set of rows is the obvious problem. Only the root node of the decision tree will have a perfectly dense row-set. As you get further from the root, the row sets get sparser and sparser, with each question answered resulting in the set of rows been distributed between two or more disjoint next-node row sets.

So a simple sorted-array-of-row-numbers might be the best representation for these sets. However, it's also possible that a "sparse bit-vector" might be worthwhile. One possible implementation is a sorted array of pairs where the first of each pair is the first row-ID of a block and the second is a fixed-size bitvector for that block. For example, the row number 35 might be stored in block 32 (35 & ~(32 - 1)) in bit position 3 (35 & (32 - 1)). If you only save the pairs where the bitvector is non-zero, this gives something between a sorted array of IDs and a simple bitvector - it handles sparse arrays reasonably well, especially when IDs tend to cluster closely together in sets.

Also, it may be worthwhile using a class that can switch from a bitvector to a sorted-array representation when the size gets small enough. The extra complication, purely to benefit a few nodes near the root, is probably pointless though.

Anyway, however these sets are represented, as they refer back to a single constant "database", this saves a lot in data-copying and space-waste as the algorithm runs. But it's still worth looking at that "database".

I used an associative data structure, allowing me to look up using a tuple of question-ID and conclusion-ID to get a answer-ID. That means I had a per-item overhead for the key (question-ID and conclusion-ID) and in this case B+-style tree overhead as well. The reason - basically habit. I have containers that are very flexible, and I tend to use them a lot because it saves on anticipating what capabilities I'll actually need later. There's a price for that, but that's just the old premature optimisation thing.

In your case, you're using a matrix - I assume a two-dimensional array indexed by question-ID and answer-ID.

The only way I can imagine my version being more efficient that yours is if most answers aren't known. In a matrix, you need a special not-known answer ID for that, taking the same space as a known answer-ID. In an associative container, you exclude those rows.

Even so, a sorted array would be more efficient than my B+ tree based solution. You don't need to allow for efficient inserts, so the only necessary overhead is for the keys.

If you use two key fields (question and conclusion, row and column) that might be a problem (I don't really remember) - you maybe can't just keep one copy of the table in one sorted order. But if you use a single computed key along the lines of (row * num_columns) + column, you're basically implementing a two dimensional sparse array anyway.

For me, the presence of unknown/undefined answers for a particular question means I'm not allowed to ask that question yet - and even that was just the theory I used back when I first implemented the algorithm. I never actually put that to use. There's a use I could put it to, but I never got around to it. For the record, in that multiple-dispatch code generator, one idea was to dispatch based on fields in the type. As the type itself is polymorphic, those fields may not even be there, so it's only valid to look at them once you've confirmed that they must be present.

If you don't have an application for unknown/undefined answers, your existing matrix is probably the best solution already.

So basically, that's it - I can't really offer any clearly better options, and what you're doing is probably already better than what I did. However, there are some trade-off possibilities that you might consider - assuming that's not premature (and possibly false) optimisation, of course.

The main trade-off issue relates to the efficiency of representations of sparse vs. dense sets of values, so it isn't really specific to C4.5 or decision-tree building. And a more "sophisticated" approach is often less efficient than a simple one that was chosen with care.

Body:
Last time I tried to understand C4.5, I failed, but I have implemented a variant of ID3 - originally out of curiosity, but it eventually got used as part of an overkill multiple-dispatch code generator. This never deals with large data sets, though, and it's a good job. You wouldn't do well to imitate most of what I did, but maybe with a few exceptions, and of course I learned a bit from the mistakes.

I tend to think in terms of building a decision tree for an expert system, so I tend to use the following terms - sorry if that's confusing...

Column = Question ..... A question the expert system might ask
Row    = Conclusion ... A possible conclusion the expert system might reach
Cell   = Answer ....... For the question and conclusion, what answer should
                        the user be expected to give

Actually, in my case, I made the conclusion into another column - similar to a truth table for a logic gate. Row numbers were therefore just row numbers. This allowed me to handle XOR-style problems which can't even be represented if the same conclusion cannot appear on several rows. I'm not sure if this is relevant to you or not. In any case, I'm ignoring this below - it doesn't really make a lot of difference unless until you look at the details of choosing which question to ask next anyway. For data mining, you probably don't have a particular piece of information to treat as the target conclusion anyway - the "conclusion" is just whatever is left when you decide to stop asking questions.

So - for each decision tree node derived so far, you have a set of outstanding questions (columns) and a set of not-yet-eliminated conclusions (rows). That's what I did. The only point worth adding is I used bit-vectors.

IIRC, the C++ std::vector<bool> and std::array<bool> may be implemented as bit-vectors, but you're still reliant on the STL algorithms for set operations, which operate one item at a time. I used my own bit-vector class which has been gradually built up over a period of time, and which uses bitwise operators on the underlying std::vector<CHUNK> (where CHUNK is an unsigned int type, usually 32 bits wide).

There may be a better bit-vector option in C++11 or in Boost, and there must be some good libraries out there some where - there's plenty of kinds of program where you end up working with sets of unsigned integers. I just don't know much about them because I've been too lazy to switch from using my own.

However, bit-vectors are at there best when sets are mostly dense. In this case, the set of rows is the obvious problem. Only the root node of the decision tree will have a perfectly dense row-set. As you get further from the root, the row sets get sparser and sparser, with each question answered resulting in the set of rows been distributed between two or more disjoint next-node row sets.

So a simple sorted-array-of-row-numbers might be the best representation for these sets. However, it's also possible that a "sparse bit-vector" might be worthwhile. One possible implementation is a sorted array of pairs where the first of each pair is the first row-ID of a block and the second is a fixed-size bitvector for that block. For example, the row number 35 might be stored in block 32 (35 & ~(32 - 1)) in bit position 3 (35 & (32 - 1)). If you only save the pairs where the bitvector is non-zero, this gives something between a sorted array of IDs and a simple bitvector - it handles sparse arrays reasonably well, especially when IDs tend to cluster closely together in sets.

Also, it may be worthwhile using a class that can switch from a bitvector to a sorted-array representation when the size gets small enough. The extra complication, purely to benefit a few nodes near the root, is probably pointless though.

Anyway, however these sets are represented, as they refer back to a single constant "database", this saves a lot in data-copying and space-waste as the algorithm runs. But it's still worth looking at that "database".

I used an associative data structure, allowing me to look up using a tuple of question-ID and conclusion-ID to get a answer-ID. That means I had a per-item overhead for the key (question-ID and conclusion-ID) and in this case B+-style tree overhead as well. The reason - basically habit. I have containers that are very flexible, and I tend to use them a lot because it saves on anticipating what capabilities I'll actually need later. There's a price for that, but that's just the old premature optimisation thing.

In your case, you're using a matrix - I assume a two-dimensional array indexed by question-ID and answer-ID.

The only way I can imagine my version being more efficient that yours is if most answers aren't known. In a matrix, you need a special not-known answer ID for that, taking the same space as a known answer-ID. In an associative container, you exclude those rows.

Even so, a sorted array would be more efficient than my B+ tree based solution. You don't need to allow for efficient inserts, so the only necessary overhead is for the keys.

If you use two key fields (question and conclusion, row and column) that might be a problem (I don't really remember) - you maybe can't just keep one copy of the table in one sorted order. But if you use a single computed key along the lines of (row * num_columns) + column, you're basically implementing a two dimensional sparse array anyway.

For me, the presence of unknown/undefined answers for a particular question means I'm not allowed to ask that question yet - and even that was just the theory I used back when I first implemented the algorithm. I never actually put that to use. There's a use I could put it to, but I never got around to it. For the record, in that multiple-dispatch code generator, one idea was to dispatch based on fields in the type. As the type itself is polymorphic, those fields may not even be there, so it's only valid to look at them once you've confirmed that they must be present.

If you don't have an application for unknown/undefined answers, your existing matrix is probably the best solution already.

So basically, that's it - I can't really offer any clearly better options, and what you're doing is probably already better than what I did. However, there are some trade-off possibilities that you might consider - assuming that's not premature (and possibly false) optimisation, of course.

The main trade-off issue relates to the efficiency of representations of sparse vs. dense sets of values, so it isn't really specific to C4.5 or decision-tree building. And a more "sophisticated" approach is often less efficient than a simple one that was chosen with care.


问:
Throwing an exception inside finally
Static code analyzers like Fortify "complain" when an exception might be thrown inside a finally block, saying that Using a throw statement inside a finally block breaks the logical progression through the try-catch-finally. Normally I agree with this. But recently I've come across this code:

```<code>SomeFileWriter writer = null;
try {
     //init the writer
     //write into the file
} catch (...) {
     //exception handling
} finally {
     if (writer!= null) writer.close();
}
</code>```

Now if the writer cannot be closed properly the writer.close() method will throw an exception. An exception should be thrown because (most probably) the file wasn't saved after writing.

I could declare an extra variable, set it if there was an error closing the writer and throw an exception after the finally block. But this code works fine and I'm not sure whether to change it or not.

What are the drawbacks of throwing an exception inside the finally block?

答: I think this is something that you will need to address on a case by case basis. In some cases what the analyser is saying is correct in that the code you have is not that great and needs a rethink. But there may be other cases when throwing or even re-throwing might be the best thing. It's not something you can mandate.</p>

ContentLicense: CC BY-SA 3.0

Title: Throwing an exception inside finally


问:
What discipline does Computer Science belong to?
Is Computer Science science, applied mathematics, engineering, art, philosophy? "Other"?

To provide background, here is Steven Wartik's blog posting for Scientific American titled "I'm not a real scientist, and that's okay." The article covers some good topics for this question, but it leaves open more than it answers.

If you can think of the discipline, how would computer science fit into its definition? Should the discipline for Computer Science be based on what programmers do, or what academics do? What kind of answers do you get from people who've seemed to think deeply about this? What reasons do they give?

答:
There are two distinct IT disciplines:

Computer Science - is the discipline study of computers and computation using the scientific method.

Software Engineering - is the discipline of designing and implementing software following proper engineering principles.

The two overlap somewhat, but the distinction is really about desired outcomes of science versus engineering.  The desired outcome of a scientific discipline is knowledge.  The desired outcome of a engineering discipline is things that work.

So to answer your question:

Is Computer Science science, applied mathematics, engineering, art, philosophy? "Other"?

Computer Science is Science ... when done properly.  However, like other disciplines CS has overlaps with Mathematics, Engineering, Physical Sciences, Social Sciences, Philosophy and so on.

I would also add that what most programmers do is neither Computer Science or Software Engineering.  It is more like what a craftsman does.

And sad to say, neither academic Computer Science or the Software Engineering profession are as rigorous as older science and engineering disciplines.  (There are fields of Computer Science that are traditionally rigorous; for example, the ones with a strong mathematical basis.  But for many fields, it is simply too hard / expensive to do proper scientific studies on the questions that really matter.)

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答:
Basically, finally clauses are there to ensure proper release of a resource. However, if an exception is thrown inside the finally block, that guarantee goes away. Worse, if your main block of code throws an exception, the exception raised in the finally block will hide it. It will look like the error was caused by the call to close, not for the real reason.

Some people follow a nasty pattern of nested exception handlers, swallowing any exceptions thrown in the finally block.

```<code>SomeFileWriter writer = null;
try {
     //init the writer
     //write into the file
} finally {
    if (writer!= null) {
        try {
            writer.close();
        } catch (...) {
            // swallow
        }
    }
}
</code>```

In older versions of Java, you can "simplify" this code by wrapping resources in classes that do this "safe" clean up for you. A good friend of mine creates a list of anonymous types, each that provide the logic for cleaning up their resources. Then his code simply loops over the list and calls the dispose method within the finally block.

Title: Throwing an exception inside finally

Body:
Static code analyzers like Fortify "complain" when an exception might be thrown inside a finally block, saying that Using a throw statement inside a finally block breaks the logical progression through the try-catch-finally. Normally I agree with this. But recently I've come across this code:

```<code>SomeFileWriter writer = null;
try {
     //init the writer
     //write into the file
} catch (...) {
     //exception handling
} finally {
     if (writer!= null) writer.close();
}
</code>```

Now if the writer cannot be closed properly the writer.close() method will throw an exception. An exception should be thrown because (most probably) the file wasn't saved after writing.

I could declare an extra variable, set it if there was an error closing the writer and throw an exception after the finally block. But this code works fine and I'm not sure whether to change it or not.

What are the drawbacks of throwing an exception inside the finally block?

Body:
Basically, finally clauses are there to ensure proper release of a resource. However, if an exception is thrown inside the finally block, that guarantee goes away. Worse, if your main block of code throws an exception, the exception raised in the finally block will hide it. It will look like the error was caused by the call to close, not for the real reason.

Some people follow a nasty pattern of nested exception handlers, swallowing any exceptions thrown in the finally block.

SomeFileWriter writer = null;
try {
     //init the writer
     //write into the file
} finally {
    if (writer!= null) {
        try {
            writer.close();
        } catch (...) {
            // swallow
        }
    }
}

In older versions of Java, you can "simplify" this code by wrapping resources in classes that do this "safe" clean up for you. A good friend of mine creates a list of anonymous types, each that provide the logic for cleaning up their resources. Then his code simply loops over the list and calls the dispose method within the finally block.


问:
Why would each widget need a reference to its parent in a simple widget system?
I'm working on a simple widget system (single window, fixed size). Each widget gets its parent (i.e. the widget containing it) passed into its constructor - except for the root widget, which I called Screen.

I have some doubts if that approach makes sense. I did it because most of the widget systems I used before do it (Qt, GTK, ...), but I realised that these are quite a bit more complex than mine:

I have no window resizing

I don't plan to size containers based on their children's sizes

I don't think I need it for memory management (I'm using C++), I can use shared pointers instead (basically how it would work in Java)

Is there any reason why a widget would need a reference to its parent?

It's a major refactoring to change this. So before I go ahead and implement containers and layouts, I want to have a good idea of whether or not I'm going to need that parent.

Edit: Please note that the parent does know all its children anyway, I'm just wondering if the children need to know the parent as well.

答:
I would say that, when the children know their parents, a widget and all its ancestors form a chain of responsibility. A typical example is a mouse event received by a widget : the widget can either consume the event (and react accordingly), or pass the event to its parent, who can either consume or pass to its parent, etc...

In the case of Qt, each widget is given its parent by constructor, and this indicates that the widget is owned by the parent. In particular, the deletion of the parent triggers the deletion of the widget.


答:
What Travis Parks said is true that exceptions in the finally block will consume any return values or exceptions from the try...catch blocks.

If you're using Java 7, though, the problem can be solved by using a try-with-resources block. According to the docs, as long as your resource implements java.lang.AutoCloseable (most library writers/readers do now), the try-with-resources block will close it for you. The additional benefit here is that any exception that occurs while closing it will be suppressed, allowing the original return value or exception to pass up.

From

```<code>FileWriter writer = null;
try {
  writer = new FileWriter("myFile.txt");
  writer.write("hello");
} catch(...) {
  // return/throw new exception
} finally {
  writer.close(); // an exception would consume the catch block's return/exception
}
</code>```

To

```<code>try (FileWriter writer = new FileWriter("myFile.txt")) {
  writer.write("hello");
} catch(...) {
  // return/throw new exception, always gets returned even if writer fails to close
}
</code>```

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Title: Throwing an exception inside finally

Body:
What Travis Parks said is true that exceptions in the finally block will consume any return values or exceptions from the try...catch blocks.

If you're using Java 7, though, the problem can be solved by using a try-with-resources block. According to the docs, as long as your resource implements java.lang.AutoCloseable (most library writers/readers do now), the try-with-resources block will close it for you. The additional benefit here is that any exception that occurs while closing it will be suppressed, allowing the original return value or exception to pass up.

From

FileWriter writer = null;
try {
  writer = new FileWriter("myFile.txt");
  writer.write("hello");
} catch(...) {
  // return/throw new exception
} finally {
  writer.close(); // an exception would consume the catch block's return/exception
}

To

try (FileWriter writer = new FileWriter("myFile.txt")) {
  writer.write("hello");
} catch(...) {
  // return/throw new exception, always gets returned even if writer fails to close
}

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


问:
With libraries available, should programmers also learn the old way of writting the same things?
With pre written programs available, needing just editing, should programmers also learn writing them from scratch?</p>

答:
You seem to believe that software developpement is a solved problem. It is not.

People in all businesses have a lot of reasons to be unsatisfied by existing technologies. New  hardware and new markets are created every day. New solutions to old problems are found. There will always be a need for new softwares/librairies.

Beside, you never actually write anything "from scratch". You use compilers and standard libraries. You should instead ask your self if you'd rather programm in high level or "low level" languages, depending on want you want to achieve.


答:
I'm going to hedge my bets with "it depends on the library."

If it's something specific like a Twitter client library, then you probably don't need to know how to write a Twitter-specific client from scratch. What you probably should know how to do is write a client for XML or JSON REST APIs, write basic HTTP transport, etc.

When you're building an application, having a wide ecosystem of libraries you can piece together is a definite plus, and probably shows you've made a good choice of language/platform/framework.

OTOH, you need to understand what's going on "under the covers", because not every (any?) library is going to account for every edge- or corner-case you might encounter in your specific business domain. So writing a similar library "from scratch" (or using lower-level components like the language's stdlib) is a wothwhile excercise. If nothing else, it will make you a more competent and more capable developer.

Should you use your library instead of a well-tested, open-source library that's in production successfully elsewhere? Probably not.

But that doesn't reduce the value of knowing how that library was built.

Title: With libraries available, should programmers also learn the old way of writting the same things?

Body: With pre written programs available, needing just editing, should programmers also learn writing them from scratch?</p>


问:
I code rarely. Is this a bad sign?
I am a computer science student and learning Java now a days.

I want to be a good developer/programmer.

I like reading books. I search on the internet for the related topics and study them. I refer to StackOverflow and other good programming websites daily but I code rarely. Is this a bad sign? If yes then what should I do to overcome this problem?

答:
If your still a student, I would fret so much. Your course studies are for more important right now. However, once you leave the world of Academia, you might have a problem if you still have yet to find what your interested in within this field and don't code.

I'm in a similar dilemma, I'm a senior finishing my B.S in Computer Science I don't code outside of my course work at the moment.

It really frustrates me right now to be studying AP Statistics and Geological Sciences with respect to weather than work on my personal projects.

I have a Game project I so desperately want to work on but I got to graduate as well. (I know why Marc Zuckerburg and Bill Gates Dropped out now).

If these things are what prevent you from coding, don't worry. But if Coding doesn't motivate you, drive you, and the urge to create something really cool to you doesn't kick in by the time you graduate, I think you might have a problem.

Title: I code rarely. Is this a bad sign?


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

答:
This example really misses the point.  We're talking about a single straightforward function here not a software design.  Is it a bit complicated? yes, so you break it down.  And you absolutely do not test every possible input from 1, 1, 1, 1, 1 to 6, 6, 6, 6, 6, 6.  The function in question doesn't require order, just a combination, namely AAABB.

You don't need 200 seperate logic tests. You could use a set for example. Nearly any programming language has one built in:

```<code>Set set;
set.add(a);
set.add(b);
set.add(c);
set.add(d);
set.add(e);

if(set.size() == 2) { // means we *must* be of the form AAAAB or AAABB.
    if(a==b==c==d) // eliminate AAAAB
        return false;
    else
        return true;
}
return false;
</code>```

And if you get an input that isn't a valid Yahtzee roll, you should throw like there's no tomorrow.

Title: How should you TDD a Yahtzee game?

Body:
This example really misses the point.  We're talking about a single straightforward function here not a software design.  Is it a bit complicated? yes, so you break it down.  And you absolutely do not test every possible input from 1, 1, 1, 1, 1 to 6, 6, 6, 6, 6, 6.  The function in question doesn't require order, just a combination, namely AAABB.

You don't need 200 seperate logic tests. You could use a set for example. Nearly any programming language has one built in:

Set set;
set.add(a);
set.add(b);
set.add(c);
set.add(d);
set.add(e);

if(set.size() == 2) { // means we *must* be of the form AAAAB or AAABB.
    if(a==b==c==d) // eliminate AAAAB
        return false;
    else
        return true;
}
return false;

And if you get an input that isn't a valid Yahtzee roll, you should throw like there's no tomorrow.


问:
Why shouldn't a GET request change data on the server?
All over the internet, I see the following advice:

A GET should never change data on the server- use a POST request for that

What is the basis for this idea?

If I make a php service which inserts data in the database, and pass it parameters in the GET query string, why is that wrong? (I am using prepared statements, to take care of SQL Injection). Is a POST request in some way more secure?

Or is there some historic reason for this? If so how valid is this advice today?

答:
Each HTTP verb has it's own responsibility. For example GET, as defined by RFC

means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

POST, on the other hand, means insert or more formally

The POST method is used to request that the origin server accept the

entity enclosed in the request as a new subordinate of the resource

identified by the Request-URI in the Request-Line

Reasons for keeping it this way:

It's very simple and works on the global Internet scale since 1991

Stick to the single responsibility principle

Other parties use GET to act as means of information retrieval and data mining

GET is assumed to be a safe operation that never modifies the state of the resource

Security considerations, GET is effectively a read, whereas POST is effectively a write

GET is cached by browsers, nodes in the network, Internet Service Providers

Unless the content changes, GET to the same URL must return same results to all the users or else you you won't have any trust what so ever in the returned result

For completeness and just to enforce correct usage (source):

GET parameters are passed as part of the URL, which is of small and limited length of 256 chars by default, with some servers supporting 4000+ chars. If you want to insert a long record, there is no legitimate way to pass this data in

W̶h̶e̶n̶ ̶u̶s̶i̶n̶g̶ ̶s̶e̶c̶u̶r̶e̶ ̶c̶o̶n̶n̶e̶c̶t̶i̶o̶n̶,̶ ̶s̶u̶c̶h̶ ̶a̶s̶ ̶T̶L̶S̶,̶ ̶U̶R̶L̶ ̶i̶s̶ ̶n̶o̶t̶ ̶g̶e̶t̶t̶i̶n̶g̶ ̶e̶n̶c̶r̶y̶p̶t̶e̶d̶,̶ ̶h̶e̶n̶c̶e̶ ̶a̶l̶l̶ ̶t̶h̶e̶ ̶p̶a̶r̶a̶m̶e̶t̶e̶r̶s̶ ̶o̶f̶ ̶̶G̶E̶T̶̶ ̶a̶r̶e̶ ̶t̶r̶a̶n̶s̶f̶e̶r̶r̶e̶d̶ ̶p̶l̶a̶i̶n̶ ̶t̶e̶x̶t̶. URL is actuall encrypted with TLS, so TLS is fine.

Inserting binary data or non-ASCII characters using GET is impractical

GET is re-executed if a user presses a Back button in a browser

Some older crawlers may not index URLs with a ? sign inside


问:
What's the standard practice to prevent users from having unreasonable expectations?
There's some subscription-based data processing web service - users pay via PayPal for the right to use the service. The "terms of service" document prepared by lawyers explicitly says that there're no guarantees so customers can't possibly file a lawsuit.

Now the service doesn't always work trouble-free. Sometimes there're network problems and so it's unreachable to some clients. Sometimes there's a problem with third-party services the service depends upon. So something like twelve hours per year total it doesn't work. This is not perfect, but IMO very good.

Yet clients feel that since they've paid for it - it must just work, period, at all times and they even write claims for compensation to the service support.

I'd guess they just don't read the "terms of service" but I can't be sure.

What's the standard practice (besides having "terms of service") to prevent users from having unreasonable expectations?

答:
This really isn't your question, but that a system works all the time isn't "unreasonable".  With that being said, it would depend on how your system reacts to failure by third party systems and providing a good user experience when those occur.

As for your question.  I would say that the best way to handle user's expectations is to provide them with a good experience in working with your system.  This will help reset your user's expectations of the system.  As pointed out in the comments, "No one reads the terms of service anyway".


答:
I think your idea is good. I am not sure how general your library for accessing the data you wish to be. But you could something like store your whole initial data in a std::vector of rows. If the columns are invariable for you, for the datatype I would choose boost::tuple library.

Then, you could pass a handle to the whole "database" to your Node types. It would be very easy to retrieve/access any subset of columns and rows from such structure. A Node type would act as a kind of proxy object or wrapper to access the data, somewhat acting as a view for the whole database.

Moreover, the time cost would be constant in time, as the data would be accessed directly. The memory footprint would be
low as you mentioned, cause the main cost is the initial database and there are no copies of the data itself made. Only cost would be indexes in from of the rows-columns vectors.

There is, however, one caveat. If you speak of millions of records and hundreds of columns, you need to remember there is a scalability limit for memory. You might be forced to resort to some real database system just be cause of memory amount limitations. I would advice probably SQLite. SQLite allows to create volatile in-memory database. So you can go with it initially and seamlessly transition into normal file DB if your data sets will grow too large.

Title: What is the best way to store a table in C++

Body:
I'm programming a decision tree in C++ using a slightly modified version of the C4.5 algorithm. Each node represents an attribute or a column of your data set and it has a children per possible value of the attribute.

My problem is how to store the training data set having in mind that I have to use a subset for each node so I need a quick way to only select a subset of rows and columns.

The main goal is to do it in the most memory and time efficient possible (in that order of priority).

The best way I have thought of is to have an array of arrays (or std::vector), or something like that, and for each node have a list (array, vector, etc) or something with the column,line(probably a tuple) pairs that are valid for that node.

I now there should be a better way to do this, any suggestions?

UPDATE: What I need is something like this:

In the beginning I have this data:

```<code>Paris    4    5.0    True
New York 7    1.3    True
Tokio    2    9.1    False
Paris    9    6.8    True
Tokio    0    8.4    False
</code>```

But for the second node I just need this data:

```<code>Paris    4    5.0
New York 7    1.3
Paris    9    6.8
</code>```

And for the third node:

```<code>Tokio    2    9.1
Tokio    0    8.4
</code>```

But with a table of millions of records with up to hundreds of columns.

What I have in mind is keep all the data in a matrix, and then for each node keep the info of the current columns and rows. Something like this:

```<code>Paris    4    5.0    True
New York 7    1.3    True
Tokio    2    9.1    False
Paris    9    6.8    True
Tokio    0    8.4    False
</code>```

Node 2:

```<code>columns = [0,1,2]
rows = [0,1,3]
</code>```

Node 3:

```<code>columns = [0,1,2]
rows = [2,4]
</code>```

This way on the worst case scenario I just have to waste

```<code>size_of(int) * (number_of_columns + number_of_rows) * node
</code>```

That is a lot less than having an independent data matrix for each node.


答:
Terms of service are a good start.  That helps protect you legally.

Otherwise:

Don't promise what you can't provide

This is good both legally and for customer satisfaction.  If you're advertising better service than you're providing (100% Uptime!) on your main page, even if the Terms of Service are more laid back there's going to be trouble.  This also applies to comparing yourself to services that you can't match/etc.  Focus on what you do well and sell it for all its worth, but do make sure you can actually live up to it.

Try to show the customer that you feel their pain when things don't go well

Things break, services go down.  When they do, make sure the customer knows you care.  Don't let them bully you into feeling like you have to provide more than you said, but if you have the opportunity to go above and beyond, do so.  And certainly if you DO drop below the terms of service, make sure you compensate them properly.

Title: What's the standard practice to prevent users from having unreasonable expectations?

Body:
There's some subscription-based data processing web service - users pay via PayPal for the right to use the service. The "terms of service" document prepared by lawyers explicitly says that there're no guarantees so customers can't possibly file a lawsuit.

Now the service doesn't always work trouble-free. Sometimes there're network problems and so it's unreachable to some clients. Sometimes there's a problem with third-party services the service depends upon. So something like twelve hours per year total it doesn't work. This is not perfect, but IMO very good.

Yet clients feel that since they've paid for it - it must just work, period, at all times and they even write claims for compensation to the service support.

I'd guess they just don't read the "terms of service" but I can't be sure.

What's the standard practice (besides having "terms of service") to prevent users from having unreasonable expectations?


答:
I think the only real answer here in helping your customers with unreasonable expectations is to be proactive with positive customer service.

What I mean is take every opportunity to reach out to your customers in a positive way when things are going well and go above and beyond to satisfy them when things are bad and most will overlook the small issues and negative experiences.

Overwhelming positive customer service will quell much in the way of negative experiences.

As a side, most users do not adequately read the ToS but stating it when they have a problem is not perceived as a positive experience. Sometimes even when you are right and they are wrong, you just have to make it right for the subscriber. What that is for your particular business I don't know. A free month maybe?


答:
It doesn't hurt, and its value will depend on the specific stack in question, but overall? Not really.

In the framework case, except for purely academic purposes (or if you want to contribute to the framework's development), I'd say you don't need to learn to write them from scratch, but you should have a general understanding of language the framework is for. That's the whole point of a framework. On the other hand, I don't need to know the ins and outs of FCKEditor in order to add it to my website, and even do moderate customizations to it.

Now, does that mean people shouldn't understand that the return value of a LINQ query is very often an IEnumerable type (or what IEnumerable is)? It's always good to have some understanding of the underlying structure of the higher-level technology that you're using.

Did you ever do any coding with .Net stuff before version 3 and the introduction of Entity Framework and LINQ? Did you ever have to do the raw ADO.NET calls to connect to a database, run the raw SQL query, get the data and store it somewhere, and make sure to disconnect from the database? This stuff wasn't really that hard, per se, but it did take time and testing - time better spent on doing something with that data. It was tedious, it was error-prone, and everyone had to do it, usually multiple times per application. Why not create a utility that deals with all that for you?

That's where Entity Framework (and really, any ORM or similar system for any language) comes in, and before that, people often built model-like classes to handle the connection tasks itself. By automating that system, you can spend your time using the data, instead of debugging the act of getting the data (and getting it into a state that's usable in your system).

If you want to take the idea of "writing everything from scratch" to it's absurd, though logical and very real extreme, then let's just go back to programming with physical chips and logic gates. I can tell you from experience that doing so will give you a very good understanding of how computers work, and the importance of binary.

But why? Why should everyone have to spend their time putting logic gates together, when that's already been done countless times, and refined to the point close enough to perfection to be reliable on a regular basis, without having an intimate knowledge of the details?

This goes all the way up the stack, from the physical gates and switches, through the binary, the assembler, and up the stack into the C and similar-level languages, and all the way up into the .Net framework you use today.

Have a general understanding of some of the underlying systems, and it would probably be a good rule of thumb to understand more about the systems closer to "the surface" of your current technology (ie - jQuery makes a lot of syntax changes to JavaScript, so there's often a stark contrast between the person that has a solid understanding of JS and one who just uses jQuery; in this case, the understanding of the technology the next level down is a major boon, but knowledge of the systems that JavaScript depends on (the layout engines in browsers, the languages underlying them, etc) becomes increasingly unnecessary), but that understanding need not be expert-level. Technology is a huge field, even narrowed down to programming. It's impossible for any given individual to know everything about every piece of technology that their current one depends on.


问:
Using natural language grammar in fluent API
I'm tinkering with a query abstraction over WebSQL/Phonegap Database API, and I find myself both drawn to, and doubtful of, defining a fluent API that mimics the use of natural English language grammar.

It might be easiest to explain this via examples. The following are all valid queries in my grammar, and comments explain the intended semantic:

```<code>//find user where name equals "foo" or email starts with "foo@"
find("user").where("name").equals("foo").and("email").startsWith("foo@")

//find user where name equals "foo" or "bar"
find("user").where("name").equals("foo").or("bar");

//find user where name equals "foo" or ends with "bar"
find("user").where("name").equals("foo").or().endsWith("bar");

//find user where name equals or ends with "foo"
find("user").where("name").equals().or().endsWith("foo");

//find user where name equals "foo" and email is not like "%contoso.com"
find("user").where("name").equals("foo").and("email").is().not().like("%contoso.com");

//where name is not null
find("user").where("name").is().not().null();

//find post where author is "foo" and id is in (1,2,3)
find("post").where("author").is("foo").and("id").is().in(1, 2, 3);

//find post where id is between 1 and 100
find("post").where("id").is().between(1).and(100);
</code>```

Edit based on Quentin Pradet's feedback: In addition it seems, the API would have to support both plural and singular verb forms, so:

```<code>//a equals b
find("post").where("foo").equals(1);

//a and b (both) equal c
find("post").where("foo").and("bar").equal(2);
</code>```

For the sake of question, let's presume that I haven't exhausted all possible constructs here. Let's also presume that I can cover most correct English sentences - after all, the grammar itself is limited to the verbs and conjuctions defined by SQL.

Edit regarding grouping: One "sentence" is one group, and the precedence is as defined in SQL: left to right. Multiple groupings could be expressed with multiple where statements:

```<code>//the conjunctive "and()" between where statements is optional
find("post")
  .where("foo").and("bar").equal(2).and()
  .where("baz").isLessThan(5);
</code>```

As you can see, the definition of each method is dependent on the grammatical context it is in. For example the argument to "conjunction methods" or() and and() can either be left out, or refer to a field name or expected value.

To me this feels very intuitive, but I would like you hear your feedback: is this a good, useful API, or should I backpedal to more straighforward implementation?

For the record: this library will also provide a more conventional, non-fluent API based on configuration objects.

答:
I think it's very wrong. I study natural langage and it's full of ambiguity that can only be resolved with context and a lot of human knowledge. The fact that programming languages are not ambiguous is a very good thing! I don't think you want meaning of methods to change according to context:

This is adds more surprises since you bring ambiguity

Your users will want to use constructions that you will not have covered, eg. find("user").where("name").and("email").equals("foo");

It's hard to report errors: what can you do with find("user").where("name").not().is().null();?

Let's also presume that I can cover most correct English sentences -
  after all, the grammar itself is limited to the verbs and conjuctions
  defined by SQL.

No, you can't cover most correct English sentences. Others have tried before, and it gets very complicated very quickly. It's called Natural language understanding but nobody really tries that: we're trying to solve smaller problems first. For your library, you basically have two options:

either you restrict yourself to a subset of English: that gives you SQL,

or you try to cover "English" and you find out that it's not possible due to the ambiguity, complexity and diversity of the language.

OwnerDisplayName: fencliff

OwnerDisplayName: Quentin Pradet


问:
What is the preferred way of communicating between applications on the same system?
I'm designing a system that is built on several small applications written in python, some of these will be services and others will be programs that only run during special situations. What I need to achieve is to let the server communicate to a service when a certain event occurs with some small amount of data. So that the service knows about the new situation and can take the appropriate action, sometimes immediately and sometimes in the future.

I've been looking at memcached, but it seems like an overkill solution for my system (which is just a few separate applications running on a raspberry pi), or writing to files and using something like pyinotify but I don't think that is very elegant and finally I've been thinking about storing state in a database which I also don't like very much.

Are there any preferred ways to handle this sort of communication between processes that I haven't thought of(I'm sure there is) or which of the above mentioned ones would be the smartest to go with?

答:
To my knowledge, the only standard for specific technologies is "whatever works for your needs."

That said, you might want to look into Redis. I've used it before to communicate between disparate systems, and it works well.

Basically, what it is is an in-memory datastore. You set the service to watch for a specific key, and when your system does something with that watched key, the service reacts.

In a more general sense, what you're asking for is often known as a "pub-sub" (publisher-subscriber) setup. So if Redis doesn't work for you, you might be able to use the more general term to find a solution that does work. And really, if you wanted to, you could leverage Twitter to be the intermediary, if you really wanted to (the system would post a tweet, and the service would watch the twitter feed for updates). If I recall correctly, GitHub uses Hubot and Campfire in a similar manner (Hubot sits in a Campfire chat room, waiting for someone to send commands, to which Hubot responds).


答:
Make some promises, make them prominent, and keep them. If you fail, extend your user's subscriptions appropriately to cover the down time. Don't promise anything you don't think you can deliver, but if you start making (and keeping) promises, then you'll take care of a lot of the customer issues.

Now, your lawyers may try to weasel-word you (in the TOS) out of making these promises real. Don't let them do it.

Don't promise you'll give away the store if it all goes pear-shaped on you one day (because it will), but don't treat these promises like marketing-speak. Mean them. Own them. Live up to them.

Do realize that you'll always have some annoying customer who thinks that having sent you $5 entitles them to everything in the universe, and compensation in the form of jeweled goblets filled with caviar whenever you have 5 minutes of downtime. Just be firm and tell them no. They might walk, but don't give into irrational demands - give them what you'd give everyone else, and get on with your day.


问:
Does anybody ever uses the OpenId url Log in?
As programmers I think we are the most inclined to use new technologies and things that are not so mainstream.

I absolutely love OpenId's ability to log in with credentials you already have, but I always use a provider that I already use and that is the fastest to log in, like google. God knows I'd never used it if i had to type in the whole "https://www.google.com/accounts/o8/id" I like to click on the google button and then just say yes (the first time, then its just clicking the button).

Does any of you ever uses the Generic "Enter your own provider" OpenId?

Do you think its worth to even offer it to more casual end users?

答: Yes. I set up delegation on my own site, so I just use one of my own URLs. Easy to remember, and doesn't tie me to a provider.</p>


问:
Will a program ever crash if the main loop is put in a try/catch block
If we have a class main and the constructor of main constructs our setupclass and we put this class in a try catch in main.

Theoratically Will all errors go into catch? If they will how will it effect the performance and mantainability? Will the application be crash free?

答:
Depends on languaga but probably not.

In c# then other threads generating exceptions will kill the main process off the top of my head.

It's irrelevant though, except for very simple programs, you're likely to end up in an irrecoverable state resulting in bad or lost data which for most users is much worse than the application crashing.


答:
Your program can still crash or otherwise fail to perform it's tasks:

Your exception handling code could have a bug in it; by definition your handler is outside of the code 'protected' by your try / catch, so an error there will still result in a program crash.

Just because you handled the exception, doesn't mean you your program state is still sane. Your program could easily end up in a state that is effectively useless, because it's internal state is left in an inconsistent state. You program will then continually throw exceptions, and the end user will be left with no other option but to terminate your program forcibly.

Moreover, because you catch all exceptions, you'll have a much harder time debugging what actually goes wrong in your program, and you can never be sure if the exceptions you see are the results of broken internal state after a previous exception was handled, or a genuine bug.

Better to let your program crash. At least then the end user understands the program broke, and you as a developer will have a much better sense of what broke the program.

Title: Will a program ever crash if the main loop is put in a try/catch block

Body:
If we have a class main and the constructor of main constructs our setupclass and we put this class in a try catch in main.

Theoratically Will all errors go into catch? If they will how will it effect the performance and mantainability? Will the application be crash free?


答:
Yes and no.  I work on embedded systems.  When an unhandled exception occurs we log it and reboot the system, very similar to what you're suggesting.  Maybe 9 times out of 10 the reboot clears up the problem, at least good enough while the exception report is being analyzed for a fix.  The other 1 time in 10 we get a continuous reboot cycle, which is enough of a problem unto its own that we keep track of how many reboots have happened and go into a "recovery" mode after a few tries.

At any rate, it's no panacea.  It's a small bandage you apply to give you time to fix it for real, and it's only helpful if you get those exception reports and have solid initialization code that truly resets the state of your system.


答:
The appropriate goal is not to make your application "crash free" but to make your application reliable and stable.

It may be possible to reduce or even virtually eliminate crashes with exception handling.  However, all other things being equal, this will simply replace crashes with cases in which the program enters an unusable state.

This isn't going to look any better to your users.  In fact, it will very likely be worse.  At least a crash is a clear, clean failure.  A program in a non-functioning state is ambiguous at best.  The user may waste a long time to see if the application is frozen or just "thinking".  At worst it may actually do damage, continuing to perform actions, but in a corrupt manner.

There is no shortcut to writing good, reliable code.


问:
What would be the best way to store movements on a game to allow a rollback?
I'm developing a board game that has a game class that controls the game flow, and players attached to the game class. The board is just a visual class, but the control of the movements is all by the game.

The player can try to make false movements that lead to the game telling the player that this kind of movement is not allowed (and tell the reason behind it). But in some cases, the player can just make a movement and realize it's not the best move, or just miss click the board, or just want to try another approach.

The game can be saved and loaded, so an approach could be storing all the data before the movement and not allow a rollback, but allow the user to load the last autosaved turn. This looks like a nice approach, but involves user interaction, and the redrawing of the board could be tedious to the user. Is there a better way to do this kind of things or the architecture really matters on this thing?

The game class and player class are not complicate so it's cloning the classes a good idea, or separate the game data from the game rules a better approach, or the saving/loading (even automatic on an asked rollback) is ok?

UPDATE: how this game works:
It has a main board where you make moves (simple moves) and a player board that react on the moves makes on the main board. It also has reaction moves according to other player moves and on yourself moves.You can also react when is not your turn, doing things on your board. Maybe I can't undo every move, but I like the undo/redo idea floating in one of the current answers.

答:
Why not store the history of all moves made (as well as any other non-deterministic events)?  That way you can always reconstruct any given game state.

This will take significantly less storage space than storing all of the game states, and it would be fairly simple to implement.


答:
I would maintain an undo-list of the (valid) moves the player made.

Each item in the list should contain enough information to restore the game state to what it was just before the move was made. Depending on the amount of game-state that there is and the number of undo-steps you want to support, this could be a snapshot of the game-state, or information that tells the game-engine how to reverse the move.

Title: What would be the best way to store movements on a game to allow a rollback?

Body:
I'm developing a board game that has a game class that controls the game flow, and players attached to the game class. The board is just a visual class, but the control of the movements is all by the game.

The player can try to make false movements that lead to the game telling the player that this kind of movement is not allowed (and tell the reason behind it). But in some cases, the player can just make a movement and realize it's not the best move, or just miss click the board, or just want to try another approach.

The game can be saved and loaded, so an approach could be storing all the data before the movement and not allow a rollback, but allow the user to load the last autosaved turn. This looks like a nice approach, but involves user interaction, and the redrawing of the board could be tedious to the user. Is there a better way to do this kind of things or the architecture really matters on this thing?

The game class and player class are not complicate so it's cloning the classes a good idea, or separate the game data from the game rules a better approach, or the saving/loading (even automatic on an asked rollback) is ok?

UPDATE: how this game works:
It has a main board where you make moves (simple moves) and a player board that react on the moves makes on the main board. It also has reaction moves according to other player moves and on yourself moves.You can also react when is not your turn, doing things on your board. Maybe I can't undo every move, but I like the undo/redo idea floating in one of the current answers.


答:
Building an Undo system is conceptually pretty simple.  You just need to keep track of changes.  You'll want a stack, and an object type that describes a piece of the state of the game.  Your stack should be a stack of arrays/lists of game state objects.

The trick is, don't record moves that people make.  I see this in the other answers, and it can be done, but it's a lot more complicated.  Instead, record what the game board looked like before the move was made. For example, when you move a piece, you've made two changes: The piece left one square, and the piece was placed onto a new square.  If you create an array showing what those two squares looked like before the move began, then you can Undo the move simply by restoring those two squares to the way they were before the move was made.

Or, if your game state is held in the pieces and not the squares, then what you record is the position of the piece before it moved.  (And if your piece interacts with any other pieces, such as a capture in chess, record where those other pieces were before they were changed.)

When any move happens:

Create a new Undo frame (array)

Every time something changes, if you do not already have a change for that object in the current Undo frame, add its state to the current Undo frame before applying the change.

When the move is over, push the Undo frame onto the stack.

When the user says Undo:

pop the top of the stack and grab an Undo frame

iterate over each object in the frame, and restore it

(Optionally): Track the changes made here in exactly the same way as you did when setting up an Undo frame, and push the frame onto a stack. This is how you implement Redo.  (If you do this, pushing a new Undo frame should also clear the Redo stack.)


答:
In addition to Quentin Pradet's very good points, I am doubtful of the alleged benefits of this language.

Presumably the point of a grammar close to natural language is to make it accessible.  But SQL already is quite close to natural language.  Is one of these really closer to English than the other?

```<code>find("user").where("name").equals("foo")

select user from table where name = 'foo'
</code>```

I don't really see the benefit of your grammar, from a standpoint of intuitiveness or readability.  In fact, the SQL version looks more readable (and is easier to type) because of its whitespace.

Title: Using natural language grammar in fluent API

Body:
I'm tinkering with a query abstraction over WebSQL/Phonegap Database API, and I find myself both drawn to, and doubtful of, defining a fluent API that mimics the use of natural English language grammar.

It might be easiest to explain this via examples. The following are all valid queries in my grammar, and comments explain the intended semantic:

```<code>//find user where name equals "foo" or email starts with "foo@"
find("user").where("name").equals("foo").and("email").startsWith("foo@")

//find user where name equals "foo" or "bar"
find("user").where("name").equals("foo").or("bar");

//find user where name equals "foo" or ends with "bar"
find("user").where("name").equals("foo").or().endsWith("bar");

//find user where name equals or ends with "foo"
find("user").where("name").equals().or().endsWith("foo");

//find user where name equals "foo" and email is not like "%contoso.com"
find("user").where("name").equals("foo").and("email").is().not().like("%contoso.com");

//where name is not null
find("user").where("name").is().not().null();

//find post where author is "foo" and id is in (1,2,3)
find("post").where("author").is("foo").and("id").is().in(1, 2, 3);

//find post where id is between 1 and 100
find("post").where("id").is().between(1).and(100);
</code>```

Edit based on Quentin Pradet's feedback: In addition it seems, the API would have to support both plural and singular verb forms, so:

```<code>//a equals b
find("post").where("foo").equals(1);

//a and b (both) equal c
find("post").where("foo").and("bar").equal(2);
</code>```

For the sake of question, let's presume that I haven't exhausted all possible constructs here. Let's also presume that I can cover most correct English sentences - after all, the grammar itself is limited to the verbs and conjuctions defined by SQL.

Edit regarding grouping: One "sentence" is one group, and the precedence is as defined in SQL: left to right. Multiple groupings could be expressed with multiple where statements:

```<code>//the conjunctive "and()" between where statements is optional
find("post")
  .where("foo").and("bar").equal(2).and()
  .where("baz").isLessThan(5);
</code>```

As you can see, the definition of each method is dependent on the grammatical context it is in. For example the argument to "conjunction methods" or() and and() can either be left out, or refer to a field name or expected value.

To me this feels very intuitive, but I would like you hear your feedback: is this a good, useful API, or should I backpedal to more straighforward implementation?

For the record: this library will also provide a more conventional, non-fluent API based on configuration objects.

Body:
In addition to Quentin Pradet's very good points, I am doubtful of the alleged benefits of this language.

Presumably the point of a grammar close to natural language is to make it accessible.  But SQL already is quite close to natural language.  Is one of these really closer to English than the other?

find("user").where("name").equals("foo")

select user from table where name = 'foo'

I don't really see the benefit of your grammar, from a standpoint of intuitiveness or readability.  In fact, the SQL version looks more readable (and is easier to type) because of its whitespace.


答:
There are a number of bad less than ideal design decisions that appear to have been made in considering this API.

The first is the question of utility - what purpose does it serve?  This appears to be creating a data structure that will compile into a dialect of SQL.  Incidentally, the grammar appears to be a limited set of SQL.  The question of "what advantage does this serve over just using SQL?" becomes key.  If it is more cumbersome to write using the fluent interface than just writing a string with the appropriate interpolation in it then one won't write using this API.

English is ambiguous.  Attempting to model a fluent interface on English is a poor choice (you are better off using Latin).  When there are multiple possibly valid parsings of the same set of chain of calls, this leads to confusion and surprise. Neither of these are good things to have in an API.

There are more parts to SQL than this API is exposing.  Joins (in any of their myriad forms) are notably absent form the example set.  Subqueries (foo in (select id from bar)), unions, and group by are a few of the things that are often used.  Complex groupings of logic do not appear to be present in any intuitive way.

If one was writing using this API and then found that the API is not capable of expressing the desired query, significant time will be lost.  It is a poor choice to be using mixed styles for doing a queries in an application (simple queries in this api, complex in raw sql) - and ultimately the one that is more expressive will be used.

While programming is widespread, English fluency is not.  Even with a limitation of the language to "SQL like" there are nuances of how a native speaker would read something and someone who has English as a second or third language.

There is unnecessary redundancy in the API for the sake of English.  In particular equal() vs equals() doing the same thing.  While I am not certain of it, I believe that is() is a no-op added for sake of a matching English closer.  I welcome any to listen to my ranting about redundancy of methods in ruby in chat - don't make the same mistake.

Sit down and write out a comprehensive example set of the queries you want to be able to use.  Determine who you will handle all of those examples in a non-ambiguous way that is less cumbersome than the queries themselves.  If you can't, consider if it is worthwhile to go down the path of writing the API.  SQL is where it is today (it isn't perfect, but I haven't found anything better) over decades of refinement.

RFC 1925 - The Twelve Networking Truths

(12) In protocol design, perfection has been reached not when there is
  nothing left to add, but when there is nothing left to take away.


问:
Methods to share memory or state across JVMs?
This is long question I know.  I have a few options for what I want.  I don't want to know "this is obviously the best," but maybe any pros or cons I may be missing about the options, as well as any options I'm unaware of.

We have a java application seperately run as multuple daemons, each a seperate JVM.  Right now SQL is used to store data and effecticvely our 'shared memory', but luckily not much is dynamic once in memory.

We will soon be dynamically creating and destroying connections and that will mean dynamic changes happening semi-fast and need something better then a SQL database.  We think all the dynamic stuff will happen in only one daemon, but we aren't certain.

We will need a faster method of saving and loading this state data, going to disk each time is just too slow.  The current database needs an overhaul for this change anyways, so we're open to modification or tossing of it as well.  We can re-learn all the state we keep in memory; but it's a slow process.  Persisting some or all of the data to a DB between runs to save time learning state at bootup is nice, if we can be certain it gets persisted right.

Ability to easily query a 'database' to see current state for debugging is a major plus.

The solutions I have considered, and some of the pros & cons are:

1) some sort of hibernate solution combined with an in-memory sql database.  I haven't used hibernate yet (really want to!), but I think it can address persistance and avoid stale objects between JVM's for us and sql will still be close to the speed of other options if in memory?  I don't know how much the overhead for this is or how it scales to multuple JVM's and possible (semi?) fast changes to data.  Presumable this is slower then all the other options, but think it's fast enough for our needs?

2) Have each JVM store it's own internal state without any shared system.  Use reliable intercommunication (probably JVM) to try to keep state consistent.  Most important state is in one daemon, so there won't be that much sharing of dynamic state, but still need to address inconsistent state and dataraces when it does occure.  I'm uncertain of how we would want to record persistant state to allow fast reboot even if daemon dies unexpectedly.  Also, this solution would require implementing some quick messages to allow fetching a description of memory state to help debugging.  It would offer the highest performance once we get it right, but probably the most time consuming to implement (I anticipate obscure bugs due to data-race and inconsistent data?).

3) Use a system to allow some shared memory between JVMs.  Quick research suggested MappedByteBuffer and Ecache as possible options, there could be more.  Only looked into this a little so far so don't fully know pro's and cons yet.  Slightly afraid of creating a single point of failure if our memory is all shared.

4) Some sort of alternative I don't know about or possible merging of two of these idea.

答: Have you looked at the Hazelcast technology?  We're using it internally with vert.x - goes without a hitch (for now).</p>


答:
One other thing: A "terms of service document prepared by lawyers" is not good enough. Write plain language and state your service (and limitations of it) clearly in advance and in no more than 5 lines.

Plain and clear language come first. Legalese is totally unimportant in developing good customer relations.


答:
What you can do:

Be willing to weedout bad clients.The customer is always right, but in my interpretation, if they don't want to pay for services or they believe they've paid for services at a price I'm not willing to provide, you're no longer my customer. This could be a mutual agreement, maybe not. There is another old saying about getting what you paid for. If you stay at a cheap hotel expect cheap service. If I stay at a five star hotel and want a peanut butter sandwich at 4 O'clock in the morning and they run out, someone better run down to the corner store and pick up a jar and it's not going to be me. That's the expectation and the fact you paid a lot of money supports that agreement and justifies their rating.

Manage Expectations with warnings. Website outages never happen at a good time. Most people would prefer scheduled maintenance, so they can plan around it. If you're not doing that, you should. Send an email. Post it on your site when they log in. Keep people informed. Taking the site down because you're trying to manage the added growth could be interpreted as a positive sign that you'll be around.

The success of Facebook wasn't the idea for a social networking site (It wasn't the first.) it was the ability to manage the technical requirements of adding millions of users and keeping up with the volume without crashing like all the other sites. It is nearly impossible to do, but they've separated themselves very successfully.


答:
One nice way to implement this is to encapsulate your moves in the form of Command objects. Think of a Command interface that has the methods move(Position newPosition) and undo. A concrete class may implement this interface such that for the move method, it can store the current position on the board (Position being a class holding the row and column values probably), and then make a movement to the row and column identified by newPosition. After this, the method will add the command (this) to a global stack of Command objects.

Now, when the user needs to roll back to the previous step, just pop the last Command instance from the stack, and call its undo method. This also provides you with the ability to roll-back to as many steps as you need.

Hope that helps.


答: The easiest and most stable method would probably to use an in-memory database (SQL or not). I'm not sure what your data structure looks like, but a relatively competent DBA (or someone with a bit of Google Fu) should be able to configure the system to store the relevant tables in memory, assuming they fit.</p>

Title: Methods to share memory or state across JVMs?

Body:
This is long question I know.  I have a few options for what I want.  I don't want to know "this is obviously the best," but maybe any pros or cons I may be missing about the options, as well as any options I'm unaware of.

We have a java application seperately run as multuple daemons, each a seperate JVM.  Right now SQL is used to store data and effecticvely our 'shared memory', but luckily not much is dynamic once in memory.

We will soon be dynamically creating and destroying connections and that will mean dynamic changes happening semi-fast and need something better then a SQL database.  We think all the dynamic stuff will happen in only one daemon, but we aren't certain.

We will need a faster method of saving and loading this state data, going to disk each time is just too slow.  The current database needs an overhaul for this change anyways, so we're open to modification or tossing of it as well.  We can re-learn all the state we keep in memory; but it's a slow process.  Persisting some or all of the data to a DB between runs to save time learning state at bootup is nice, if we can be certain it gets persisted right.

Ability to easily query a 'database' to see current state for debugging is a major plus.

The solutions I have considered, and some of the pros & cons are:

1) some sort of hibernate solution combined with an in-memory sql database.  I haven't used hibernate yet (really want to!), but I think it can address persistance and avoid stale objects between JVM's for us and sql will still be close to the speed of other options if in memory?  I don't know how much the overhead for this is or how it scales to multuple JVM's and possible (semi?) fast changes to data.  Presumable this is slower then all the other options, but think it's fast enough for our needs?

2) Have each JVM store it's own internal state without any shared system.  Use reliable intercommunication (probably JVM) to try to keep state consistent.  Most important state is in one daemon, so there won't be that much sharing of dynamic state, but still need to address inconsistent state and dataraces when it does occure.  I'm uncertain of how we would want to record persistant state to allow fast reboot even if daemon dies unexpectedly.  Also, this solution would require implementing some quick messages to allow fetching a description of memory state to help debugging.  It would offer the highest performance once we get it right, but probably the most time consuming to implement (I anticipate obscure bugs due to data-race and inconsistent data?).

3) Use a system to allow some shared memory between JVMs.  Quick research suggested MappedByteBuffer and Ecache as possible options, there could be more.  Only looked into this a little so far so don't fully know pro's and cons yet.  Slightly afraid of creating a single point of failure if our memory is all shared.

4) Some sort of alternative I don't know about or possible merging of two of these idea.


答:
I tend to somewhat agree with others' posts that this is not a great design.  However, I believe I have different reasons.

You're presenting what I view as a concrete syntax for SQL queries.  I strongly believe that concrete syntax can never help a language, only hurt if it is bad.

However, abstract syntax is a different story.  Abstract syntax defines the structure of your language and how phrases may be combined to build bigger phrases.  I feel that the success of a language strongly depends on the quality of its abstract syntax definition.

My problem with the fluent API isn't that it's ambiguous, or unclear, or not expressive -- it's that it hides the real language and its structure, and in so doing, ends up making things much more complicated than they have to be (by introducing ambiguities, non-obvious syntax errors, etc.).

Since you mentioned that you'll also provide a "more conventional API", it sounds like you already know all this.  To that I say "Good!"  But that doesn't mean that you can't also develop your fluent API in parallel!  A single abstract syntax definition can support multiple concrete syntaxes.  While you should keep in mind that the abstract syntax is the real deal, a concrete syntax can also be very helpful.


答:
How much data are you saving/retrieving? Is it simply configuration information, or do you want to store business data?

If the latter, then the only thing that makes sense is an on-disk database. Unless you're OK with losing all of your data due to a system crash, and don't mind dirty reads. And I wouldn't rule out SQL-Server based on performance until you've actually tested it.

If all you want to do is share a (relatively small amount of) configuration data, then take a look at Apache Zookeeper: http://zookeeper.apache.org/


答:
EDIT: Before, I said POST helps protect you against CSRF but this is wrong. I did not think this through correctly. You must require a session-scope unique hidden token in all your requests to change data to protect against CSRF.

In the early days of the internet there were browser accelerators. These programs would start clicking links on a page to cache the content. Google Web Accelerator was one of these programs. This could wreak havoc on an application that makes changes when a link is clicked. I would make the assumption that there are still people using accelerator software.

Proxy servers and browsers will cache GET requests so when the user accesses the page again it may not send the request to your application so the user thinks they took an action, but they really didn't.

Title: Why shouldn't a GET request change data on the server?

Body:
All over the internet, I see the following advice:

A GET should never change data on the server- use a POST request for that

What is the basis for this idea?

If I make a php service which inserts data in the database, and pass it parameters in the GET query string, why is that wrong? (I am using prepared statements, to take care of SQL Injection). Is a POST request in some way more secure?

Or is there some historic reason for this? If so how valid is this advice today?


问:
Design Pattern For Util Classes and General Static Variables
I am developing a Mojo(think it as just a usual class) for my custom Maven Plugin. There is an Abstract Mojo at top. I have some other custom Mojos in example which makes server side includes. I have some static variables and some util methods in example get operating system name, fix file separator in order to used operating system etc. I have created an abstract Base Mojo that extends Abstract Mojo and put every common things inside it. When I create a Mojo (i.e. server side includer) I extend it from my Base Mojo. However should I think that I should separate variables and util methods or not and what kind of pattern I should follow.

To make it clear there is:

AbstractMojo at top by default (I can not change it)

BaseMojo an abstract class that extends AbstractMojo that has util methods and static system variables

CustomMojo extends BaseMojo and does its responsibility.

Any ideas how to implement a design for my needs?

答: The pattern depends on what the Mojo classes are doing. The util methods should be moved to a helper or utility class or encapsulated within the class that uses them. Unless BaseMojo is providing common implementations for a behavior which may be over ridden in Custom Mojos, it is not required. </p>

OwnerDisplayName: kamaci


问:
What can I do to maintain respect for a poorly written codebase?
In my job I have to maintain a poorly written codebase which is both hard to understand, has tons of comments that are just plain wrong, has a bunch of weird decisionmaking going on in it and a whole lot more.

I primarily do bugfixing which ranges from finding that little comment somewhere in the code that makes some random part not work, to understanding complex circular dependencies with some kind of singleton'a'palooza going on, and occasionally I actually get to write some real code, which is when I'm the happiest. But I'm concerned about the bugfixing witch I must confess many times ends up in being sloppy patchwork because I don't have the time or the mental fortitude to look at the horrendous code anymore.

Now the biggest problem this project has is not that I'm just a whiny guy, I'm most certainly not alone in having above mentioned sentiments about the codebase. The biggest problem is probably the cost of maintaining it... But I digress.

What I'm wondering is if there is some practices that I and my colleagues can try use to regain some respect for the codebase we've inherited and are working so that we don't walk down the path of creating more code rot?

答:
Sometimes you have to understand these things in the context they were concieved in, then built in, then maintained in.

Some of the worse offenders that I have seen probably started out as very nicely written programs. You can see a bit of well-thought out architecture trying to poke out through the mess. But as it happens, the requirements change during the end of the initial build, so some things get a little sloppy, to ensure deadlines are met, etc... Then the initial team of contractors hands it off to the internal dev team that have a different way of doing things. That team might have a dozen people, and with one or two members turning over per year, and with different people changing their focus on the system, it's easy to understand how quickly and easily a nice code base can become an abomination. By the time I came on to it, it was full of all kinds of "WTF"'s and eccentricities. Some of them made no sense, some were clear anti-patterns, some were to fix platform-specific issues with a specific vendor component that may or may not still have issues in their current versions (but no one's had the time to test and the current code just works so no one wants to mess with it).

At least that's how the horrible legacy codebases I've worked on evolved. Of course there were probably many things that could have been done at many of these cycles to mitigate the WTF-factor, but if that had happened then I'd have nothing to write about. ;)

As for working with it: I used to think of my job on one of those systems as a precision-strike fighter plane: fly in quick and fast through hostile terrain and deliver that one small line of code that blows the bug to pieces. Sometimes it was more fun to think of the longer, more involved big-fixes process as a Sherlock Holmes mystery: The Case of the Garbled Queue Message (or something like that).


答:
There is no need to use an external service, you can use sockets.

At least if you have one-to-one communications, if there are many listeners for certain events, a pub-sub solution, like @Shauna recommended, might be better.

for an overview on sockets and their use in python see the docs

Title: What is the preferred way of communicating between applications on the same system?

Body:
I'm designing a system that is built on several small applications written in python, some of these will be services and others will be programs that only run during special situations. What I need to achieve is to let the server communicate to a service when a certain event occurs with some small amount of data. So that the service knows about the new situation and can take the appropriate action, sometimes immediately and sometimes in the future.

I've been looking at memcached, but it seems like an overkill solution for my system (which is just a few separate applications running on a raspberry pi), or writing to files and using something like pyinotify but I don't think that is very elegant and finally I've been thinking about storing state in a database which I also don't like very much.

Are there any preferred ways to handle this sort of communication between processes that I haven't thought of(I'm sure there is) or which of the above mentioned ones would be the smartest to go with?


答:
I work for a company that also provides data as a service. So I feel your pain. We have decided that keeping customers for the long term is more important and thus we decided to give refunds (so in the long term we keep them paying a monthly fee).

The only way to stop the complaints is to start providing refunds.

Do it such a way that you detail exactly how much you will refund (explicitly how it is calculated) and under what conditions the refunds kick in. Differentiate planned vs unplanned outages. This can be very strict just document it. Make the calculations done in such a way that it will be unlikely that you refund much (this is not unreasonable either) and the max you refund is one payment (assuming customers pay monthly).

Customers will vote with their feet and stop paying if the don't like the service.

Put on the home page down-time in the last 12 months and expected down time in the future (given past experiences). On the front page put a link to a page that details all down times and explain why the service was down. just be open and honest.

You have to remind people that downtime for a service is expected and document the conditions under which you expect to fail.


答:
Maybe there is no pride in the code, but you did not write it. What you can acknowledge yourself for is making the user experience better by removing the bugs. Not glorious, but the users will love you for it.

Also, you leave the code a little better for the next guy.

Title: What can I do to maintain respect for a poorly written codebase?

Body:
In my job I have to maintain a poorly written codebase which is both hard to understand, has tons of comments that are just plain wrong, has a bunch of weird decisionmaking going on in it and a whole lot more.

I primarily do bugfixing which ranges from finding that little comment somewhere in the code that makes some random part not work, to understanding complex circular dependencies with some kind of singleton'a'palooza going on, and occasionally I actually get to write some real code, which is when I'm the happiest. But I'm concerned about the bugfixing witch I must confess many times ends up in being sloppy patchwork because I don't have the time or the mental fortitude to look at the horrendous code anymore.

Now the biggest problem this project has is not that I'm just a whiny guy, I'm most certainly not alone in having above mentioned sentiments about the codebase. The biggest problem is probably the cost of maintaining it... But I digress.

What I'm wondering is if there is some practices that I and my colleagues can try use to regain some respect for the codebase we've inherited and are working so that we don't walk down the path of creating more code rot?


问:
Turning n-dim points into m-dim where m<n and where point-to-point distance deviation is minimized
I want to apply k-means clustering to a (sparse) adjacency graph. For this I need to assign the nodes to a position in an euclidean space. Trivially I can do this by having a space with as many dimensions as there are nodes where each component corresponds to another node.

Now, in order to make the clustering a bit more understandable, or maybe just different, I'm thinking about whether there are ways of "folding" the n-dimensional space of points into a more manageable space, perhaps 3-dim or maybe just m-dim where m < n. While doing this I want to maintain distance relations between nodes - so I want to minimize the deviation between the straight line distance between any two points before the fold compared to after the fold, or in other words, the sum of all deviations.

So I can't seem to find any to-the-point info on this when looking. Perhaps I'm missing terminology. What good/efficient methods are there for this? Algorithms? It seems like a somewhat archetypical optimization/mean square minimization problem.

A simple base case:

```<code>P1 = (1,1,1)
P2 = (1,1,0)
p3 = (1,0,1)
newPoints = spacefold(2,[P1,P2,P3])

// example output:
// newPoints = [(1,1),
//              (1,0),
//              (0,1)]
</code>```

For this example they happened to be conveniently placed in a plane - removing the x component gives an optimal solution.

答: Multidimensional scaling is probably what you're looking for. It takes as input a distance matrix and assigns to each object a vector of the target dimension.</p>


答:
Well, you're directing a lot of energy toward an inanimate object.  I actually deal with it by relishing in the challenge, in the contest itself.  It's the same way you face an opponent on the sports field.  You want to win.  They are an obstacle to you winning, but you don't hate them for it.

The next thing I do is a refactoring step first, while I'm still trying to understand the code.  If my change needs to go in a 1000 line function, I break up that function.  If there's boilerplate code repeated all over the place, I pull it out into its own function.  I replace magic numbers with named constants.  I'm not talking major rework that requires a deep understanding of the code, just simple transforms that can be almost mechanically applied.

At that point, I'm ready to make my change, and it's a lot easier to do so, usually more than making up for the time I spent refactoring.  Some of my best work ends up with a net loss in number of lines of code, even when I've added new features.  When I'm facing an uphill battle, I try to remember how good that will feel when I finish.


答:
Having worked with some truly horrid C# at my first job, I've ran headlong into this problem.  While I wound up leaving, in the time I spent with it I took the mindset of treating the code as a patient.

All code, no matter how awful, WTF-ridden, poorly-conceived, inadequately-implemented, or just plain bad was intended by its developers to solve a problem, with the tools they had at their disposal.  Does that make the code good?  Nope.  Does that makes maintaining it less painful?  Assuredly not.  Of course, your question isn't about the developer pain; its about whether you can look at this code day-in and day-out for however long you remain employed at your current shop.

To that end, when working with code, I view it as a doctor might: an entity that is exhibiting symptoms of a particular trait.

We call symptoms of intended behaviors 'correct behavior' most of the time...except for when the reasoning behind the behavior being 'intended' is bad.  When this circumstance occurs, it might be helpful to pull together something that you can present to your management to explain the behavior you're seeing, and an optimal process that would improve how the app works, and finally the minimal changeset to modify those symptoms.  If all goes well, they'll approve and let you do what a developer does best: leave code in better condition than you find it.  If not?  It might not be so bad, they might just have a business reason (too little time, too little money).

When I encounter symptoms of an unintended behavior, I prefer to follow whatever bug-reporting workflow is in place in my shop; it's the quickest, most efficient way to inform your leaders of the problems besetting your app.  In my first job, there were some issues we didn't get to address for about two months due to the nature of the industry we were operating in, but not reporting it (or worse, making rogue changes) would have had far worse side-effects, which leads to still-lower respect for your code base.

Better still, try to find constructive ways to get your managers to speed up the process by which bugs are responded to (this was a problem at that first shop of mine), because the longer you know a bug is in the wild, the less your respect for the code will be at the end of the day.  Morale matters!

When I see malformed code that dosen't match standards for the language, I don't blame the code for being malformed, but I do consider the developer who wrote it; maybe they're not familiar with the language?  (I encountered this case with a coworker who had zero programming experience, but a rich history as a manual tester; this person wrote some truly horrid copy/paste code that it took me weeks to stabilize.)

When you encounter this case, you have two options.  If the developer is there and in easy access, make yourself available as a teaching resource; you can influence this person to write code to the standards of your language and your shop.  Help them be a better developer, chances are they're having a difficult time, but are putting on a tough face and grimacing through it just like you.  Better still, you can sleep easier at night knowing that the volumes of poor code will be decreasing over time, which is always welcome.

If the person isn't in easy access, or has already left, when an excuse to revise the code appears in a positive, low-risk fashion, take it.  You're doing your organization a favor by being the change you want to create.

If in a few weeks you've tried all of this and still seen no improvements to your own consideration of your codebase, and to others' treatment of it, there's nothing for it: you shouldn't support something you hate, as you'll do it sub-par as to make all the symptoms I've just talked about worse.  But, before you start chatting up that recruiter, make absolutely sure you've exhausted every option to improve that codebase, and to get your coworkers to do the same.  I would imagine if you're cringing in this much pain, this can't be pleasurable to them, either!