问:
Restrictions Calling DLLs Across Technologies?
I want to call a DLL in my programming language of 'choice'. The documentation surrounding this clearly states that it must be a 32-bit DLL written in C, C++ or Delphi. But I wanted to call a DLL written in C#. It goes on to mention that the default calling mode is cdecl.

So my question is: why would this be the case? Is there any way to make it think a C# DLL was written in C, C++ or Delphi?

答:
That very problem is what COM was designed to address. I'll leave it to my good friend Jeremiah Morrill to explain what the problem is:

I explained briefly how simple exporting regular “C” methods can be to
  share code between DLLs and the application.  I also explained how C++
  classes get flattened and compiled down and also how they are seen to
  your CPU (more or less).  If C++ classes just get compiled to static
  “C” methods, which can be exported from our DLL, is that not
  sufficient to reuse and share classes across DLLs?  Yes…but not
  without some major caveats as this would come at a cost.

The first disadvantage of exporting a C++ class is you must use the same C runtime in all DLLs/exe involved.  So if one DLL used MSVCRT7,
  the caller of the DLL must be using MSVCRT7.  The reason is different
  versions of C runtimes manage the heap differently, so if DLL A tried
  to free resources allocated by DLL B, memory corruption can occur.

The second disadvantage is the same compiler version must be used.  This is because different compilers mangle names differently.  Name
  mangling differences among compilers ensures a DLL built with
  Microsoft would have completely different symbol names than a DLL
  built with GCC.  So when linking of your code occurs, the linker might
  be looking for “??4MyWidget…” when the export is really
  “MyWidget__Fi…”

Third, if a large change of the base classes in DLL A are made, even without breaking API, then DLL B that uses the base classes must
  be recompiled.

Forth [sic], if you take the last three disadvantages into consideration, we have a very tight coupling between our DLLs.  This
  inhibits reusability of the module.

Sometimes these issues are not an issue for a given project.  This is
  usually acceptable when the project is small, or an in house utility.
  That’s totally fine.  But let’s pretend Microsoft ignored these
  problems.  All developers would have to use the same compiler version.
  Applications would have to be written for very specific versions of
  Windows.  This would be a complete nightmare for everyone.

Looking at those problems, COM is a simple solution for solving them. By exposing your C# dll to COM, you can call it from any other COM compliant language.


问:
Visiting points on a number line while minimizing a cost not related to distance
I need some help on this ACM ICPC problem. My current idea is to model this as a shortest path problem, which is described under the problem statement.

Problem

There are N = 1000 nuclear waste containers located along a 1-D number line at distinct positions from -500,000 to 500,000, except x=0. A person is tasked with collecting all the waste bins. Each second that a waste container isn't collected, it emits 1 unit of radiation. The person starts at x = 0 and can move 1 unit every second, and collecting the waste takes a negligible amount of time. We want to find the minimum amount of radiation released while collecting all of the containers.

Sample Input:

4 Containers located at [-12, -2, 3, 7].

The best order to collect these containers is [-2, 3, 7, -12], for a minimum emitting of 50 units. Explanation: the person goes to -2 in 2 seconds and during that time 2 units of radiation are emitted. He then goes to 3 (distance: 5) so that barrel has released 2 + 5 = 7 units of radiation. He takes 4 more seconds to get to x = 7 where that barrel has emitted 2 + 5 + 4 = 11 units. He takes 19 seconds to get to x = -12 where that barrel has emitted 2 + 5 + 4 + 19 = 30 units. 2 + 7 + 11 + 30 = 50, which is the answer.

Notes

There is an obvious O(N!) solution. However, I've explored greedy methods such as moving to the closest one, or moving to the closest cluster but those haven't worked.

I've thought about this problem for quite a while, and have kind of modeled it as a graph search problem:

We insert 0 in as a baseline position (This will be the initial state)

Then, we sort the positions from least to greatest.

We then do a BFS/PFS, where the state consists of

Two integers l and r that represent a contiguous range in the sorted position array that we have visited already

An integer loc that tells us whether we're on the left or right endpoint of the range

An integer time that tells us the elapsed time

An integer 'cost' that tells us the total cost so far (based on nodes we've visited)

From each state we can move to [l - 1, r] and [l, r + 1], tweaking the other 3 integers accordingly

Final state is [0, N], checking both ending positions.

However, it seems that [L, R, loc] does not uniquely define a state, and we have to store L, R, loc, and time, while minimizing cost at each of these. This leads to an exponential algorithm, which is still way too slow for any good.

Can anyone help me expand on my idea or push my into the right direction?

Edit: Maybe this can be modeled as a dynamic programming optimization problem? Thinking about it, it has the same issues as the graph search solution - just because the current cost is low doesn't mean it is the optimal answer for that sub problem, since the time also affects the answer greatly.

Greedy doesn't work: I have a greedy selection algorithm that estimates the cost of moving to a certain place (e.g. if we move right, we double the distances to the left barrels and such).

Could you do a Priority-first search, with a heuristic? The heuristic could combine the cost of the current trip with the amount of time elapsed.

答:
I have a solution that will solve this problem in 2^N time, which is poor, but I think it is a helpful way of framing the problem, so I thought I would post.

Rather than model the problem as a graph, I would model it is a binary decision tree (say T). At each level you have to choose between going right or left. It is fairly easy to calculate the 'cost' of each edge. Let h(K) be the height of the current node, K, then the cost of the edge going to left_child(K) = h(K) x dist(K, left_child(K)).  A similar calculation suffices for the cost of the edge to the right child. You construct this tree, and keep track of the cummulative cost of edges all the way down, and report the path to the leaf node with the smallest total cost.

Note that the cost calculation works because the length of each edge dist(K, left_child(K)) represents the time to go to the next site, while the height of the subtree is the number of sites remaining (eg. still emitting radiation).

Now the trick within this framework is to determine if there are some heuristics you can use to 'prove' that you can ignore expanding the search along some branch.  My intuition is that for any such heuristic there is an arrangement of sites that will defeat it, but perhaps someone can come up with something.

A number have proposed applying shortest path solutions for graphs, I have some doubts over whether such a solution can work. Your neighbours in the 'graph' in the problem will change depending on the path you follow. For example in your original post with [-12, -2, 3, 7] if you go to -2 then -12 and 3 become 'neighbours' and if you go to 3 then -2 and 7 are neighbours. Every possible 'pair' of positive and negative values can potentially be neigbhours in the final graph.  I don't know of any shortest path algorithms that are provably correct in an dynamic graph.

ContentLicense: CC BY-SA 3.0


问:
Error handling - Should a program fail on errors or silently ignore them
I'm writing a simple little program to transmit MIDI over a network. I know that the program will encounter transmission problems and / or other exception situations that I won't be able to predict.

For the exception handling, I see two approaches.  Should I write the program so that it:

fails with a bang when something goes wrong
or

should it just ignore the error and
continue, at the expense of data integrity?

Which approach would a user reasonably expect?

Is there a better way of handling exceptions?

Additionally, should my decision about handling exceptions be affected by whether or not I am dealing with a network connection (ie. something where I can reasonably expect to have problems come up)?

答:
There are other options between "blow up" and "ignore."

If the error is predictable and avoidable, change your design or refactor your code to avoid it.

If the error is predictable but not avoidable, but you know what to do when it happens, then catch the error and handle the situation. But be careful to avoid using exceptions as flow control. And you may want to log a warning at this point, and maybe notify the user if there's some action they might take to avoid this situation in the future.

If the error is predictable, unavoidable, and when it happens there's nothing you can do that will guarantee data integrity, then you need to log the error and fall back to a safe state (which, as others have said, may mean crashing).

If the error is not something you've anticipated, then you really can't be sure that you can even fall back to a safe state, so it may be best to just log and crash.

As a general rule, don't catch any exception you can't do anything about, unless you just plan to log and rethrow it. And in the rare cases where a try-catch-ignore is unavoidable, at least add a comment in your catch block to explain why.

See Eric Lippert's excellent exception-handling article for more suggestions on categorizing and handling exceptions.

ContentLicense: CC BY-SA 4.0


问:
How to implement lazy evaluation of if()
I am currently implementing an expression evaluator (single line expressions, like formulas) based on the following:

the entered expression is tokenized to separate literal booleans, integers, decimals, strings, functions, identifiers (variables)

I implemented the Shunting-yard algorithm (lightly modified to handle functions with variable number of arguments) to get rid of parenthesis and order the operators with a decent precedence in a postfixed order

my shunting-yard simply produces a (simulated) queue of tokens (by means of an array, my Powerbuilder Classic language can define objects, but only have dynamic arrays as native storage - not true list, no dictionary) that I evaluate sequentially with a simple stack machine

My evaluator is working nicely, but I am still missing an if() and I am wondering how to proceed.

With my shunting-yard postfixed and stack based evaluation, if I add if() as another function with a true and false parts, a single if(true, msgbox("ok"), msgbox("not ok")) will show both messages while I would like to show only one. This is because when I need to evaluate a function, all of its arguments has already been evaluated and placed on the stack.

Could you give me some way to implement if() in a lazy way?

I though about processing these as a kind of macro, but at early time I have not yet the condition evaluation. Perhaps that I need to use an other kind of structure than a queue to keep separately the condition and the true / false expressions? For now the expression is parsed before evaluation, but I also plan to store the intermediate representation as kind of precompiled expression for future evaluation.

Edit: after some though on the problem, I think I could build a tree representation of my expression (an AST instead of a linear token stream), from which I could easily ignore one or another branch of my if().

答:
It is quite easy, if you compile everything lazily. You must have some means to see if a value is already evaluated, or if it needs more evlauation.

Then you can do the following: If it is a literal or variable (do you have those?, i.e. names of functions?), push it on  the stack. If it is an application of a function, compile it separately, and push the entry point on the stack.

Execution of a program is, then, merely looping until the top of the stack is evaluated and not a function. If it is not evaluated or a function, call the code the top of the stack points to.


问:
Why does Go have a special case for abs(0)
I was playing around with Go, and found this particular interesting code for the abs function in the math package:

http://golang.org/src/pkg/math/abs.go

```<code>14 func abs(x float64) float64 {
15      switch {
16      case x < 0:
17          return -x
18      case x == 0:
19          return 0 // return correctly abs(-0)
20      }
21      return x
22  }
</code>```

Why do we need to have the special case of x == 0? What will happen if I delete line 18 and 19?

答:
The comment explains the reason - abs(-0) should return 0, but without the special case, abs(-0) would return -0.

I assume Go uses IEEE floats so both +0 and -0 can be represented using different values for the sign bit.


问:
Fixing a push to the wrong branch
I committed and pushed some changes to the wrong branch. I found a way to fix it, but it seems overly complicated. Is this really the easiest way?

on the branch that you made your changes, type hg parent

run hg diff -r <parent> -r <with_changes> > patch.diff

hg up <proper_branch>

hg import --no-commit patch.diff

hg ci -m 'committing changes to proper branch'

hg up <bad_branch>

hg parent to find previous changeset on this branch that is good

hg ci --close-branch -m 'closing bad branch'

hg up <last_good_changeset>

add a space or other minor change

hg ci -m 'making tip'

hg push

Something to that effect anyway. I did it in a slightly different order; I made the good changeset the tip again, and had to do a force commit because it creates a new head, then had to run

```<code>hg heads `hg branch`
</code>```

To find the bad branch again, then close it. Now it still shows the bad changeset as the "tip" because I closed it after I "re-tipped" the good branch, but when updating to that branch, I guess it takes the most recent non-closed head?

Seems like quite a ridiculous process to fix such a simple mistake.

Is there any easier way to do this? Why not?

答:
I did find a cleaner solution. You don't need to "touch" the branch to bring it back to tip, nor close off the bad branch.

Instead, just up to the bad branch, hg revert -r <last_good_commit> -a then recommit.

Since you're upping to the tip of the bad branch it doesn't create a new head, and then your reverted changes get pushed to the tip instead.

Title: Fixing a push to the wrong branch


答: The IEEE 754 floating-point standard allows signed zeros. A negative zero is equal to a positive zero, so it wouldn't be covered by the < 0 test.

Title: Why does Go have a special case for abs(0)

Body:
I was playing around with Go, and found this particular interesting code for the abs function in the math package:

http://golang.org/src/pkg/math/abs.go

```<code>14 func abs(x float64) float64 {
15      switch {
16      case x < 0:
17          return -x
18      case x == 0:
19          return 0 // return correctly abs(-0)
20      }
21      return x
22  }
</code>```

Why do we need to have the special case of x == 0? What will happen if I delete line 18 and 19?


问:
Test planning for an Agile sprint
Can anyone offer any tips or experience on developing a test plan for an Agile sprint? Most of the time our team simply creates a "Test Feature X" task and goes about writing ad-hoc test cases. There typically isn't much strategic forethought put into how features will be tested and how we'll communicate the expectations and results to the rest of the development team and our users.

Is it common to just write high-level testing tasks without making the actual test cases transparent to the development team? What sort of methodologies have you used when developing a test plan and what does it look like both at the beginning of a sprint and at the end? Any advice or tips on what comprises an effective and transparent test plan as well as a means of developing the test plan would be much appreciated.

答:
I've found that session based testing and test automation really do shine in these kinds of cases.  I'll normally start off with some high level scenarios that the stakeholders find important.  From there, I start writing session charters for things that I want to test, with a little bit more detail.  When I execute the session, that's when detail starts going in, recorded in the session notes.

Having test automation can also help. Even more so when using something like cucumber.  Myself, using SpecFlow, I'm able to create the test in a way that my stakeholders can understand what the test is doing, and they have a high level summary of what actually passed/failed.

Although I'm not a fan of giant test plans, I understand that it's occasionally required.  Instead of putting test cases into your test plan, put the session charters and test automation into it instead.  Remember, it is a living document, and will change and evolve as testing continues.  At the same time however, your test plan should probably be for your application/project, and not necessarily for each individual sprint.

Title: Test planning for an Agile sprint


问:
Handling recurring cURL POST request
I've basically came here for some advise based on my criteria,

The application I'm trying to build is built completely from an API. It's like a "marketplace bidding" application, what I'm trying to accomplish is an "Auto bidding" function, but for this to happen it will have to send a cURL POST request every 3 seconds based on criteria given, then return the JSON result for me to handle server side,

I'd basically like a direction on what would be the best way to handle this kind of idea, I got told something called "polling" would work but I've never heard of it. Initially the idea is as provided below

Load set page "bid.php"

Enter certain criteria

Click submit as to which an "Ajax" request of some sort would start

The recurring cURL request would be activated through the Ajax.

Display the data back from the cURL request every 3 seconds via Javascript.

I'm not initially asking for the work to be given to me, I'm just asking the professionals as to which they recon would be the best way I can do this task.

答:
You could have one page, let's call it auto_bid.php. This file could be a basic php file that receives a string through GET or POST, does a curl to wherever and receives the JSON response. You could process the response and generate your own response.

Your bid.php file could have the input box and button. When the user enters criteria and clicks the button, it would make a call to a javascript function that is set on a recursive 3 second timeout loop (settimeout() perhaps), and that function can use a javascript or jquery ajax call (jquery has a built in method) passing the string, to auto_bid.php.

The response from auto_bid.php that you set up could be a JSON string that you can have js handle and adjust the bid.php html to display "auto bidded $XX". Then it would attempt a bid again and display again. You could also have auto_bid.php respond with HTML instead, and when you receive it through your ajax call, just dump it into a DIV or something.

Title: Handling recurring cURL POST request


问:
How are Scala Traits implemented in the JVM?
I have been reading about traits in Scala. They are pretty amazing. I am curious how they extend a class without actually resulting in multiple inheritance. I know that the JVM doesn't support multiple inheritance, so I am wondering how these extensions work. Is the language just providing syntactic sugar for composition? Or is the code within a trait duplicated in each class that uses it?</p>

答:
As far as I remember, it's actually a combination of both plus a whole bunch of optimization tricks. It's a pretty tricky encoding, actually.

Your best bet is probably to just compile some simple examples and decompile the resulting .class files.


问:
Theory about software communications mixing up with other software causing an Apocalypse?
I can remember a very Very long time ago (pre Y2K) , reading an article by some "expert" that theorized that software communicating over the internet, especially video games could get mixed up with Military communications meaning that a user could inadvertently mobilize a B52 nuclear bomber with a click of his mouse on a video game.

This theory sounds ridiculous enough as it would be very unlikely that packets of data from different software going to different Hosts on different ports could get mixed up. PLus the recipient would have a hard time interpreting the data that may only be understandable by the application it was meant to be read by.

However I digress, does anyone know about this theory and if it had a name, and has anything like this happened in software.

Apologies if this seems like a Networking question but since its ultimately about Application data then I felt it would suit this Stack site.

Thanks

Any other info would be welcome on similar theories or ideas.

答:
This scenario of "nuclear apocalypse by inadvertence" would require some inordinate incompetence at some point. Namely, we can imagine a buggy router which mixes some packets together, and sends the wrong packet to the wrong destination. And then, inexplicably, the military system which receives the packet which, by a stroke of bad luck, contains what that system interprets as the coded order for "it's payback time, commies !" just goes ahead with it.

Normally (hopefully), command systems which can trigger the nuclear Ragnarok are supposed to resist wanton attacks from bad people with evil intentions. They use authentication and cryptography and dual control and many other things to prevent outsiders from launching missiles, even if they try real hard to craft packets which will mimic the normal launch packets. The scenario envisioned here is that a random bit flip in a router due to a cosmic ray just succeeded in mutating or redirecting an innocent game-related chunk of data into a one-way-ticket for fission inferno. In other words, the scenario assumes that all of the following hold true:

the security systems and failsafes on the controls for nuclear missiles are so awfully weak that a single misrouted packet is sufficient to trigger the launch;

none of the existing attackers, be they spies from other nations, nihilists who crave emptiness, or bored students who should know better, succeeded in doing a task so simple that a random bug achieved it (it's like being crushed at StarCraft, when your opponent is a cat who decided to take a nap on the keyboard; it is very embarrassing);

the nuclear strike force controls are connected to the Internet.

Any of these conditions requires a lot of people to be terrible at their own job, to a magnitude which is remarkable even if we consider that some of them are a public organization, and others are pre-pubescent geeks. The whole picture is then quite improbable.

It may happen, but a lot of improbable things are more plausible than that, and arguably worse, including the usual example of a ten-kilometer asteroid striking the Earth, something which has already happened in the past, will probably happen in the future, and totally dwarfs out our puny nuclear arsenals when it comes to destructive consequences. Such an event occurs on average about once every 40 millions of years, i.e. has probability 1 in 40 millions to occur every year. Anything which could happen with a lower probability is therefore negligible.

A generic name for such theories could be "misaligned danger assessment". It is worrying about the very improbable instead of the very probable. If you want to live longer, don't worry about nuclear missiles; instead, quite smoking, drink less alcohol, and eat more vegetables and less fat.


问:
Do You Still Need Indexing After Database Normalization
After you have done a good normalization, do you still need to index the table? How is this going to affect the performance? Will it even affect the performance in some way after a good normalization?

Which columns are usually indexed if you already have the primary key and the foreign key?

It's seems like it's already effective to normalize a database. But, I might have skipped how indexing affects the database. Is this only effective when queries are used? How does this work/perform and make a database better?

答:
Indexes are generally needed in all but the smallest tables. Pretty much every foreign key should  be indexed and just setting up an FK does not mean you have an index (at least not in some databases, check you db documentation). Fields you frequently join on or use in where clauses should be indexed if they are ones that would benefit (you need a certain amount of variablity in data so Booleans don't benefit for instance) and ones where it is possible to index.

However, every index slows down inserts\updates\deletes while speeding up selects, so choose your indexes carefully.

Indexes are critical to acceptable performance in a database.


答:
It wouldn't be a stretch for the military to hire a game development company to work on something for them. I doubt they would start from scratch, so there would be similar code whether they knew it or not.

The game could be designed to host its own shared game over the Internet and even reach out to other games. Of course they would exclude that feature from the military's. Maybe not.

Title: Theory about software communications mixing up with other software causing an Apocalypse?

Body:
I can remember a very Very long time ago (pre Y2K) , reading an article by some "expert" that theorized that software communicating over the internet, especially video games could get mixed up with Military communications meaning that a user could inadvertently mobilize a B52 nuclear bomber with a click of his mouse on a video game.

This theory sounds ridiculous enough as it would be very unlikely that packets of data from different software going to different Hosts on different ports could get mixed up. PLus the recipient would have a hard time interpreting the data that may only be understandable by the application it was meant to be read by.

However I digress, does anyone know about this theory and if it had a name, and has anything like this happened in software.

Apologies if this seems like a Networking question but since its ultimately about Application data then I felt it would suit this Stack site.

Thanks

Any other info would be welcome on similar theories or ideas.


问:
Scrum Master in the organization
I'm wondering how to set up the organization with Scrum Masters. I would prefer to see real examples of where the scrum masters are located in the organization's hierarchy and how report-to / chain-of-command issues are handled.

we are service company. We have one agile project done for agile customer where team manager of developers fulfills the role of delivery responsible. So far we had matrix organization where scrum masters were assigned to the project management team consisting of people working for other projects (not agile), but this was causing that they did not have much contact with agile culture in their PM team and goals were not always aligned with project.

How should we structure Scrum Masters within our organization?

答:
In our organization (80+ developer, 10 scrum teams), the scrum masters are part of the scrum teams. Scrum masters are responsible for only one team, and are also developer/QA in it's team.

Our scrum masters responsibility is an overall team responsibility, that is keep the team alignment in sync with overall Product Manager alignments. Scrum masters also work as a filter between the PM/outside world and developers, making sure the individual developers can focus on their day to day work, instead of being pestered with all kind of requests. They also have the responsibility of communicating what is going on in the team, and warn about possible delays.

This works fairly well for us, and the scrum masters are also kept free to do a lot of development work, meaning not to much noise towards them either. One of the reasons it works for us though, at least I believe, is that we have a culture where we trust the developers 100%, which means the scrum teams basically runs themselves without much work from PM.

Title: Scrum Master in the organization


问:
A good C Variable Length Array example
This question got rather a freezing reception at SO, so I decided to delete it there and try here instead. If you think it does not fit here either, please at least leave a comment on suggestion how to find an example I'm after...

Can you give an example, where using C99 VLAs offers a real advantage over something like current standard heap-using C++ RAII mechanisms?

The example I am after should:

Achieve an easily measurable (10% maybe) performance advantage over using heap.

Not have a good workaround, which would not need the whole array at all.

Actually benefit from using dynamic size, instead of fixed maximum size.

Be unlikely to cause stack overflow in normal use scenario.

Be strong enough to tempt a developer needing the performance to include a C99 source file in a C++ project.

Adding some clarification on the context: I mean VLA as meant by C99 and not included in standard C++: int array[n] where n is a variable. And I am after an example of use case where it trumps the alternatives offered by other standards (C90, C++11):

```<code>int array[MAXSIZE]; // C stack array with compile time constant size
int *array = calloc(n, sizeof int); // C heap array with manual free
int *array = new int[n]; // C++ heap array with manual delete
std::unique_ptr<int[]> array(new int[n]); // C++ heap array with RAII
std::vector<int> array(n); // STL container with preallocated size
</code>```

Some ideas:

Functions taking varargs, which naturally limits item count to something reasonable, yet is without any useful API-level upper limit.

Recursive functions, where wasted stack is undesirable

Many small allocations and releases, where heap overhead would be bad.

Handling multi-dimensional arrays (like arbitrarily sized matrices), where performance is critical, and small functions are expected to get inlined a lot.

From comment: concurrent algorithm, where heap allocation has synchronization overhead.

Wikipedia has an an example which does not fulfill my criteria, because the practical difference to using heap seems irrelevant at least without context. It is also non-ideal, because without more context, it seems item count could very well cause stack overflow.

Note: I'm specifically after an example code, or suggestion of an algorithm which would benefit from this, for me to implement the example myself.

答:
The reason to use a VLA is primarily performance.  It is a mistake to disregard the wiki example as having only an "irrelevant" difference.  I can easily see cases where exactly that code could have a huge difference, for instance, if that function was called in a tight loop, where read_val was an IO function that returned very quickly on some sort of system where speed was critical.

In fact, in most places where VLAs are used in this manner, they don't replace heap calls but instead replace something like:

```<code>float vals[256]; /* I hope we never get more! */
</code>```

The thing about any local declaration is that it is extremely quick.  The line float vals[n] generally only requires a couple of processor instructions (maybe just one.)  It simply adds the value in n to the stack pointer.

On the other hand, a heap allocation requires walking a data structure to find a free area.  The time is probably an order of magnitude longer even in the luckiest case.  (I.e. just the act of placing n on the stack and calling malloc is probably 5-10 instructions.)  Probably much worse if there's any reasonable amount of data in the heap.  It would not surprise me at all to see a case where malloc was 100x to 1000x slower in a real program.

Of course, then you also have some performance impact with the matching free, probably similar in magnitude to the malloc call.

In addition, there's the issue of memory fragmentation.  Lots of little allocations tend to fragment the heap.  Fragmented heaps both waste memory and increase the time required to allocate memory.

Title: A good C Variable Length Array example

Body:
The reason to use a VLA is primarily performance.  It is a mistake to disregard the wiki example as having only an "irrelevant" difference.  I can easily see cases where exactly that code could have a huge difference, for instance, if that function was called in a tight loop, where read_val was an IO function that returned very quickly on some sort of system where speed was critical.

In fact, in most places where VLAs are used in this manner, they don't replace heap calls but instead replace something like:

float vals[256]; /* I hope we never get more! */

The thing about any local declaration is that it is extremely quick.  The line float vals[n] generally only requires a couple of processor instructions (maybe just one.)  It simply adds the value in n to the stack pointer.

On the other hand, a heap allocation requires walking a data structure to find a free area.  The time is probably an order of magnitude longer even in the luckiest case.  (I.e. just the act of placing n on the stack and calling malloc is probably 5-10 instructions.)  Probably much worse if there's any reasonable amount of data in the heap.  It would not surprise me at all to see a case where malloc was 100x to 1000x slower in a real program.

Of course, then you also have some performance impact with the matching free, probably similar in magnitude to the malloc call.

In addition, there's the issue of memory fragmentation.  Lots of little allocations tend to fragment the heap.  Fragmented heaps both waste memory and increase the time required to allocate memory.


问:
Source control system for binary files
At work we have a legacy system written in Visual FoxPRO.

Everything in foxpro is a table, even forms, so basically if you open a form file with a text editor you don't learn much.

Does anyone know about a tool for source control, that support merging and managing binary files? For now I'm converting what I can convert to text, use a text tool like to merge changes, and replace them manually, to get the team work in one version, then upload the stuff to a TFS server. I know it is not genius... please advise

答:
There is no one size fits all tool, because binary file formats are highly customized.  However, some version control systems, like git, let you specify a custom merge driver for specific file formats.  Here's an example.  Basically, you write a program that can do the merge for any three files, and git will automatically call that program whenever needed to merge entire branches.

If you already have a way to convert a binary file back and forth to text, that's a pretty good start to a custom merge driver.  Unfortunately, there is no easy solution.

Title: Source control system for binary files


问:
Fast algorithm for finding common elements of two sorted lists
Suppose I have two lists of N 3 by 3 vectors of integers.

I need to find a quick way (say of running time at most N^(1+epsilon)) to find the vectors of the first list that have the same 1st coordinate with a vector of the second list.

Of course, I could do the following naive copmarison:

```<code>for u in list_1 do
for v in list_2
if u[1] equals v[1] then
print u;print v;
end if;end for; end for;
</code>```

This, however, would require N^2 loops.

I feel that sorting the two lists according to their first coordinate
and then look up for collisions is perhaps a fast way. Bubbleshort, etc., would probably take logN time, but I can't really see how to code the search for collision between the sorted lists.

Any help would be appreciated.

答:
Here is a quick and dirty O(N) Python answer for you that uses only the given lists. This only works if both lists are SORTED.
I need to clean this up, but it does illustrate what you need to get done. I have chosen bad names for the variables; I will clean this up later.

```<code>def test():
    sorted_full = [1,3,5,7,9,11,15,17]
    sorted_sub = [5,11,17]

    full_ix = 0
    sub_ix = 0

    while full_ix < len(sorted_full) and sub_ix < len(sorted_sub):
        curr_full = sorted_full[full_ix]
        curr_sub = sorted_sub[sub_ix]
        if curr_full == curr_sub:
            print('Common id ' + str(curr_full) + ' at index ' + str(full_ix))
            full_ix +=1
            sub_ix +=1
            continue
        if curr_full < curr_sub:
            full_ix +=1
        else:
            sub_ix+=1

test()
</code>```

Body:
Here is a quick and dirty O(N) Python answer for you that uses only the given lists. This only works if both lists are SORTED.
I need to clean this up, but it does illustrate what you need to get done. I have chosen bad names for the variables; I will clean this up later.

def test():
    sorted_full = [1,3,5,7,9,11,15,17]
    sorted_sub = [5,11,17]

    full_ix = 0
    sub_ix = 0

    while full_ix < len(sorted_full) and sub_ix < len(sorted_sub):
        curr_full = sorted_full[full_ix]
        curr_sub = sorted_sub[sub_ix]
        if curr_full == curr_sub:
            print('Common id ' + str(curr_full) + ' at index ' + str(full_ix))
            full_ix +=1
            sub_ix +=1
            continue
        if curr_full < curr_sub:
            full_ix +=1
        else:
            sub_ix+=1

test()


答:
Rather than the function having the signature:

```<code>object if(bool, object, object)
</code>```

Give it the signature:

```<code>object if(bool, object function(), object function())
</code>```

Then your if function will call the appropriate function based on the condition, only evaluating one of them.

Title: How to implement lazy evaluation of if()

Body:
I am currently implementing an expression evaluator (single line expressions, like formulas) based on the following:

the entered expression is tokenized to separate literal booleans, integers, decimals, strings, functions, identifiers (variables)

I implemented the Shunting-yard algorithm (lightly modified to handle functions with variable number of arguments) to get rid of parenthesis and order the operators with a decent precedence in a postfixed order

my shunting-yard simply produces a (simulated) queue of tokens (by means of an array, my Powerbuilder Classic language can define objects, but only have dynamic arrays as native storage - not true list, no dictionary) that I evaluate sequentially with a simple stack machine

My evaluator is working nicely, but I am still missing an if() and I am wondering how to proceed.

With my shunting-yard postfixed and stack based evaluation, if I add if() as another function with a true and false parts, a single if(true, msgbox("ok"), msgbox("not ok")) will show both messages while I would like to show only one. This is because when I need to evaluate a function, all of its arguments has already been evaluated and placed on the stack.

Could you give me some way to implement if() in a lazy way?

I though about processing these as a kind of macro, but at early time I have not yet the condition evaluation. Perhaps that I need to use an other kind of structure than a queue to keep separately the condition and the true / false expressions? For now the expression is parsed before evaluation, but I also plan to store the intermediate representation as kind of precompiled expression for future evaluation.

Edit: after some though on the problem, I think I could build a tree representation of my expression (an AST instead of a linear token stream), from which I could easily ignore one or another branch of my if().

Body:
Rather than the function having the signature:

object if(bool, object, object)

Give it the signature:

object if(bool, object function(), object function())

Then your if function will call the appropriate function based on the condition, only evaluating one of them.


答:
Can anyone offer any tips or experience on developing a test plan for
  an Agile sprint?

First, consider where do test plans fall within your definition of a story being "done"?  Is it enough to write them out at a high level?  Implement them?  Implement and pass them? There are various pieces here worth noting that can be debated within a team that should be a consensus to determine the standard for the time.

Is it common to just write high-level testing tasks without making the
  actual test cases transparent to the development team?

Could be.  At various places I've worked there have been no testing done as part of development to breaking down more than a handful of tasks as part of testing as there would be unit tests, integration tests, QA having their own tests, and sign off from the end-users that could be part of our process at one place.

What sort of methodologies have you used when developing a test plan
  and what does it look like both at the beginning of a sprint and at
  the end?

TDD would be one idea you could use here.  There are lots of other possibilities where the question is what are you trying to gain from having this methodology: Is it to reduce technical debt, improve quality, or something else?

The sprint demos can be a useful point to show off the functionality to users and collect feedback on what may have been missed.  While this isn't technically in a "test plan," I would argue this falls under Quality Assurance which is part of the point of testing.

Any advice or tips on what comprises an effective and transparent test
  plan as well as a means of developing the test plan would be much
  appreciated.

First, document what are the issues with the current strategy you are using.  Where is it failing to deliver value?  Second, what are the factors you'd want in a revised test strategy?  Part of Agile is about changing things and being prepared to keep adapting.  If you know a structured way that the tests should be done, communicate that and see what others in the team think of such an approach.  Perhaps they'll love it and want to give it a try?  Perhaps they'll have questions that you didn't ponder initially?

Where I have worked where we had a number of tests there could be issues with how fragile the tests make the code because of all the dummy data we had to generate to run the tests and then if someone does change something some tests break and didn't always get cleaned up properly.

Title: Test planning for an Agile sprint

Body:
Can anyone offer any tips or experience on developing a test plan for an Agile sprint? Most of the time our team simply creates a "Test Feature X" task and goes about writing ad-hoc test cases. There typically isn't much strategic forethought put into how features will be tested and how we'll communicate the expectations and results to the rest of the development team and our users.

Is it common to just write high-level testing tasks without making the actual test cases transparent to the development team? What sort of methodologies have you used when developing a test plan and what does it look like both at the beginning of a sprint and at the end? Any advice or tips on what comprises an effective and transparent test plan as well as a means of developing the test plan would be much appreciated.


问:
Presenting PHP source on the Web
I've written a patch for a GPL'ed JavaScript library. To check how the patch works one needs sample CGI (or PHP) backend.

I want to write a demo PHP to show that my JS works and put the open code on my site.

The question: What it the best way to have PHP on server both executed and viewed as the source?

Note that recently I have ordered a Virtual Private Server with a 5 Gb disk, so there are no troubles with installing new software (if any needed) for me.

答:
The official PHP website itself , I believe, is a good example.

For every page, you have a link to its source code at the bottom of it. For example the download page has its source available publicly; by the way, the page which displays the source can display its own source as well.

As a side note, while the concept of showing both the runtime result of the page and its source code is interesting on php.net, make sure to watch only the concept itself, not the source code of the downloads page. After browsing it, I'm quite surprised about how terrible it is.

Title: Presenting PHP source on the Web


答:
Does anyone know about this theory and if it had a name?

"Scare mongering", "B grade Hollywood movie plot", "Vested Interests" come to mind.

has anything like this happened in software.

The Ariane 5 rocket failure, and the AT&T long distance crash in 1990 were caused my something remotely similar to this - as far as both were caused by incorrect messages causing an otherwise working system to fail.


答:
There is one class of cases where ignoring errors is the right thing to do:  When there's nothing that could possibly be done about the situation and when poor and possibly incorrect results are better than no results.

The case of decoding the HDMI stream for display purposes is such a case.  If the stream is bad it's bad, yelling about it won't magically fix it.  You do what you can to display it and let the viewer decide if it's tolerable or not.

Title: Error handling - Should a program fail on errors or silently ignore them

Body:
I'm writing a simple little program to transmit MIDI over a network. I know that the program will encounter transmission problems and / or other exception situations that I won't be able to predict.

For the exception handling, I see two approaches.  Should I write the program so that it:

fails with a bang when something goes wrong
or

should it just ignore the error and
continue, at the expense of data integrity?

Which approach would a user reasonably expect?

Is there a better way of handling exceptions?

Additionally, should my decision about handling exceptions be affected by whether or not I am dealing with a network connection (ie. something where I can reasonably expect to have problems come up)?


问:
How to rewrite from scratch a code for which I own the copyright so I can use it on my job without losing the rights to the first version?
Well I don't want to make it open-source! That's the problem. But I do want to use it on my current job. Company did not agree to sign any alternative license with me and told me to rewrite everything from scratch so they will own it. :(

So how can I do it in a safe way so later on the company don't come back to me and say that I am using the code I wrote for them, which will be similar to the first version I wrote and own the copyright, on my personal projects or even on another job?

How would you rewrite a second version of a hash map without making it look like the first version? This sounds kind of hard to me. :(

答:
Use a different language! Re-write your C in Java or vice-versa.
That way there is no possibility of long sequences of code looking the same. </p>


答:
I don't believe a program should silently ignore or cause havoc whenever it runs into an issue.

What I do with internal software I write for my company...

It depends on the error, lets say if it is a critical function that is entering data into MySQL, it needs to let the user know that it failed. The error handler should try to collect as much information and provide the user with an idea of how to correct the mistake themselves so they can save the data. I also like to provide a way silently send us the information they where trying to save so if worse comes to worse we can enter it manually after the bug is fixed.

If it is not a critical function, something that can error and not affect the final outcome of what they are trying to achieve, I may not show them an error message, but have it send an email that automatically insert it into our bug tracking software or an email distribution group that alerts all programmers in the company so that we are aware of the error, even if the user is not. This allows us to fix the back end while on the front end no one knows what is going on.

One of the biggest things I try to avoid is having the program crash after the error - not being able to recover. I always try to give the user the option to continue without closing the application.

I believe if no one knows about the bug - it will never be fixed.
I am also a firm believer of error handling that allows the application to continue to function once a bug is discovered.

If the error is network related - why not have the functions perform a simple network communication test before executing the function to avoid the error in the first place? Then just alerting the user that a connection is not available please verify your internet etc. etc. and try again?


答:
The language is "providing syntactic sugar for composition".

The trait methods become static methods on a helper class associated with the trait.  See this reference.

Title: How are Scala Traits implemented in the JVM?

Body: I have been reading about traits in Scala. They are pretty amazing. I am curious how they extend a class without actually resulting in multiple inheritance. I know that the JVM doesn't support multiple inheritance, so I am wondering how these extensions work. Is the language just providing syntactic sugar for composition? Or is the code within a trait duplicated in each class that uses it?</p>


问:
Dev approaches to complex JavaScript UI's
I am trying to understand the landscape of different approaches, and best practices, around the development of complex client-side JavaScript.

I'm not sure what to label this class of application, perhaps heavy AJAX or RIA (but not plugins like Flash/Silverlight).  I'm referring to web apps with these characteristics:

Emulate rich/native desktop UX in JavaScript

Contain most/all behavior in client-side JS, using the server as a data-API (JSON/Html-Templates).

This is in contrast to using the web-server for the UI rendering, producing all HTML in a page-refresh model.

Some examples are:

Google Docs / Gmail

Mindmeister

Pivotal Tracker

As we move forward into HTML5, I can see this style of RIA development, with heavy JavaScript, becoming ever more common and necessary to compete.

QUESTION: So what are the common approaches emerging around managing these kinds of heavy JS developments?

Client-side code, as an app grows in features, is fiendishly complicated.  There are problems scaling a development effort across multiple teams with raw JS (or so I hear, and can well believe it).

Google has approached the problem by building GWT that compiles from a higher level language (Java) to JS, leaning on the existing development infrastructure that the higher level language has (Eclipse, strong-typing, refactoring tools), along with abstracting browser compatibility and other issues away from the developer.

There are other tools, like Script# for C# that do something similar.  All this puts JS more in the role of an IL (Intermediate Language). ie. "You never really write in that 'low level language' anymore."

But this 'compile to JS' is not the only approach.  It's not apparent that GWT is the dominant approach...or indeed will become it.

What are people doing with rich-client JavaScript? Some orienting questions:

Are most shops crafting JS manually (atop libs like jQuery et al)?

Or are there many many different approaches, with no clear best-practice emerging?

Are most shops avoiding RIA scale development in favor of the simpler to developer server-side/page-redraw model?  If so, will this last?

Is compiling to JS perhaps an emerging future trend?  Or is this just wrong headed?

How do they manage the complexity and refactoring of client JS?

Modularization and distribution of work across teams?

The application, enforcement, and testing of client-side patterns like MVC/MVP etc.

So, what are the emerging trends in this heavy-JavaScript and HTML5 future of ours?

Thanks!

答:
I work on such an app, built on top of Ext JS. The app is organized modularly. Different modules are implemented as self-contained components that clean up after themselves when they are removed from the Ext component hierarchy. On-demand loaders load additional components right before they are needed (one js file = one component).

I've found that this approach is not that hard to scale. The only real limits I've run into are related to having too many DOM elements in the tree at the same time in IE. The solution there is to strategically unload hidden parts of the application. Because all DOM manipulation occurs via the Ext component hierarchy, the DOM is almost fully abstracted away, and development remains straightforward.

ContentLicense: CC BY-SA 2.5


问:
Why use a database instead of just saving your data to disk?
Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all.

Why should one use a database instead of just saving the data to disk?

答: You need a databse to store / retrieve QAs like the ones we are posting here ! A simple file is unable to organize data related to different topics.</p>


答:
Saving the data to disk IS writing it to a database, especially if you put each object in its own file with the name of the file being the key to the record. And to minimize lookup times for reading the file, create subdirectories based on the first few characters of the key.

For instance key=ghostwriter would go in g/ho/stwriter.json or g/h/o/stwriter.json or g/ho/ghostwriter.json or g/h/o/ghostwriter.json. Choose your naming scheme based on the distribution of your keys. If they are sequence numbers then 5/4/3/12345.json is better than the other way around.

That is a database and if it does all that you need, then do it that way. Nowadays that would be called a NoSQL database like GDBM, or Berkeley db. So many choices. First figure out what you need, then build an interface library to deal with the details, perhaps a get/set interface like memcached or a CRUD interface, and then you will be able to swap libraries if you need to change the database format for one with different characteristics.

Note that some SQL databases like PostgreSQL and Apache Derby DB, will allow you to do SQL queries on top of many NoSQL formats including your own homegrown databases. Not sure about MyBatis but it may be similar.

Avoid NoSQL hype. Read about the features, test the performance and capability and then choose based upon how well it matches your application needs.

http://www.hdfgroup.org/HDF5/ is yet another interesting and widely used datastore format that people do not often consider.

Title: Why use a database instead of just saving your data to disk?

Body:
Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all.

Why should one use a database instead of just saving the data to disk?


问:
Why OTServs have an item cloning problem if the server crashes?
OTServs are open source MMORPGs with a huge community. Mostly all of them have a serious problem: if the server crashes, people can clone items. This is a dirty trick that can be executed because the state of a player is saved to the SQL database when the player logs out. This means the the database is not always in valid state. If 5 different players logged out with the same item, the item would be saved five times on the DB! So a crash would effectively clone the items. The OTServ core is several years old and the main branches still don't provide a solution.

As online games, they consist of a world of dynamic data that changes at a very fast pace. There are thousands of online players and millions of registered players. The data is stored in MySQL. There are tables such as players, player_items, player_skills, player_storage and so on, some with millions of rows. I believe the problem could be that overhead brought by SQL makes it impossible to save all the data at the same pace it happens - hundreds of updates per player per second.

Why OTServs have that problem, what's the impact of the use of SQL databases on the issue and how could it be solved?

答:
Well, to some extent database design was the problem, since giving each item a unique ID from the start would have solved your particular problem.

However, your bigger issue is that the SQL solution wasn't the fastest possible.  That will pretty much always be true.  SQL is designed to go as fast as possible while preserving ACID guarantees and while following a relational model.  If you don't care about those things then it may well not be the best solution.

For raw speed, it would be hard to beat dumping your in-memory structure in a giant block to disk.  Then you don't even have to serialize/deserialize.  If you are always going to save/load the whole world state at once and can deal with the pain of integrating that with the parts done with SQL, and you really need that speed, it might be worth it.

If you want to take everything out of the database and only use JSON, you will get to solve all the concurrency problems the database handles for you (unless it is still feasible to save/load everything every time, which I doubt).  That really won't be easy.


答:
Blame this one both the design adopted by the OT community and MySQL.

This is really not somewhere that I would consider any kind of SQL database server, and especially not one with as many flaws as MySQL. Possibly your problems could be solved with PostgreSQL but even that is not a good fit to this problem. You would do better to look for a solution based on message queueing where all transactions are messages. Make sure that you use/configure an MQ solution that guarantees delivery of messages. Then the app only has to get its transaction into an MQ broker, and your internal systems can take care of writing data to a datastore if necessary, and resolving conflicts.

However, be warned, that if you move to message queuing you will likely have to deal with issues such as serial numbers (similar to DNS zone serial numbers), timestamps, and resolving synchronization corner cases. But at least this is a well documented art. Usually this kind of code is hidden inside database server replication software and never revealed to the customer, but the computer science community has developed all the algorithms in the open, at conferences on Very Large Data Bases, and so on. Hunt for information on CiteSeer, follow up the citations in the papers you read, and you will find everything that you need to implement this yourself.

But please implement this in a modern language like Python or Scala first, and only if you really need to, translate parts of it to lower level C.

More on why I feel that MySQL is a risky choice for this use case.
You have asked about a scenario where synchronization of replicas is an important issue. I have seen so many issues with just master-slave replicas on MySQL 5.5 that I simply don't trust it. But don't trust me. Try two or thtree solutions and test them under load with your application. MySQL is fine for webapps that use the ActiveRecord design pattern, but other open source dbs do exist and are better for many scenarios. For anything as important as a dbms, you need to do comprehensive testing if you want to avoid suffering later.

A lot of people use a simple form of MySQL replication which basically sends a stream of commands from the master to the replica server. You can even chain this together so that the slave sends a stream of commmands onward to yet another server, perhaps one that is considered the "backup" copy and is never used for select queries or to replace a crashed master db. The problem seems to arise because not all commands will produce the same result when run on different servers. Commands using temporary files, random number functions and others, cannot be replicated. In addition I don't believe that MySQL enforces identical configuration on the replicas so you could get DDL that creates tables with different default character sets and sorting rules. Other databases have more replication systems but even Oracle can go haywire if its sequence numbers get munged up.

You are building a banking system and it could easily end up handling a much higher volume of transactions than the biggest New York banks, so the common Enterprise solution of an SQL database is probably not right for you. Tell your developers that they are working on a banking system and that it must be IMPOSSIBLE for money/objects to replicate themselves in multiple accounts. Give them the time and resources to build this system and tell them to read the research that is openly available, i.e. they do not have to reinvent the wheel, just implement it in a way that gives more control than a prepackaged db replication system.

Title: Why OTServs have an item cloning problem if the server crashes?

Body:
OTServs are open source MMORPGs with a huge community. Mostly all of them have a serious problem: if the server crashes, people can clone items. This is a dirty trick that can be executed because the state of a player is saved to the SQL database when the player logs out. This means the the database is not always in valid state. If 5 different players logged out with the same item, the item would be saved five times on the DB! So a crash would effectively clone the items. The OTServ core is several years old and the main branches still don't provide a solution.

As online games, they consist of a world of dynamic data that changes at a very fast pace. There are thousands of online players and millions of registered players. The data is stored in MySQL. There are tables such as players, player_items, player_skills, player_storage and so on, some with millions of rows. I believe the problem could be that overhead brought by SQL makes it impossible to save all the data at the same pace it happens - hundreds of updates per player per second.

Why OTServs have that problem, what's the impact of the use of SQL databases on the issue and how could it be solved?


问:
Performance and other issues with using floating point types in C++
Being interested in C++ performance programming there is one aspect I really have no clue about- and that is the implications of using floating point calculations vs doubles vs normal integer mathematics?

What performance issues with these types of calculations should I consider? What other issues need to be considered when deciding which kind of operators to use?

All I currently know is that doubles are probably the most expensive because they are larger, floating point is next and then integer calculations are usually the fastest on a CPU because they are much simpler.

答:
Use the Right Tool for the Job

Remember the old saw about the man who only had a hammer?

There are many integer and many floating point types and there are many implementations for them.  If you get to know these well, it will make your results better, not to mention your code.  When you make your choices, you will use several criteria.

Application

If your application basically uses whole numbers, generally use integers.  In C++ you have both signed (the default) and unsigned, and selecting unsigned will not only give you almost twice the maximum limit, it may permit the compiler to warn you about unwise uses of your number.

If it uses decimal values, often a floating point representation may be better.  First, it may be more natural to program an equation from science, engineering, or business when the values are not restricted to whole numbers.  Binary coded decimal (BCD) can also help with currency and although it takes more space and is slower, it has some desirable characteristics when used appropriately.

If you application relates to currency, that might be a tricky one because floating point is not precise, so occasionally you can gain or lose cents due to rounding.  Sometimes you can manipulate in integer cents instead of floating point dollars to speed things up and make them more precise.

Prefer Doubles to Floats

I generally prefer doubles to floats because they are less likely to introduce rounding errors.  The C++ compiler will often promote floats to doubles as it passes them to standard library functions even for calculations with basic operators.  Using doubles generally makes your code and the compiler's generated machine code a little bit less complicated.

Rounding very frequently can become a concern, so you will need to consider conversions between integer and floating point, sequence of evaluation within equations, accumulated errors within loops, and normalization of very large and very small values when used together.  You will wish to validate the ranges of both inputs and outputs, and sometimes intermediate values to insure things have not gone wrong.

Size Matters

To insure your results have precise values, you may need to understand the range and representation of the floating point types, and a little bit of numerical analysis.  http://en.wikipedia.org/wiki/Floating_point has a lot of cool information.

As another down vote for floats in favor of doubles consider that a 32-bit float will burn eight bits for the exponent, and the mantissa part that holds a scaled version of your value will need to fit in 23 bits after you account for the sign of the mantissa.  2^23 is not particularly big.  If you want to count from one to 10 million, you might want to use a 32 bit integer or a double.

Underlying architecture

If you have hardware floating point, generally it is OK to use it.  If you don't, highly optimized libraries on fast clocked fix point processors may still cope very well.

If you have a eight bit embedded work horse, learn how to scale and normalize inputs and by all means, carefully implement your repetitious and time consuming calculations using fixed point.  I am an Arduino documentation fan, even though my taste is to use beefier hardware when I work on embedded systems.  The following link has a good discussion of what to do when your environment doesn't have native floating point and your compiler only gives you floats (but no doubles).

http://www.sparkfun.com/tutorials/317

Many fixed point oriented architectures (for example, some Digital Signal Processors (DSP)) can help you with hardware instructions like multiply - accumulate, and often include very capable instructions to help multiply or do arithmetic shifts using integers.  Details for using these may be performed by the compiler or by libraries, so it pays to learn as much as you can about your processor, particularly if you work on DSP or embedded projects.


问:
What's the difference between syntax and semantics?
I've always thought that referring to the syntax of a language was the same as referring to the semantics of a language. But I've been informed that apparently that's not the case. What's the difference?</p>

答:
Syntax refers to formal rules governing the construction of valid statements in a language.
Semantics refers to the set of rules which give the meaning of a statement.

Errors due to syntax occur in a program when ruels of the programming language are violated or misused.
Errors due to semantics occur in a program when statements are not meaningful.

Word order is the basic principal of syntax, those trying to
understand what is written use the syntactic cues of word order to
help give the sentence structure and meaning.
Semantics are an individuals own interpretation of the meaning of a
"sentence" based on their prior knowledge. Therefore a sentence that
seemingly makes no syntactic sense, can have meaning when using
semantic cues.

Syntax is only concerned with what is linguistically and grammatically correct.
Semantics requires all ones prior knowledge which, and is far beyond anything which is language specific.

The sentence "Baby milk drinks" does not have a syntactic meaning, but through semantics most people would interpret it as meaning " Baby drinks milk " as our prior knowledge tells us that a baby drinks milk, and therefore we can find a meaning from the key words.


答:
For a third normal form you will definitely need indexes on all the primary keys.

Whether you need any other indexes depends on how your database is used.
For example if you regularly search for customers in a particular ZIP code, then, it might be a good idea to index the zip_code column in the customer table.

Title: Do You Still Need Indexing After Database Normalization

Body:
After you have done a good normalization, do you still need to index the table? How is this going to affect the performance? Will it even affect the performance in some way after a good normalization?

Which columns are usually indexed if you already have the primary key and the foreign key?

It's seems like it's already effective to normalize a database. But, I might have skipped how indexing affects the database. Is this only effective when queries are used? How does this work/perform and make a database better?


问:
Where is the application of Calculus (of continuous quantities) in Computer Science or programming
I am a Software Engineer professional. I have studied calculus as a core course in my graduation studies. I want to ask question, that what/where is the implementation of calculus in computer science?</p>

答:
I'm brushing up on my calculus because of the problems I've been encountering in the field in which I wish to become expert in: ANN's - artificial neural nets, and signal processing, which are a mixture of programming and physical systems, the physical being the relationship between the neurons, and what kind of neurons you wish to develop and what kind of network you wish to build, what you want it to do. Calculus is not handy for ANN's - it's essential.

So I suppose to answer when do you need higher math for programming I imagine the answer depends upon what problems you wish to tackle in real life. Also I imagine game programmers modelling real life would need higher math as well.


问:
Which of these OOP examples demonstrate proper OOP concepts?
I'm still trying to wrap my head around OOP. All of the following examples work, of course, but is there one (or possibly another) that best exemplifies OOP concepts?

```<code>/**
 * For the following examples the Image class queries an image
 * and associated info from a database, which is passed on
 * instantiation via dependency injection.
 */

$image = new Image(new Db());
</code>```

Example 1:

```<code>if ($image->setImageId($id, $size)) {
    header('content-type: ' . $image->content_type);
    header('content-length: ' . $image->length);
    echo $image->getBytes();
}
</code>```

Example 2:

```<code>if ($image_info = $image->getImageInfoByIdAndSize($id, $size)) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytesByIdAndSize($id, $size);
}
</code>```

Example 3:

```<code>$image->setImageIdAndSize($id, $size);

if ($image_info = $image->getImageInfo()) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytes();
}
</code>```

答:
Personally I prefer #1.

#2 almost seems like you are trying to use a singleton pattern, where you could have dozens of such calls in a row with different $id's each time on the same object.  If that is your intent, you should probably go all the way and make the calls like Image::getImageBytes($id)

#2 and #3 are both odd because it seems like you are loading some kind of sidecar data.  This would be fine if the object composition was such that this side car data may represent another query to the DB (like if there is a table in your db called 'ImageComments' and you wanted to use $image->getImageComments() to return to you an array of 'ImageComments') OR a shared resource that multiple Images might need (like say a parent gallery) but it seems unlikely that an image (especially with a selectable size) would have a stored 'image_info' and even less likely that it would share that with other images.

I might suggest using public methods (i.e. $image->length()) instead of public instance variables to improve any of them (but especially #1).  This would allow for you to do simple things like delay actually loading data from the DB until you actually need to.  And in the case of any sidecar data as discussed earlier, the methods could take care of doing whatever background work was needed to accomplish the task (e.g. public function getImageComments() { return $this->DB("SELECT * FROM 'ImageComments' WHERE image_id = {$this->_id}"); } )

OwnerDisplayName: Isius

OwnerDisplayName: Jared Kipe


答:
The Image class has two responsibilities that should be separated:

Abstract database access

Encapsulate image information

Extract the database access into a data access object (DAO).

```<code>class ImageDao
{
    private $db;

    public function __construct(Db $db) {
        $this->db = $db;
    }

    public function findByIdAndSize($id, $size) {
        return new Image($db->exec(...));
    }
}
</code>```

This frees up Image to do what it should: store information about an image and possibly provide methods to manipulate it.

Title: Which of these OOP examples demonstrate proper OOP concepts?

Body:
I'm still trying to wrap my head around OOP. All of the following examples work, of course, but is there one (or possibly another) that best exemplifies OOP concepts?

```<code>/**
 * For the following examples the Image class queries an image
 * and associated info from a database, which is passed on
 * instantiation via dependency injection.
 */

$image = new Image(new Db());
</code>```

Example 1:

```<code>if ($image->setImageId($id, $size)) {
    header('content-type: ' . $image->content_type);
    header('content-length: ' . $image->length);
    echo $image->getBytes();
}
</code>```

Example 2:

```<code>if ($image_info = $image->getImageInfoByIdAndSize($id, $size)) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytesByIdAndSize($id, $size);
}
</code>```

Example 3:

```<code>$image->setImageIdAndSize($id, $size);

if ($image_info = $image->getImageInfo()) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytes();
}
</code>```

Body:
The Image class has two responsibilities that should be separated:

Abstract database access

Encapsulate image information

Extract the database access into a data access object (DAO).

class ImageDao
{
    private $db;

    public function __construct(Db $db) {
        $this->db = $db;
    }

    public function findByIdAndSize($id, $size) {
        return new Image($db->exec(...));
    }
}

This frees up Image to do what it should: store information about an image and possibly provide methods to manipulate it.

OwnerDisplayName: David Harkness


答:
I will explain it to you with a simple example in the language ENGLISH:

The glass drank Ben

Is a syntactically correct statement. It has a noun, a verb, etc.

But semantically it is wrong, because this statement has no conceivable or correct meaning.

Title: What's the difference between syntax and semantics?

Body: I've always thought that referring to the syntax of a language was the same as referring to the semantics of a language. But I've been informed that apparently that's not the case. What's the difference?</p>


问:
What's the right balance between code consistency and code improvement?
Recently I had a discussion with a colleague regarding code style. He was arguing that your usage of APIs and the general patterns you are using should be as similar as possible with the surrounding code, if not with the the codebase as a whole, just as you would with code appearance (brace positioning, capitalisation etc). For example if I were adding a method to a DAO class in C# I would try to use LINQ where appropriate to help make my code clean and easy to maintain, even if none of the other methods in that class were using it. However, my colleague would argue that I should not use it in that instance because it would be against the existing style of that class and thus harder to understand.

At first I found his position rather extreme, but after thinking it over for a while I am beginning to see his point. With the hypothetical LINQ example, perhaps this class doesn't contain it because my colleagues are unfamiliar with LINQ? If so, wouldn't my code be more maintainable for my fellow developers if I didn't use it? On the other hand, if I truly believe that using such a technique would result in cleaner code, then shouldn't I use it even if it differs drastically from the surrounding code?

I think that the crux of my colleague's argument is that if we all go about implementing similar functionality in a codebase in different ways, and we each think that our way is "best", then in the end the code as a whole just gets harder to understand. However at the moment I still think that if we blindly follow the existing code too much then the quality will just slowly rot over time.

So, to what extent are patterns part of code style, and where should we draw the line between staying consistent and making improvements?

答:
Unfamiliar with LINQ? If so, wouldn't my code be more maintainable for my fellow developers if I didn't use it?

The C# language is still evolving. If people didn't learn the changes from C# 1, they would be missing out on:

Generics

Partials

Anonymous methods

Iterators

Nullable types

Auto-properties

Anonymous types

Extension methods

Ling

Lambdas

Asynchronous methods

This is just a small selection of common features found at the Wikipedia article. The point I'm making is that if the developers don't learn, the codebase will stay in a vacuum. One would hope that your developers do continually improve and the code base evolves, supported by a complete test suite. Do you remember how bad it was with .NET 1 to manually implement properties.

Linq makes life easier. Use it where you can. You might motivate your team members.

So, to what extent are patterns part of code style, and where should we draw the line between staying consistent and making improvements?

Improvements are gradual. To me, it makes no sense to keep old style code which is less readable and potentially less maintainable. Your team members should at least be able to work out what's going on, even if they can't write it.


答:
API consistency is very important, both for public and internal APIs.

Code formatting consistency is important, and should ideally be enforced by automatic formatting tool with same formatting rules for everybody. Makes living with shared version-controlled codebase easier.

Naming conventions should be consistent, also for things like local variables etc.

Static analysis tools should be used to enforce certain other conventions and good practices (but do not blindly follow the defaults of any such tool, the defaults can sometimes border on insane), though if something demands it, don't be afraid to disable some check (usually with a directive inside a comment) temporarily, if you can justify it.

What happens inside functions/methods, apart from what is listed above, doesn't need to be consistent in any way, as long as it is good code on its own. Good, understandable, well commented code is very important, but after that, if compiler and static analysis tools think it's consistent code, that's consistent enough.

About new language features such as LINQ (well, that's not exactly new), the only thing that needs to be considered is, will new enough version of language/libraries be in use everywhere where the code will be used? If in doubt, stick to features which are known to be compatible. This doesn't of course prevent you from pushing a version upgrade throughout the system, so you can start using the new nice things.

And every developer working with code should keep up to date, so any .NET developer should know LINQ, and if they don't they should be forced to learn, for their own good (you never know when you will be looking for a new job in this business, for one reason or another).

Title: What's the right balance between code consistency and code improvement?

Body:
Recently I had a discussion with a colleague regarding code style. He was arguing that your usage of APIs and the general patterns you are using should be as similar as possible with the surrounding code, if not with the the codebase as a whole, just as you would with code appearance (brace positioning, capitalisation etc). For example if I were adding a method to a DAO class in C# I would try to use LINQ where appropriate to help make my code clean and easy to maintain, even if none of the other methods in that class were using it. However, my colleague would argue that I should not use it in that instance because it would be against the existing style of that class and thus harder to understand.

At first I found his position rather extreme, but after thinking it over for a while I am beginning to see his point. With the hypothetical LINQ example, perhaps this class doesn't contain it because my colleagues are unfamiliar with LINQ? If so, wouldn't my code be more maintainable for my fellow developers if I didn't use it? On the other hand, if I truly believe that using such a technique would result in cleaner code, then shouldn't I use it even if it differs drastically from the surrounding code?

I think that the crux of my colleague's argument is that if we all go about implementing similar functionality in a codebase in different ways, and we each think that our way is "best", then in the end the code as a whole just gets harder to understand. However at the moment I still think that if we blindly follow the existing code too much then the quality will just slowly rot over time.

So, to what extent are patterns part of code style, and where should we draw the line between staying consistent and making improvements?


问:
What API design for storing generic data in a more specific format?
for In the project I am working on we send messages about widgets over message queues, serializing them onto the queues as XML. The XML schema contains tags for properties that are common to all types of these widget messages, such as the widget type, command name and destination. It can also contain an arbitrarily sized list of key-value pairs to allow storage of properties that are only relevant for a specific type of widget message. The WidgetMessage class encapsulates this data and the WidgetMessageXmlWriter and WidgetMessageXmlReader classes provide serialization to and from the XML.

I have made some classes that encapsulate specific messages, for example a FooPlaySoundMessage for a 'Foo' widget or a BarSetLightPatternMessage for a 'Bar' widget. They each have a ToWidgetMessage instance method and a FromWidgetMessage static method for converting to and from the WidgetMessage class. Each family of messages inherits from an abstract class for that widget type, e.g. FooMessage and BarMessage, which in turn inherits from the WidgetMessageMapping class; this stores the common message properties and the protected methods used by subclasses for conversion. None of these classes inherit from WidgetMessage since I don't want them to inherit its key-value collection property and associated methods, hence the need for conversion rather than simple casting.

I like the simplicity of my API (e.g. FooPlaySoundMessage msg = FooPlaySoundMessage.fromWidgetMessage(widgetMessage)), but the fact I am having to use protected methods in a base class to share functionality, and static methods to expose it, makes me wonder if there ought to be a separate class or two involved here (similar to WidgetMessageXmlWriter and WidgetMessageXmlReader). On the other hand, I thought that part of the point of OOP is to group data and methods together and so avoid "dumb data objects".

So, do I have the right idea by adding conversion methods to my data objects, or should that functionality be extracted out into another class?

Update:

I think that in all the detail above of my current attempt at a design I didn't explain clearly enough the problem I am trying to solve.

In summary, I have a "generic" DTO class that has some strongly typed properties and a collection of key-value pairs to store other custom data. I want to have some specialized DTO classes for each set of custom data that store all the same data as the generic DTO, except with the key-value pairs replaced by strongly-typed properties. What is the best design for converting between these two types of DTO?

答:
If FooPlaySoundMessage knows how to play sound and also how to map itself to a message queue format you could say the class has more then one responsibility. If it directly delegates the actual sound playing to a different class your FooPlaySoundMessage is basically a data transfer object. Putting common mappings in a shared base class seems fine to me in that case.

I would probably separate it out though. Data transfer objects typically have little to no code, you could see FooPlaySoundMessage as one.

At some point you may have to transmit the same data by some other means or some other format (json perhaps?). You could YAGNI it for now and separate it out then.

I'd probably make some message handler class that parses out the common parts, detects the message type and then delegates to a specific parser e.g. FooPlaySoundXmlMessageParser. When in doubt favor composition over inheritance.


答:
Staying consistent has little value in my perspective; continuously making improvements is a must.

Your colleague's position really impedes innovation. The consistency argument gets you into a situation where you can use, for example, LINQ only if you migrate all code to use LINQ. And well, we don't have time for this, do we?

I'd rather have inconsistency where some code is still doing foreach over ArrayLists and other parts use LINQ on IEnumerable<T>, instead of sticking to the oldest way of doing things until the end of time.

It's your colleagues' responsibility to stay relevant and learn new ways of doing things.


答:
To give a more general answer:

In a case like this, you have two programming "best practices" that are opposed to each other:   code consistency is important, but so is choosing the best possible method to accomplish your task. There is no one correct answer to this dilemma; it depends on a couple factors:

How beneficial is the "correct" way?

Sometimes the new and improved best practice will dramatically increase performance, eliminate bugs, be far easier to program, etc. In such a case, I would lean heavily toward using the new method. On the other hand, the "correct way" may be little more than syntactic sugar, or an agreed idiomatic method of doing something that is not actually superior. In that case, code consistency is probably more important.

How big of a problem would inconsistency create?

How interconnected is the new code with legacy code? Is your new code part of a library?  Does it create an object that gets passed to many parts of the program? In cases like these, consistency is very important. Using a new API, or a new way of doing things in general, might create subtly different results that break assumptions elsewhere in your program.  On the other hand, if you are writing a fairly isolated piece of code, inconsistency is less likely to be a problem.

How large and how mature is your code base? How many developers need to understand it and work on it? Agreed-upon, consistent standards are much more important for larger projects.

Does the code need to run in older environments that may not support the latest features?

Based on the balance of these issues, you have to make the right choice about which route to take. I personally see little value in consistency for consistency's sake, and would prefer to use the latest, best methods unless there is a significant cost to do so.

Of course, there is a third option: rewriting the existing code so that it uses the best methods and is consistent. There are times when this is necessary, but it comes with a high cost.


问:
What classes to put exactly in a class diagram?
What classes must I put in a class diagram? Only classes used in Business Layer and associations between them? Or also other classes in the Data Access Layer, Service Layer, etc.?</p>

答:
First of all, you are not limited to one class diagram. You can have as many diagrams as you want! the purpose of the class diagrams is to help you (or someone else) understand the system better, so it is mostly a problem of taste. Some people need to see all of the details to understand the structure of the system and so they need one big class diagram. But other people prefer having the big picture separated into smaller chunks where each one shows only a part of the system, and they can build their own "big picture" in the head.

BTW, you can also create a component diagram that connects the small details of the class diagrams into a more high-level diagram.


问:
In a resume, what all constitutes a Programming Language
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?

答:
You should target your CV/resume to the context in which it's being applied. Are you applying for a job where they want experience of "programming languages including Java, C++ and HTML"? If you have the relevant experience, list it. Ask yourself whether your Rexx knowledge needs to be presented at all, and if so whether to lump it in with everything else or put it in a secondary section.

I usually have a "relevant technologies" section where I list the things that I have experience in and have been explicitly asked for in the person spec, and a "technology experience" section which is a bit more expansive. Remember that the target audience for your resume includes HR people who aren't technology experts. They don't care whether you think HTML is a programming language, a markup language or a document format: they care whether they can readily discover if your experiences match those they've been asked to look for.


答:
I think it is important to follow a code style in a project eg. naming conventions, indentations etc.

I do not agree that you should be limited from using new language constructs or design patterns simply because your colleagues do not understand them, or they haven't been used in the project before.

Of course these things should have good reasons for using them eg. performance or brevity, if appropriate.


问:
What is a key event Dispatcher in keyboard-interactive apps?
What is a :

Key-Event Dispatcher ?

in keyboard-interactive apps.

What does it really do ?

答:
it listens to all keyboard events and dispatches the events to those listeners that want it (characters to the text box, tab to the focus manager, shortcuts to the respective handler...)

this can be more efficient that everything listening to the keyboard and doing an if test, if the dispatcher uses (for example) a hash map to quickly find where to send the event


答:
Without more context it is hard to be sure, but usually that would be the small piece of code that receives the information "A key of the type X was just pressed/released/kept down for certain time" and then does whatever the program is supposed to to in response. (For instance, in emacs most letter keys trigger the aptly named self-insert-command, while modifier keys change the state of the program so that the next key event will do something different from the normal response.)

It can come as a surprise to beginners, but there is really no intrinsic reason why pressing an 'a' key would let a computer program react by printing an 'a' character. Programmable computers are Turing-complete machines, they can in principle give any conceivable response to any input - if you want the typewriter-like 'copying' behaviour (and in editors, shells etc. that is usually the case), the code has to be told explicitly to do it. The keyboard event dispatcher takes care of that.

Title: What is a key event Dispatcher in keyboard-interactive apps?

Body:
What is a :

Key-Event Dispatcher ?

in keyboard-interactive apps.

What does it really do ?


问:
C++ library API: new or getters?
I'm writing a C++ wrapper for my C library (my C++ skills are a bit rusty) and I'm wondering what's preferable: allowing user to construct objects themselves or give them objects via getters?

What would be idiomatic C++ equivalent of that C function?

```<code>result* process_foo(library_handle*, foo*);
</code>```

a constructor like this:

```<code>Result *res = new Result(library_handle, foo);
</code>```

or a getter like this? (that basically wraps the above code):

```<code>Result *res = library->get_result(foo);
</code>```

Does the answer change if creation of the result could fail?

Getter could return NULL, but what should constructor version do on failure?
AFAIK some people don't like exceptions. An extra method such as init() or is_valid() doesn't seem elegant.

OTOH the Result object sticks to RAII, it's tiny with inline methods, so it might be good candidate for stack allocation.

答:
I would either return a shared_ptr or custom smart pointer, or allow automatic (stack) creation of objects. I might wrap a shared pointer in a result object if the result was large.

Whether it is the library which is processing the foo or a foo which is being processed using resources from the library depends on information you haven't provided, but typically you'd expect something like:

```<code>class Foo {
    public:
        Result Process ( Library& library );
};
</code>```

or, if library is fixed for the lifetime of the Foo

```<code>class Foo {
    public:
        explicit Foo ( Library& library );
        Result Process ();
};
</code>```

either Result is a small struct, or if it is large then I would have it hold a smart pointer to the data.

I would throw an exception if Process failed. Given new throws an exception on failure, as do many standard C++ functions, people who don't like exceptions probably shouldn't be working in C++.

If it is expected that process could return an invalid result, then instead of an exception I would add a function to the result to test its validity, and possibly a conversion to bool so you could write

```<code>Result res ( foo.Process() );

if ( res.IsValid() ) {
    ...
}
</code>```

or

```<code>if ( res ) {
    ...
}
</code>```

Accessing data from an invalid result would throw an exception.

Title: C++ library API: new or getters?

Body:
I would either return a shared_ptr or custom smart pointer, or allow automatic (stack) creation of objects. I might wrap a shared pointer in a result object if the result was large.

Whether it is the library which is processing the foo or a foo which is being processed using resources from the library depends on information you haven't provided, but typically you'd expect something like:

class Foo {
    public:
        Result Process ( Library& library );
};

or, if library is fixed for the lifetime of the Foo

class Foo {
    public:
        explicit Foo ( Library& library );
        Result Process ();
};

either Result is a small struct, or if it is large then I would have it hold a smart pointer to the data.

I would throw an exception if Process failed. Given new throws an exception on failure, as do many standard C++ functions, people who don't like exceptions probably shouldn't be working in C++.

If it is expected that process could return an invalid result, then instead of an exception I would add a function to the result to test its validity, and possibly a conversion to bool so you could write

Result res ( foo.Process() );

if ( res.IsValid() ) {
    ...
}

or

if ( res ) {
    ...
}

Accessing data from an invalid result would throw an exception.


答: For something like this, where the data is (likely) immutable once it is loaded into the object, you should really have some sort of ImageFactory that encapsulates the loading of images, that way the Image class can be immutable.


答:
You should be consistent, but not necessarily with the old code. That is, your team should agree on the right way of doing something, and use that way whenever new code is written or substantial changes are made.

That way, you reap most of the benefits of consistency (in particular, it won't matter who writes the code), but can still improve if the team sees a clear benefit by doing things another way.

In an ideal world, we would rewrite all old code to conform to the new right way. While this is not economically viable, it should make technical sense (or else, the new way is not a better way), and your long term plan should be to upgrade it. If that is not worth it, don't bother with the new way. Put differently, there must be a clear advantage to the new way to consider declaring it the right one.