问:
Developing a team of programmers
So, I have a web application that I need to build. The application will be done in a LAMP environment. I'm being given the resources to bring in 2 other programmers to work on my team. I have team lead and architecture experience before, so taking charge isn't a problem.

The roadblock that I am experience is that I am currently living in a developing country. They have plenty of Software Engineer programs at universities, but no training/classes on really anything relating to LAMP. It is all C++/Java. So, I have a set of resumes I've culled as experience programmers that seem intelligent sitting in front of me. They come from various backgrounds, which include a couple Java developers, an old-school C++/MFC type guy, some C# devs, and a whole bunch of young out of school C++/Java developers. I'm honestly already leaning one way on which skillset I think would mold the easiest to web dev, but as I am not an application developer (exposure in school, but that was a while ago), I though I might open it up and ask you guys: Which skillset of these do you think would lead into the easiest transition to web development? I'm especially curious to hear from anyone who moved from application side over to web development.

答:
A great developer who is "smart and gets things done" (via Joel Spoelsky - credit to @EricBoersma) will likely be more productive than a poor one no matter what language they work in

Unless you're on an extremely tight deadline (and you need the specific skill set) then simply hire people who are smart and work hard.  They'll pick up the web development tech quickly enough, just give them some time to bash out a prototype or two first.

Title: Developing a team of programmers


问:
Client Server .NET application with queuing message
I am new, so forgive me if my question is mistaken or anything, just give me an alert and I'll be glad to fix it.

Me and my team is about to develop a system where the database is located in a private server, and the applications is distributed between clients on distant location.

It is actually a simple CRUD application, but our primary concern is how poor the internet connection on some remote clients.

I thought to give a try to WCF queue message so that when the connection is down, I can save the message to later send it again when it is up, but I don't have a real clear solution in mind.

Currently, my solution would be something like this :

CLIENT

MySolution.sln

-- MyDataAccess

---- Entities (Contains my object class definitions and properties)

---- Repositories (Handles database communication)

---- Services (Handles message queue to server CRUD)

-- MyClassLibraries (Contains third party's DLLs)

-- MyHelper (Contains helper classes and functions)

-- MyCore (Main application project)

---- Model

---- View

---- ViewModel

and for the server :

SERVER

-- MyBackgroundService (Responsible for fetching incoming message and doing CRUD to database)

Is there a better solution to this? I am not good enough yet to see it.

Please let me know if I violate some rules here.

Cheers !

答:
MSMQ is included with Windows (both client and server). Look at the reference for System.Messaging.MessageQueue.

An alternative would be to batch your operations up and to write an application that will submit them to your remote server when connectivity is restored.

ContentLicense: CC BY-SA 3.0


问:
Can we pull future user stories in current sprint?
Suppose we have estimated 5 user stories to complete in a sprint and completed all of them with testing, buffer time and for expected bugs.

Still we have 2-3 days left for one of the developer. Can we pull a future user story in current sprint knowing that only development or part of development can be completed in current sprint?

答:
Scrum exists to serve your needs, not vice versa.  Do whatever makes sense to you.  Monitor how to works.  Adjust.

Does it make sense to give this developer a vacation?  Does your developer have some piece of trivial cleanup that they would like to do and didn't get to?  Is there a particular story that the developer can get a head start on, and then set aside?  We're not there, we don't know the situation.  You are, make something reasonable up.

Remember, Scrum came out of the Agile movement.  Go read the Agile Manifesto at http://agilemanifesto.org/.  It is short, 4 bullet points.  Half of them apply directly to this case, and agree that if an "official Scrum procedure" gets in your way, you should be doing what makes sense to you rather than following ritual.


答:
Certainly, you should be able to pull in whatever is at the top of the product backlog.

But be careful.

Make sure that pulling in the new story will not interfere with the delivery of the stories you have actually committed to.  You really should make sure they are wrapped up and ready to go (deployed even).  At the very least you need to make sure that the new probably-unfinished code does not get mixed up with the finished deliverable code.

Title: Can we pull future user stories in current sprint?

Body:
Suppose we have estimated 5 user stories to complete in a sprint and completed all of them with testing, buffer time and for expected bugs.

Still we have 2-3 days left for one of the developer. Can we pull a future user story in current sprint knowing that only development or part of development can be completed in current sprint?


问:
How do I convince my boss to use REST over SOAP?
We need to create an API to our system. How do I convince my boss that REST is a better option than SOAP (or XML-RPC)?

I say REST is...

easier to implement and maintain

not much new to learn -- plain old HTTP

lot of people have chosen it Yahoo ~ Facebook ~ Twitter

will be lot quicker to code

My boss says SOAP is...

richer and more expressive

it's all standard XML (SOAP, WSDL, UDDI) -- and so will be easier to consume

well standardized than REST

Google uses a lot of SOAP

it is important to adhere to SOAP standards than to create a custom XML schema in REST

答:
Instead of getting into the perpetual boss vs coder arguments let's take some specific cases and assess the suitability of the model. REST lovers are most welcome to refute with logical and fact based arguments -

Purpose: Remoting of services / beating firewall restrictions / binding with protocols such as HTTP

Options: SOAP / REST (discarding protocols like RMI etc as that's kind of out of context)

use case 1: I need optimized binding (JMS / RMI) for several reasons such as
  a) Transaction context propagation
  b) large payload exchange
  c) Stringent QoS
Here, my choice will be SOAP. I saw someone mentioned about interoperability concerns with complex types - please explain why do you think WS-I basic profile compliance can't solve for your problem (with example preferably).

use case 2: I need identity(assertion) propagation in a federated environment of trusted intermediaries (active or passive). This is a B2B use case. I don't think I have a defined way of attaching policy with a REST endpoint. Hence SOAP based service becomes the obvious choice

use case 3: I need a management API for my PaaS. JMX mbeans are to be exposed as services. This is kind of point to point in nature. Bandwidth is a constraint. Governance is not a concern. Browser based client makes it more usable. HTTPS is good enough in this case, I'm not going to have to worry about message level security.
I'll have a pick on REST as I don't need the niceties and complexities of SOAP in this particular case.

use-case 4: I need reliable message support. WS-RM can solve for this. SOAP is the obvious model here because the SOAP engine/ app server has OOTB support for WS-RM configuration.

use case 5: I need to invoke multiple endpoints in a TX context and HTTP is the only available option for transport protocol. I don't think REST supports WS-AT hence I go with SOAP

use case 6: I need an async endpoint. I don't want to unnecessarily hold up the requesting thread. SOAP will be the choice.

use case 7: I want to do away with the unnecessary overhead of XML to types conversion as the data will land up on a UI anyway with minimal or no transformation. REST with JSON would be my choice.

In general, If I'm thinking DATA/RESOURCE I'd prefer REST
If I'm thinking operations/ methods (sync/async .. state..message level security..scalability) I be inclined to use SOAP

Let me not bring in the governance and SOA angle here. I aft'll don't want to sound like "one-of-those" in a forum dedicated to developers.

Feel free to correct me on the above ..


答:
If you feel that you can completely finish another story, then have a chat with your product owner to select the right one. (a small ad-hoc re-planning meeting)

Otherwise, spend that time well to prepare for the next sprint planning meeting. It will make a very pleasant planning.

Or, do some maintenance on your development and building tools.

Or, ... I am sure there's always something useful to do.

Make sure the product owner knows about it.


问:
How to store weekly-occuring time spans in Java objects
My school programming club is setting up a tutoring program. We have 12 tutors who specialize in a range of different languages, and each is available for a different set of hours each day of the week. I want to set up a web interface where students can select the language they need help in, and then be shown a list of the time spans each day that there is a tutor in that language available to help them.

My main question at this point is how I should go about storing tutor availability data - should I use a database (and if so, how), or should I simply store availabilities as fields in POJO "Tutor" objects. If the latter would be best, what data-type should I use? Can I get by simply storing them as strings or should I use joda or java.util Date objects? The task that seems particularly tricky to me at this point is combining availabilities of multiple tutors into a single time-span for each day - i.e., if I have one tutor available from 10-2 and one available from 12-4, I want a single line saying "10-4" to be presented to the user.

I'm just beginning to design my approach to this task, so I'm very open to general suggestions and/or having unforeseen problems pointed out to me.

I would like to use a Java JApplet as my web interface.

答:
In a tutor availability table store triplets of tutor_id, start_available, end_available with the latter two being some sort of date/time.

Have a query that joins from tutor availability through the tutor_id to a table for specific skills, and returns that availability information sorted by start_available, then end_available.  Do the merge in code.  (If you really want you can push that to the database using analytic queries, but you'll probably find code easier.)

The details of converting between the database representation and an in memory representation that you can easily manipulate are up to you and your ORM.  I am not personally a Java programmer, but http://blog.nemccarthy.me/?p=207 suggests that joda is a reasonable option.


问:
Finding the time complexity of the following program that uses recursion
I need to find the time complexity in terms of Big Oh notation for the following program which computes the factorial of a given number: The program goes like this:

```<code>public int fact(int n){

  if (n <=1)
    return 1;
  else
  return n * fact (n-1);
}
</code>```

I know that the above program uses recursion but how to derive the time complexity for the above program?

答:
Recurrence equation:

```<code>           | e                if n = 1
T(n) =     |
           | T(n - 1) + d     if n > 1

f(n) = d so is a 0-degree polynomial, n^0

T(n) ∈ Θ(n^0+1) = Θ(n)
</code>```

Method for Chip & Conquer

The problem of size n is chipped down into one subproblem of size n-c.

```<code>T(n) = T(n - c) + f(n)
</code>```

If c > 0 (the chipping factor) and f(n) is the nonrecursive cost (to create subproblem and/or combine with solutions of other subproblems) then T(n) can be asymptotically bounded as follows:

If f(n) is a polynomial n^α, then T(n) ∈ Θ(n^(α+1))

If f(n) is lg n, then T(n) ∈ Θ(n lg n)

Body:
Recurrence equation:

           | e                if n = 1
T(n) =     |
           | T(n - 1) + d     if n > 1

f(n) = d so is a 0-degree polynomial, n^0

T(n) ∈ Θ(n^0+1) = Θ(n)

Method for Chip & Conquer

The problem of size n is chipped down into one subproblem of size n-c.

T(n) = T(n - c) + f(n)

If c > 0 (the chipping factor) and f(n) is the nonrecursive cost (to create subproblem and/or combine with solutions of other subproblems) then T(n) can be asymptotically bounded as follows:

If f(n) is a polynomial n^α, then T(n) ∈ Θ(n^(α+1))

If f(n) is lg n, then T(n) ∈ Θ(n lg n)


问:
Why can't the PHP engine handle HTTP communication?
The PHP engine interprets the PHP code and is perfectly capable of working with sockets, forming HTTP packets, etc.  Why then do we need a separate Apache server, when the http serving duties could be embedded into the php application along with the page creation code?</p>

答:
It would be hard to have multiple requests running at same time.

However PHP 5.5 will have coroutines which should make writing simple servers much more sensible. (if coroutines in PHP are same as coroutines in other systems).

There are quite a few pure Python web servers, and they work great.


答:
Not just PHP but any language runtime used for web applications development. Actually all of them, including PHP as mentioned by Yannis Rizos, can handle http communication themselves and it is used for testing purposes. But it's not used for production. The reasons are:

Configurability

The dedicated web servers support virtual hosts, URL rewriting, authentication, SSL and similar things that would have to be implemented in each an every web application runtime.

Having separate front-end web server and back-end application engine allows mixing and matching features provided by different implementations of each.

Uniform interface

A single computer only has one port 80, so only one process can be listening on it. But typical public web server runs multiple different webs and web applications often implemented in different languages. The only way to get them all run together on the same host is to have the web server in front of them that dispatches the request appropriately.

Reliability

Bugs in the web application can crash the engine or at least make the engine unresponsive. The web server can shield other visitors from such problems by multiplexing the requests over multiple instances of the back-end and restarting those instances when they exhibit problems. Apache normally preventively restarts it's workers after 100 or so requests. Different front-ends can do things differently, but all are able to restart misbehaving back-end.

Title: Why can't the PHP engine handle HTTP communication?

Body: The PHP engine interprets the PHP code and is perfectly capable of working with sockets, forming HTTP packets, etc.  Why then do we need a separate Apache server, when the http serving duties could be embedded into the php application along with the page creation code?</p>


问:
Longest subsequence without string
Does there exist a dynamic programming algorithm to find the longest subsequence in a string X that does not contain Y as substring? Just that this problem seems so similar to other DP string algorithms such as longest common subsequence and string.  It must be able to handle occurrences of Y that overlap.

It seems that this might be a 2-state DP problem, with the state [s_pos, t_pos] being the longest subsequence of string S starting at s_pos that does not have sting T[t_pos..M] as a substring. N is the length of string S and M is the length of string T. However, my transitions are not correct: it does not get the case where S=aaabc and T=aabc. The problem is in the else statement - I don't know how to transition if the characters are equal. Actually I feel that the if branch is wrong... anyone know what could be wrong?

It even fails the case S=aaab and T=aab. I can explain why it fails: assuming I call solve(0, 0). solve(0, 0) calls solve(1, 1). solve(1, 1) calls solve(2, 2). Since s[2] != t[2], it restarts the search from solve(3, 0). However, aab is a substring and it never checks this or considers this case...

```<code>int solve(int s_pos, int t_pos)
{
    if (s_pos >= N || t_pos >= M) return 0;
    if (t_pos == M - 1 && s[s_pos] == t[t_pos]) return 0;
    int ret = 0;
    if (s[s_pos] != t[t_pos])
    {
        int tmp = solve(s_pos + 1, 0);
        ret = max(ret, tmp + 1);
    }
    else
    {
        for (int i = s_pos + 1; i < N; i++)
        {
            int tmp = solve(i, t_pos + 1);
            if (tmp != 0)
            {
                ret = max(ret, 1 + tmp);
            }
        }
    }
    return ret;
}
</code>```

答:
This should do the trick. I wrote it in a meta code similar to basic.</p>

```<code>LONGEST = ""
while N>0
  POS = find(T,S)
  if POS>0 then
    SUB = left(S,POS)
  else
    SUB = S
    POS = N
  endif
  if len(SUB) > len(LONGEST) then
    LONGEST = SUB
  endif
  N = N-POS
wend
</code>```

Title: Longest subsequence without string

Body:
This should do the trick. I wrote it in a meta code similar to basic.

LONGEST = ""
while N>0
  POS = find(T,S)
  if POS>0 then
    SUB = left(S,POS)
  else
    SUB = S
    POS = N
  endif
  if len(SUB) > len(LONGEST) then
    LONGEST = SUB
  endif
  N = N-POS
wend


问:
How to make .exe file from html5 css application?
I would like to make windows desktop application using HTML5, JavaScript and CSS. I am trying

tidesdk

XULRunner

appjs

I read the documentations of these technologies. But I didn't see how to export the application as a .exe package. I want to write an application in HTML and JavaScript and export to an exe file. How can I do that?

答:
You're almost there, you'll just have to dig into the documentation a bit deeper. ;-)

For example, Steps 5 and 6 in the tidesdk Getting Started Guide create the EXE file and the deployment package.


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

答:
One thing that no one seems to have mentioned is indexing of records. Your approach is fine at the moment, and I assume that you have a very small data set and very few people accessing it.

As you get more complex, you're actually creating a database. Whatever you want to call it, a database is just a set of records stored to disk. Whether you're creating the file, or MySQL, SQLite or whatever is creating the file(s), they're both databases.

What you're missing is the complex functionality that has been built into the database systems to make them easier to use.

The main thing that springs to mind is indexing. OK, so you can store 10 or 20 or even 100 or 1000 records in a serialised array, or a JSON string and pull it out of your file and iterate it relatively quickly.

Now, imagine you have 10,000, 100,000, or even 1,000,000 records. When someone tries to log in you're going to have to open a file which is now several hundred megabytes large, load it into memory in your program, pull out a similarly sized array of information and then iterate 100s of thousands of records just to find the one record you want to access.

A proper database will allow you to set up indexes on certain fields in records allowing you to query the database and receive a response very quickly, even with huge data sets. Combine that with something like Memcached, or even a home-brew caching system (for example, store the results of a search in a separate table for 10 minutes and load those results in case someone else searches for the same thing soon afterwards), and you'll have blazing fast queries, something you won't get with such a large dataset when you're manually reading/writing to files.

Another thing loosely related to indexing is transfer of information. As I said above, when you've got files of hundreds or thousands of megabytes you're having to load all of that information into memory, iterate it manually (probably on the same thread) and then manipulate your data.

With a database system it will run on its own thread(s), or even on its own server. All that is transmitted between your program and the database server is an SQL query and all that is transmitted back is the data you want to access. You're not loading the whole dataset into memory - all you're sending and receiving is a tiny fraction of your total data set.


答: As soon as the data are updated concurrently, the approach using a database (it could well be an in memory database) will likely be more correct and more performant, while at the same time your code remains easy, because you simply don't have to worry about concurrent updates, transactions, caching, asynchronous I/O and all that.</p>

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?


问:
Should I tell the interviewer I already know the answer to the question being asked?
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?

答: As an interviewer, I am not asking the question to see if you know the answer to a tricky chicken and egg question.  Instead I am looking to see how you work through a problem to arrive at an answer.  Therefore, it is often easy to tell the difference between knowing the answer and arriving at the answer (unless, of couse the interviewee acts out to arriving to the answer!)  </p>

ContentLicense: CC BY-SA 2.5


问:
How can I monitor the JVM memory in a proper way?
I'm thinking of how we do JVM memory monitor in a low overhead way in production environment even under busy hour.

Suppose I have two tomcat app server in production, load balance set up behind them. If I can see the jvm memory statistics I can tell load balance to stop sending the request to the server which will encounter OOM issue.  Do this make sense? Jconsole or VisualVM eats more performance resourse is not my choice.

答:
Maybe jvmtop is worth a look for you.

It shows you in a "top-like" manner on a per-jvm basis monitoring metrics like memory consumption, cpu utilization, thread counts etc.


问:
How to create an automated email in several languages (multipart/alternative)?
I need to send automated emails to customers whose language I am not sure about.

90 % are french and would probably not be able to read mails in english.
The other 10 % would probably be able to read in english and clearly not in french.

I don't know what their language is.

I investigated the multipart/alternative that looked promising, give the mailer several variants and he selects the best one.
( see: http://www.ietf.org/rfc/rfc1766.txt )

Unfortunately no mailer seems to care about that, they always show the last part...

did someone manage to make multi-lingual mail with automatic selection of the best version for the users?

Is there some kind of trick to know?

Do you have another solution?

答:
The common solution that I am aware of for such bi-lingual emails is to write them like this:

For the English version, see below

<The text of the message in the local language>

==============

<The text of the message in English>

This way, you don't depend on the capabilities of the mail software of the recipient.

The reason for putting the local language first is because that is what the majority of the recipients will understand best (why bother writing a local language version if everybody understands the English version well enough).

UPDATE: If you are sending emails in HTML, also consider the use of language attributes, as explained in the answer by Matt.


答: One of the important benefits of REST which hasn't been raised, is that it's cachable and easily scalable.  SOAP is not cachable, as it is a POST request.

Title: How do I convince my boss to use REST over SOAP?

Body:
We need to create an API to our system. How do I convince my boss that REST is a better option than SOAP (or XML-RPC)?

I say REST is...

easier to implement and maintain

not much new to learn -- plain old HTTP

lot of people have chosen it Yahoo ~ Facebook ~ Twitter

will be lot quicker to code

My boss says SOAP is...

richer and more expressive

it's all standard XML (SOAP, WSDL, UDDI) -- and so will be easier to consume

well standardized than REST

Google uses a lot of SOAP

it is important to adhere to SOAP standards than to create a custom XML schema in REST


问:
How to set up a Java project with unit tests, references and something like a VS .sln using IntelliJ
I do a lot of c# development work.  Recently, our company decided it was important for webservices to be able to run on Unix machines, and decided that we should write new services in Java as a result.  We've got licenses to IntelliJ, so I'll probably start with that as an IDE.

I've found it pretty easy to find resources about the Java language and the standard libraries.  There are several low level details that are harder to find.

How do I (how should I?) setup a new project with unit tests?

How do you manage references? (I spent hours trying to figure out classpath stuff in eclipse a couple years ago)

How do you setup something equivalent to a .sln file?

So I need pretty low-level help, but without it focusing on code (I don't need help learning to write Hello World, or a for loop).

答:
Just so you know if you're a C# shop and have significant experience you would be able to use Mono without problem.

How do I (how should I?) setup a new project with unit tests?
The same way you would in .NET. The IDE will have the facility to run tests; If you use NUnit you will be happy to know JUnit is what inspired it.

How do you manage references? (I spent hours trying to figure out classpath stuff in eclipse a couple years ago)
Maven. I still think it's better and more powerful than nuget. With that said whilst they're comparable they are not one in the same.

How do you setup something equivalent to a .sln file?
I don't know about IntelliJ but I've used JetBrains PHPStorm which is based on the same code I believe, you can have multiple projects open at the same time. If you move to Eclipse, it'll be a Workspace.

A lot of big / common .NET libraries (NHibernate, NUnit spring to mind) are ports from Java so if you have experience with these then you should find the transition easier.


问:
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 my current company the scrum masters report to our head of product development. They have a desk in one of our team areas, though they are unfortunately responsible for several teams. They spend a good chunk of their time going from team to team rather than working at their desk. Having one scrum master be responsible for 4-5 teams does not work very well at all. </p>

<p>Back when our company was better organized each scrum master worked with only two teams and that seemed to work fairly well. </p>

Title: Scrum Master in the organization

Body:
In my current company the scrum masters report to our head of product development. They have a desk in one of our team areas, though they are unfortunately responsible for several teams. They spend a good chunk of their time going from team to team rather than working at their desk. Having one scrum master be responsible for 4-5 teams does not work very well at all.

Back when our company was better organized each scrum master worked with only two teams and that seemed to work fairly well.


答:
We're a .net house and before starting a new product last year were given the "This needs to run on 'nix" mandate also.

We proved our code against mono, and developed our webservices with ServiceStack.

I didn't do the proving, we are now coming up to a first release which we know will be Windows & MS-SQL specific, our next target is to get the full product up and running on Unix, MySQL and Oracle.

We know from our proving work that we'll have more to do integrating with the new databases than we will getting the full product running on 'nix systems.

Not a line of Java was written.

Title: How to set up a Java project with unit tests, references and something like a VS .sln using IntelliJ

Body:
I do a lot of c# development work.  Recently, our company decided it was important for webservices to be able to run on Unix machines, and decided that we should write new services in Java as a result.  We've got licenses to IntelliJ, so I'll probably start with that as an IDE.

I've found it pretty easy to find resources about the Java language and the standard libraries.  There are several low level details that are harder to find.

How do I (how should I?) setup a new project with unit tests?

How do you manage references? (I spent hours trying to figure out classpath stuff in eclipse a couple years ago)

How do you setup something equivalent to a .sln file?

So I need pretty low-level help, but without it focusing on code (I don't need help learning to write Hello World, or a for loop).


问:
Is map-reduce the basic factor that makes NoSQL more scalable than SQL?
I'm studying the differences between NoSQL and SQL, and what makes the first more scalable. I think I got the point, so I'll try to explain:

Suppose an app has a list of billions of users, each with a quantity of money, and it wants to display the sum of the money of them all. In SQL, it'd have to SELECT SUM(money) FROM users, which would cause the engine to iterate through every user (O(n)) to compute the sum, which is slow. In NoSQL, on other hands, it could previously set up a map reduce function such as nosql_engine.mapReduce(get_money,sum). This would cause the retrieval of the sum to be instantaneous (O(1)) as it would be cached, and updating that computation drops to O(log(n)), because of the associability of the reduction operation. So, in general, this map-reducing capacity is the basic underlying principle that makes NoSQL more scalable than SQL. Is this correct to some extent?

答:
No, that's not it at all. What you describe is gaining an advantage either by caching (having computed the answer before the request arrived) or by parallelization (tasking more than one node with the computation of a big sum). Neither is necessarily exclusive to 'NoSQL' data bases. (I use scare quotes because what people call 'NoSQL' these days is mostly characterized not by the lack of a structured query language, but by non-adherence to strict relational principles.)

Caching frequently computed aggregations can be done in any kind of data store. In relational terms this is called denormalization, and while according to the strictest adherents of relational theory you should never, ever do it, it has obvious advantages in some use cases and is therefore frequently done without much regret by database engines both old and new. The trade-offs are well known (e.g. faster reads vs. slower inserts) and are generally manageable; they are in fact quite similar to the trade-offs for normal indexing.

The characteristic advantage of map-reduce is that more than one node joins in a computation, which means that the data have to be distributed. That is also often done by relational databases, whether in the form of sharding, horizontal partitioning or any other variant thereof. Obviously distributing data can also be combined with denormalization.

What typically makes non-relational data bases faster is the omission of the classical ACID guarantees on data integrity. For instance, the system may not guarantee that all your writes become visible at the same time to every other client, or even that they become visible at all. A frequent compromise is that all data you write will become visible to all clients given enough time, where 'enough' is not strictly limited amount ('eventual consistency'). Obviously, this allows very fast writing because you don't have to wait until all guarantees have been acted out. For reading, the decisive factor is often how much you care about inexact results (e.g. not counting things that are in the system but not yet visible to you). For computing a sum, it is probably that the actual computation (i.e. executing ADD instructions in the processor core) is much, much faster than the I/O involved in retrieving all relevant data chunks from wherever they are, so parallelization does not much good - the total time will almost certainly be dominated by how fast you can get to all operands, and how hard you try not to miss any.


问:
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)?

答:
Never ever should you ignore an error that your program encounters. At the bare minimum, you should log it to a file or some other mecanism for notification. There may be occasional situations where you will want to ignore an error but document it! Don't write an empty catch block without any comments explaining why it is empty.

Whether the program should fail or not depends a lot on the context. If you can handle the error gracefully, go for it. If it is an unexpected error, then your program will crash. That's pretty much the basic of exception handling.


问:
Will You Use an Online Technical Skills Test to Hire a Senior Developer?
There are online services such as IKM that offer skills tests in many areas, including programming.

Would you use these kind of tests when hiring for a senior developer position?

What about just for objectively benchmarking candidates before calling them for an interview? Would you use it as a step after short-listing candidates after interviews?

Is this approach more suitable in some situations compared to others? Have you personally used this kind of service or know someone who has?

答:
I would suggest you to use online testing services only to filter the incompetent candidates. Because many senior developers (as they think) are not senior developers. Just middle or junior.

After you filter incompetent programmers, you need to meet each candidate and ask him about the experience.

Experience should be the main criterion for selection. Programming skills is second, but also very important.

Checkout the following testing services, similar IKM, but oriented only to the programmers:

Tests for Geeks, Codility, BrainBench


问:
run local php/database application on windows pc without wamp
I have a php/mysql applications which I designed, and the client doesn't want it to be online (installed on a webserver) or available on the internet, he wants his employees to use it on a local system.

I don't want them to go through the process of starting up wamp to access the program, is there a simple way to make php web programs run on a local windows pc? using mysql database?

答: Wamp is definitely the way to go. You don't need to make the server accessible from the internet. You can install the web application on a wamp setup on a local web server and make it visible to the local network only. No need to install the application on every user's machine.</p>


答:
You should never silently ignore errors, because your program is built on a series of actions which implicitly depend on everything that's gone before them going right.  If something goes wrong in step 3, and you try to continue on to step 4, step 4 is going to be starting out based on invalid assumptions, which makes it more likely that it will end up generating an error as well. (And if you ignore that too, then step 5 throws an error, and things start to snowball from there.)

The thing is, as the errors pile up, eventually you'll run into some error so big that you can't ignore it, because it will consist of something being given to the user, and that something will be completely wrong.  Then you have users complaining at you about your program not working right, and you have to fix it.  And if the "give something to the user" part is in step 28, and you have no idea that the original error that's causing all this mess was in step 3 because you ignored the error in step 3, you're going to have a heck of a time debugging the problem!

On the other hand, if that error in step 3 makes everything blow up in the user's face, and generates an error saying SOMETHING WENT BADLY WRONG IN STEP 3! (or its technical equivalent, a stack trace,) then the result is the same--the user complaining at you about the program not working right--but this time you know exactly where to start looking when you go to fix it.

EDIT: In response to the comments, if something goes wrong that you anticipated and know how to handle, that's different.  For example, in the event of receiving a malformed message, that's not a program error; that's "user provided bad input which failed validation."  The appropriate response there is to tell the user that he's giving you invalid input, which is what it sounds like you're doing.  No need to crash and generate a stack trace in a case like that.

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)?


答:
A database is needed if you have multiple processes (users/servers) modifying the data. Then the database serves to prevent them from overwriting each others changes.

You also need a database when your data is larger than memory. Nowadays with the memory we have available, this does indeed makes the use of databases in many applications obsolete.

Your approach is definitely better than the nonsense of "in-memory databases". Which are essentially your approach, but with a lot of overhead added.


答:
You should never silently ignore errors. And especially not at the expense of data integrity.

The program is trying to do something. If it fails, you have to face the fact and do something about it. What that something will be depends on lot of things.

In the end the user requested the program to do something and the program should tell them that it didn't succeed. There are many ways how it can do it. It may stop immediately, it may even roll back already completed steps or on the other hand it can continue and complete all steps it can and than tell the user that these steps succeeded and those others failed.

Which way you choose depends on how closely the steps are related and whether it is likely that the error will reoccur for all future steps, which might in turn depend on the exact error. If strong data integrity is required, you have to rollback to last consistent state. If you are just copying bunch of files, you can skip some and just tell the user at the end that those files couldn't be copied. You should not silently skip files and tell the user nothing.

Ad edit, the only difference that makes is that you should consider retrying some number of times before giving up and telling user it didn't work, since network is likely to have transient errors that won't reoccur if you try again.


答: Failing is the right option when you have reasons to think that the overall state of the program is unstable and something bad can happen if you let it run from now on. Somewhat "ignoring" it (i.e., as others have pointed out, logging it somewhere or displaying an error message to the user, then going on) is ok when you know that, sure, the current operation cannot be performed, but the program can keep running.</p>


问:
Why do we use story points instead of man days when estimating user stories?
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?

答:
Story points also help you to measure performance improvement of the team over time. In addition, you do not need to re-estimate everything as performance improves.

Take this example which uses man days:

The team estimates different tasks with man-days. It works for a while, but after some time you see that the team is done faster with many tasks than originally thought. So the team re-estimates the tasks. It works for a while, and after some time you see again the same thing: The team is done faster with many tasks again. So you re-estimate again, and this story repeats again, and again and again...

Why? Because the performance of your team increased. But you do not know about it.

The same example with story points:

The team estimates the size of the user stories. After some sprints, you see that the team can do about 60 story points per sprint. Later, you see that the team has achieved more than 60 story points, maybe 70. And the team continues like that and pulls more user stories for next sprints and delivers them.

Why? Because performance has increased. And you can measure it. And you do not need to re-estimate everything after the performance of your team has increased.


问:
Does the usage of LINQ and Lambda Expressions lead to less readable code?
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?

答:
There is probably a reason why Linq sucks, just do try to make real world examples, instead of these textbook examples.

try to show this function in linqlamdathings and you will see, that all the beauty is gone, while the classic way remains readable. Not to mention deferred execution problems and setting breakpoints.

The truth is LinqLambdaThings are very useful in few cases and they are not thought to replace all the nifty object orientation that you guys never understood

```<code>    public IList<Customer> GetVipCustomers(IList<Customer> source, int maxCount)
    {
        var results = new SortedList<string,Customer>();

        foreach (Customer c in source)
        {
            if (maxCount == results.Count)
                break;

            if (c.IsVip && c.FirstName== "Aaron" || c.SecondName== "Aaron")
                results.Add(c.LastName, c);
        }

        return results.Values;
    }
</code>```

Body:
There is probably a reason why Linq sucks, just do try to make real world examples, instead of these textbook examples.

try to show this function in linqlamdathings and you will see, that all the beauty is gone, while the classic way remains readable. Not to mention deferred execution problems and setting breakpoints.

The truth is LinqLambdaThings are very useful in few cases and they are not thought to replace all the nifty object orientation that you guys never understood

    public IList<Customer> GetVipCustomers(IList<Customer> source, int maxCount)
    {
        var results = new SortedList<string,Customer>();

        foreach (Customer c in source)
        {
            if (maxCount == results.Count)
                break;

            if (c.IsVip && c.FirstName== "Aaron" || c.SecondName== "Aaron")
                results.Add(c.LastName, c);
        }

        return results.Values;
    }


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

答:
I just hacked up a little program that generates a set of random numbers restarting at the same seed each time, to ensure that it's "fair" and "comparable". As it goes along, it figures out the min and max of these values. And when it has generated the set of numbers, it counts how many are above the average of min and max.

For VERY small arrays, it shows a clear benefit with VLA's over std::vector<>.

It is not a real problem, but we can easily imagine something where we'd be reading the values from a small file instead of using random numbers, and doing some other, more meaningful counting/min/max calculations with the same sort of code.

For VERY small values of the "number of random numbers" (x) in the relevant functions, the vla solution wins by a huge margin. As the size goes larger, the "win" gets smaller, and given sufficient size, the vector solution appears to be MORE efficient - didn't study that variant too much, as when we start having thousands of elements in a VLA, it's not really what they were meant to do...

And I'm sure someone will tell me that there's some way of writing all this code with a bunch of templates and get it to do this without running more than the RDTSC and cout bits at runtime... But I don't think that's really the point.

When running this particular variant, I get about 10% difference between the func1 (VLA) and func2 (std::vector).

```<code>count = 9884
func1 time in clocks per iteration 7048685
count = 9884
func2 time in clocks per iteration 7661067
count = 9884
func3 time in clocks per iteration 8971878
</code>```

This is compiled with: g++ -O3 -Wall -Wextra -std=gnu++0x -o vla vla.cpp

Here's the code:

```<code>#include <iostream>
#include <vector>
#include <cstdint>
#include <cstdlib>

using namespace std;

const int SIZE = 1000000;

uint64_t g_val[SIZE];

static __inline__ unsigned long long rdtsc(void)
{
    unsigned hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}

int func1(int x)
{
    int v[x];

    int vmax = 0;
    int vmin = x;
    for(int i = 0; i < x; i++)
    {
        v[i] = rand() % x;
        if (v[i] > vmax)
            vmax = v[i];
        if (v[i] < vmin)
            vmin = v[i];
    }
    int avg = (vmax + vmin) / 2;
    int count = 0;
    for(int i = 0; i < x; i++)
    {
        if (v[i] > avg)
        {
            count++;
        }
    }
    return count;
}

int func2(int x)
{
    vector<int> v;
    v.resize(x);

    int vmax = 0;
    int vmin = x;
    for(int i = 0; i < x; i++)
    {
        v[i] = rand() % x;
        if (v[i] > vmax)
            vmax = v[i];
        if (v[i] < vmin)
            vmin = v[i];
    }
    int avg = (vmax + vmin) / 2;
    int count = 0;
    for(int i = 0; i < x; i++)
    {
        if (v[i] > avg)
        {
            count++;
        }
    }
    return count;
}

int func3(int x)
{
    vector<int> v;

    int vmax = 0;
    int vmin = x;
    for(int i = 0; i < x; i++)
    {
        v.push_back(rand() % x);
        if (v[i] > vmax)
            vmax = v[i];
        if (v[i] < vmin)
            vmin = v[i];
    }
    int avg = (vmax + vmin) / 2;
    int count = 0;
    for(int i = 0; i < x; i++)
    {
        if (v[i] > avg)
        {
            count++;
        }
    }
    return count;
}

void runbench(int (*f)(int), const char *name)
{
    srand(41711211);
    uint64_t long t = rdtsc();
    int count = 0;
    for(int i = 20; i < 200; i++)
    {
        count += f(i);
    }
    t = rdtsc() - t;
    cout << "count = " << count << endl;
    cout << name << " time in clocks per iteration " << dec << t << endl;
}

struct function
{
    int (*func)(int);
    const char *name;
};

#define FUNC(f) { f, #f }

function funcs[] =
{
    FUNC(func1),
    FUNC(func2),
    FUNC(func3),
};

int main()
{
    for(size_t i = 0; i < sizeof(funcs)/sizeof(funcs[0]); i++)
    {
        runbench(funcs[i].func, funcs[i].name);
    }
}
</code>```

Title: A good C Variable Length Array example

Body:
I just hacked up a little program that generates a set of random numbers restarting at the same seed each time, to ensure that it's "fair" and "comparable". As it goes along, it figures out the min and max of these values. And when it has generated the set of numbers, it counts how many are above the average of min and max.

For VERY small arrays, it shows a clear benefit with VLA's over std::vector<>.

It is not a real problem, but we can easily imagine something where we'd be reading the values from a small file instead of using random numbers, and doing some other, more meaningful counting/min/max calculations with the same sort of code.

For VERY small values of the "number of random numbers" (x) in the relevant functions, the vla solution wins by a huge margin. As the size goes larger, the "win" gets smaller, and given sufficient size, the vector solution appears to be MORE efficient - didn't study that variant too much, as when we start having thousands of elements in a VLA, it's not really what they were meant to do...

And I'm sure someone will tell me that there's some way of writing all this code with a bunch of templates and get it to do this without running more than the RDTSC and cout bits at runtime... But I don't think that's really the point.

When running this particular variant, I get about 10% difference between the func1 (VLA) and func2 (std::vector).

count = 9884
func1 time in clocks per iteration 7048685
count = 9884
func2 time in clocks per iteration 7661067
count = 9884
func3 time in clocks per iteration 8971878

This is compiled with: g++ -O3 -Wall -Wextra -std=gnu++0x -o vla vla.cpp

Here's the code:

#include <iostream>
#include <vector>
#include <cstdint>
#include <cstdlib>

using namespace std;

const int SIZE = 1000000;

uint64_t g_val[SIZE];

static __inline__ unsigned long long rdtsc(void)
{
    unsigned hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}

int func1(int x)
{
    int v[x];

    int vmax = 0;
    int vmin = x;
    for(int i = 0; i < x; i++)
    {
        v[i] = rand() % x;
        if (v[i] > vmax)
            vmax = v[i];
        if (v[i] < vmin)
            vmin = v[i];
    }
    int avg = (vmax + vmin) / 2;
    int count = 0;
    for(int i = 0; i < x; i++)
    {
        if (v[i] > avg)
        {
            count++;
        }
    }
    return count;
}

int func2(int x)
{
    vector<int> v;
    v.resize(x);

    int vmax = 0;
    int vmin = x;
    for(int i = 0; i < x; i++)
    {
        v[i] = rand() % x;
        if (v[i] > vmax)
            vmax = v[i];
        if (v[i] < vmin)
            vmin = v[i];
    }
    int avg = (vmax + vmin) / 2;
    int count = 0;
    for(int i = 0; i < x; i++)
    {
        if (v[i] > avg)
        {
            count++;
        }
    }
    return count;
}

int func3(int x)
{
    vector<int> v;

    int vmax = 0;
    int vmin = x;
    for(int i = 0; i < x; i++)
    {
        v.push_back(rand() % x);
        if (v[i] > vmax)
            vmax = v[i];
        if (v[i] < vmin)
            vmin = v[i];
    }
    int avg = (vmax + vmin) / 2;
    int count = 0;
    for(int i = 0; i < x; i++)
    {
        if (v[i] > avg)
        {
            count++;
        }
    }
    return count;
}

void runbench(int (*f)(int), const char *name)
{
    srand(41711211);
    uint64_t long t = rdtsc();
    int count = 0;
    for(int i = 20; i < 200; i++)
    {
        count += f(i);
    }
    t = rdtsc() - t;
    cout << "count = " << count << endl;
    cout << name << " time in clocks per iteration " << dec << t << endl;
}

struct function
{
    int (*func)(int);
    const char *name;
};

#define FUNC(f) { f, #f }

function funcs[] =
{
    FUNC(func1),
    FUNC(func2),
    FUNC(func3),
};

int main()
{
    for(size_t i = 0; i < sizeof(funcs)/sizeof(funcs[0]); i++)
    {
        runbench(funcs[i].func, funcs[i].name);
    }
}


问:
Why PHP doesn't support function overloading?
I am wondering if one of the key features of a programming language is to have the ability to overload functions via arguments. I think it is essential in-context of the Object oriented programming.

Is it intentionally left behind and not allowed? Or is overloading not a good practice?

答:
Not a  "Traditional Overloading" full support, only partial.

A DEFINITION: "Traditional Overloading" provides, when calling method, the ability to have multiple methods with the same name but different quantities and types of arguments. For method declaration, it provides the option to express a separate/isolated declaration for each overloaded function.

Note: the second part of this definition is usually associated with statically-typed programming languages which do type checking and/or arity checking, to choose the correct declaration. PHP is not a statically-typed language, it is dynamic, and use weak typing.

PHP SUPPORT:

YES, provides the ability to call multiple methods with the same name but different quantities. See func_get_args and
@rajukoyilandy answer, we can use f(x) and f(x,y).

YES, provides the ability to call multiple methods with the same name but different types. Se internal use of  gettype in the method.

BUT for references... Only variables can be passed by reference, you can not manage a overloading for constant/variable detection.

NOT  provides the ability to declare multiple methods with the same name but different quantities. This is because we can call f(x) and f(x,y) with the same f declaration.

NOT  provides the ability to declare multiple methods with the same name but different types. This is because PHP compiler must interpret f($integer,$string)  as the same function that f($string,$integer).

See also PHP5 overloading documentation for the "non-traditional overloading" explanations.


答:
I see a lot of answers focus on the problem of concurrency and reliability. Databases provide other benefits beside concurrency, reliability and performance. They allow to not to bother how bytes and chars are represented in the memory. In other words, databases allow programmer to focus himself on "what" rather than "how".

One of the answers mentions queries. "Asking SQL database a question" scales well with the complexity of a question. As code evolves during the development simple queries such as "fetch all" can easily expand to "fetch all where property1 equals this value and then sort by property2" without making it programmer's concern to optimize data structure for such query. Performance of most queries can be speed up by making index for a certain property.

Other benefit are relations. With queries it's cleaner to cross-reference data from different data sets then having nested loops. For example searching for all forum posts from users that have less then 3 posts in a system where users and posts are different data sets (or DB tables or JSON objects) can be done with a single query without sacrificing readability.

All in all, SQL databases are better then plain arrays if data volume can be big (let's say more than 1000 objects), data access in non-trivial and different parts of code access to different subset of data.


问:
How to start a new major version of my application, but still keep the old version 'alive'
I have two applications, called A and B.  The current version of these applciations are 7.x (some customers run 7.1, others run 7.2, ...).  Both applications use a same common framework (let's call this C), like this:

```<code>+---+ +---+
| A | | B |
+---------+
|    C    |
+---------+
</code>```

Because of some important new customers, I want to have the functionality of A and B in one big application.  Merging A and B into one application is not possible, so I am now trying to integrate the functionality of A into B.  So far so good, but I starting to encounter some problems.

First of all, customers that only use the base functionality of B are not interested in all the new functionality of A that is added (and which causes additional overhead for them).  They just want to upgrade their version B with support for new Windows versions, ... and maybe also want all the nice functionality that is added to C (the common framework) as well.

Second, customers that are currently using application A, don't want to directly move to application B, although the combined functionality of A+B would help them in the long term.  For easy upgrades, they want to stick with A, and even see some improvements in C.

Third, all of the developments I'm doing in B might have an impact on the common layer C.  E.g. in order to improve performance of a module in B, I have to refactor a module in C, but since C is also used in A, I need to do much more work.  Additionally, A is an older, less-structured application, and every change in C might make A more unstable.

Question is how to proceed?  I am currently thinking on splitting B in a 7.x release (I could still do some minor developments here and release 7.3, 7.4 in the coming years if needed), and an 8.x release (which would contain all the new functionality).
To solve the problem of the common layer, I could also split C into an old C (7.x) and a new C (8.x).  This gives the following result:

```<code>+-------+ +-------+  +-------+
| A 7.x | | B 7.x |  | B 8.x |
+-----------------+  +-------+
|      C 7.x      |  | C 8.x |
+-----------------+  +-------+
</code>```

Application A would not evolve anymore and would stick to the 7.x version of the common layer C.

Splitting C means that all developments in C will either not be seen in the old A and B (which would still be release 7.x), or if they must be done in release 7.x of A and B, would require doing the developments in both releases.

An alternative could be to split B into B 7.x and B 8.x, but this would limit the refactoring possibilities in C, and actually only solves the first two problems.

Does anybody have any experience with such a kind of major release change?
Any other ideas?

答:
First of all, customers that only use the base functionality of B are not interested in all the new functionality of A that is added (and which causes additional overhead for them).

This is typically only a user interface problem: bring the functionality of A into your combined application "B 8.x", but separate it in a way it won't be seen by the customers of B at the UI level. Build a switch into the application so you can activate the A-functionality only for "A customers". Probably you need to have another switch to hide the B functionality for A customers (this gives you also a chance to sell them the B functionality as a separate module)

Second, customers that are currently using application A, don't want to directly move to application B, although the combined functionality of A+B would help them in the long term.

I guess this will be no problem if you care for two things:

find a way to design your user interface for the "A functionality" in "B 8.x" in a way it is not too different compared to A 7.x

offer those A customers the transition to B 8.x for the same price as from A 7.x to A 7.(x+1). Or, declare "B 8.x" with the disabled B-functions as "A 7.(x+1)" to the A customers (how to name a follow-up may be a contract issue, you should check this).

Finally, if you can migrate your A customers to B 8.x this way, you will automatically solve your third problem.

One thing to add: I am maintaining an application which was in a very similar situation about 15 years ago ("A 7.x" was an MS DOS program, "B 7.x" was a Windows program with a lot of new features, and "B 8.x" contained all functions of both predecessors, where the old "A 7.x" functions were integrated into B and selled as a separate module). You won't be surprised when I tell you that we have no MS DOS customers any more since more than 10 years, so the transition was no problem at all.


答:
Regarding VLAs versus a Vector

Did you consider that a Vector can take advantage of VLAs itself. Without VLAs, the Vector has to specify certain "scales" of arrays e.g. 10, 100, 10000 for storage so you end up allocating a 10000 item array to hold 101 items. With VLAs, if you resize to 200, the algorithm might assume that you'll only need 200 and can allocate a 200 item array. Or it can allocate a buffer of say n*1.5.

Anyway, I'd argue that if you know how many items you'll need at runtime, a VLA is more performant (as Mats' benchmark demonstrated). What he demonstrated was a simple two pass iteration. Think of monte carlo simulations where random samples are taken repeatedly, or image manipulation (like Photoshop filters) where computations are done on each element multiple times and quite possibly each computation on each element involves looking at neighbors.

That extra pointer jump from the vector to its internal array adds up.

Answering the main question

But when you talk about using a dynamically allocated structure like a LinkedList, there is no comparison. An array provides direct access using pointer arithmetic to its elements. Using a linked list you have to walk the nodes to get to a specific element. So the VLA wins hands down in this scenario.

According to this answer, it is architecturally dependent, but in some cases memory access on the stack will be faster due to the stack being available on the cache. With a large number of elements this may be negated (potentially the cause of the diminishing returns Mats saw in his benchmarks). However, it's worth noting that Cache sizes are growing significantly and you'll potentially see more that number grow accordingly.

Title: A good C Variable Length Array example

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


问:
Programming Discrete Wavelet Transform
I am trying to program Discrete Wavelet Transform in Matlab. I do understand that their are various libraries available, but my project requires that I must implement it from scratch.

I am taking a vector of length N. I then provide this vector as input to my my Low Pass and High Pass Filters. My first question is, what must be the cut-off for these two filters?

Once I am done passing my signal through these two filters, I have S_LowPass and S_HighPass. I now down sample these vectors.

Once I have down sampled these vectors, the size of my vector has been reduced. Now when I use Matlab's Wavelet toolbox, the sizes remain the same on each level. My second question: Why are the sizes remaining the same?

答:
From the Wikipedia article on the DWT, the filter pair has to satisfy the requirements of a quadrature mirror filter.

From what I remember from school when you had two analog filters cross you wanted the crossing point (frequency) to be at the 3dB rolloff of each, but it might be different for wavelets -- I don't rememba so good.

I believe the crossing frequency you'd want would be at 1/2 the maximum frequency of your signal (so a quarter of the Nyquist rate).

You might try these notes by Phil Schniter starting w/ section 3.

If you just wanna take the easy route there's a Java implementation using the Haar wavelet; I used a C version of it in this project.

As for the Wavelet toolbox part of the question, I've not used that.

Title: Programming Discrete Wavelet Transform


答:
In my experience, for most technical interviews, the interviewee is really interested in you solution and how you came up with it and how you explain it, rather than whether you had heard the exact same thing before. Unless it was one of those "puzzle" questions that involves a "trick", knowing about the problem beforehand does not really give you a decisive edge unless you are able to solve it by yourself anyway.

For a sufficiently non-trivial question, the problem posed might actually be a well known one, or can be reduced to one. If someone asks about the way to find the shortest route between two nodes in a graph, do you pretend to not know BFS/Dijkstra? IMHO, for some problems it might even be counter-productive to hide the fact that you know your stuff.

Title: Should I tell the interviewer I already know the answer to the question being asked?

Body:
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?


问:
Release Management Tools with DVCS (Mercurial)
My development team is migrating from SVN to Mercurial. Having researched DVCS best practices, it has been suggested that we develop against feature branches of the repo mainline, test them separately, then cherry-pick the features we want in each release, before merging those selected branches into the mainline and eventually releasing it.

Question: What I'm looking for is recommendations for some sort of software tool that will make my role of "software release manager" easier, in that it will allow me to control (cherry-pick) which branches (features, bug fixes, etc) are merged (using Git, or Mercurial) into which software releases (in each environment), and be able to produce the binary deployment artefact.

Our applications are mostly Java Web apps, with a handful of Java Applications, and the projects built using Maven (v2).

I've looked around for release management tools, but nothing really fits the bill.

NB: Not all changes are released as soon as they are completed and pass QA - some are to be released at a later date, as part of a themed release

Things dismissed so far (based on recommendations in similar questions, in other SE threads):

Trac (seems to be just PM type stuff, which we already have with the Atlassian OnDemand offering)

Jenkins (plus other CI tools) - am looking for something to manage my releases, rather than a CI tool (we have used Jenkins in the past).

Mercurial Patch-Queues - I may well need this, but was looking at some sort of "nicer" interface to help me manage it.

ERP offerings - TBH, I didnt look too much into this option, as my initial feeling was that they were too heavy-weight.

BuildMaster, by Inedo - This was the closest match, by far, but was not quite suitable due to its lack of VCS branch picking/merging functionality. I would say however that this is a very nice piece of software, and would recommend it, if it fits your use-case, and is sensibly priced, even for Enterprise use.

Am currently evaluating the following tools:

Bitbucket Feature Branch management (since we use Bitbucket for our projects, seems prudent to evaluate their approach)

Since DVCS is new to us, these things may have been dismissed prematurely, so feel free to re-educate me. :)

答:
This may not be as automated as your want but TortoiseHG will let you select what branch you want to merge and indicate that the branch is merged.  The downside is that I do not think there is a TortoiseHG mode where you can see what branches are still unmerged.  You'd have to scroll throught he graph portion of the history pane to see what is what.

Edit:
From the command line hg head -t will show all branch heads that do not have children and thus no merge.

I'm experimenting with the revision set filter in TortoiseHG to see if you can duplicate the result from within THG but no luck yet :-(


问:
UTF-16 Pitfalls, Chinese
I'm going to be writing an application that is pure HTML5 and JS and MVC.net back-end.
We have .resx files that are getting compiled to .js files for resources in the html5 application.  The application has to work in English and in Chinese which I understand to mean that we need to use UTF-16 everywhere.

Does anyone have any experience using UTF-16 for such a task, or any best practices thereof?

答:
Why do you have this understanding? Both encodings [UTF-8 and UTF-16] can encode all unicode characters by the definition of them being unicode encodings.

Anyway, UTF-8 is more optimal for storage and transmission than UTF-16 in your case. Majority of your characters in the files will not be in Chinese but in markup/js syntax. UTF-8 uses 1 byte for those whereas UTF-16 uses 2 bytes for those, hence UTF-8 wins.

For common Chinese characters UTF-8 needs 3 bytes and UTF-16 needs 2 bytes. Both need 4 bytes for the rarer
characters on the supplemental planes. This gives 33% savings for UTF-16 per Chinese character.

UTF-8 uses 1 byte for any "programming character".
 is 5 bytes in UTF-8 and 10 bytes in UTF-16. 50% savings
for UTF-8 per "programming character".

Title: UTF-16 Pitfalls, Chinese

Body:
Why do you have this understanding? Both encodings [UTF-8 and UTF-16] can encode all unicode characters by the definition of them being unicode encodings.

Anyway, UTF-8 is more optimal for storage and transmission than UTF-16 in your case. Majority of your characters in the files will not be in Chinese but in markup/js syntax. UTF-8 uses 1 byte for those whereas UTF-16 uses 2 bytes for those, hence UTF-8 wins.

For common Chinese characters UTF-8 needs 3 bytes and UTF-16 needs 2 bytes. Both need 4 bytes for the rarer
characters on the supplemental planes. This gives 33% savings for UTF-16 per Chinese character.

UTF-8 uses 1 byte for any "programming character". <div> is 5 bytes in UTF-8 and 10 bytes in UTF-16. 50% savings
for UTF-8 per "programming character".


问:
When to favor ASP.NET WebForms over MVC
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?

答:
This is all about personal choice, assuming we are all proficient with the technology we use. I have been using the WebForms design approach for many years, and I must say that the only downside is that due to it's simplistic approach, many people do not take their time to unearth it's vast capabilities.

I recently used MVC to complete a project, and while I quite like the design approach to application development (which gives you more control, clean urls, SOC, etc), there really isn't much it provides, that WebForms can't. In fact, the emergence of jQuery and it's workings with WebForms (as well as MVC) has made these arguments less of an issue. And when people talk about separation of concerns as an advantage MVC has over MVP, I ask them how much they know about Object Oriented programming and how much they put into use the principle of abstraction and polymorphism.

I am currently comfortable using both technologies and I pick and choose based on the situation. Frankly speaking, it is up to you, but the truth remains that not everyone takes their time to learn in depth what a particular technology is capable of.

Title: When to favor ASP.NET WebForms over MVC


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

答:
There are two options here.

1)  Don't implement if as a function.  Make it a language feature with special semantics.  Easy to do, but less "pure" if you want everything to be a function.

2)  Implement "call by name" semantics, which is much more complicated, but allows compiler magic to take care of the lazy evaluation problem while keeping if as a function instead of a language element.  It goes like this:

if is a function that takes two parameters, both of which are declared as "by name".  When the compiler sees that it's passing something to a by-name parameter, it changes the code to be generated.  Instead of evaluating the expression and passing the value, it creates a closure that evaluates the expression, and passes that instead.  And when invoking a by-name parameter inside the function, the compiler generates code to evaluate the closure.


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

答: hg rollback will rollback the LAST transaction if you have not pushed.  If you've committed or pushed work after the transaction you want to make go away, it will not work.  hg help rollback for details.

Title: Fixing a push to the wrong branch


问:
Should I tell the interviewer I already know the answer to the question being asked?
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?

答:
"Knowing" the answer is not the point. Communicating it in a way that the interviewer has a chance to understand the answer you are giving is. (Of course, the interviewer knows a bunch of answers, but as I said, that's not the point.)

So I'd try to communicate the answer framed into a reasonably didactic, or maybe humorous, frame, so the interviewer can see how I think and function, or don't.

For example, it might be fun for all of you (and informative for the interviewer) to take the question asked into a totally different context, showing that even though the problem at hand looks similar, the solution does not work in the new context. I think the art here is to find a somehow related context for the question in which the solution from the first answer does not work, and then propose spectacular solution ideas which the interviewer may chew on (or laugh about).


问:
How to choose a proper parser generator for PHP
Some programmers avoid regexes in some situations (see this popular @nickf comment), perhaps using a parsing framework such as Lex/Yacc. Others prefer to stay within PHP, perhaps using regular expressions, as it avoids the need for another framework.

When must we use a "real" parser generator instead of coding a parser directly in PHP?

What is the best PHP tool-kit for parsing complex things and what factors can help me determine which is the best?

As I mentioned earlier, perhaps there is no best solution, but simply good practices to help select a solution.

NOTE

Read below only if you is a answer writer

My question was edited: now have good english and objectivity (!), thanks a lot for @FrustratedWithFormsDesigner, @gnat and @Matt.  But, perhaps with @Matt editins, losted my point of view.

My point is not a "Regular expressions vs. framework" dichotomy (!).

I think (and see examples) that programming PHP, we have a good "tool kit", not only with regular expresions (see the power of preg_replace_callback), strings functions, etc., for simple or very specific parsing tasks;  but also with  XML Manipulation, for complex tasks!   See de "parsing power" of process with DOM and/or XSLT...

I see also cases where I have a dilema about use this "PHP native tool kit", or install and learn about some external paser generator (plugged as a library, or a class, etc.).

答:
Regular expressions vs. framework (in the sense of being separate from a language) is a false dichotomy.  Counter-example:  parser combinators.  These can easily handle regular, context-free, and context-sensitive languages; nice libraries exist for them in many languages.  Major advantages are that language integration allows them to snarf their host languages's features (such as type system, unit-testing framework, using classes/objects/functions to extend them, composability), and fewer limitations such as token lookahead; major disadvantages are that an implementation is tied to a specific language (duh), decent error messages are often difficult to generate, and they can easily be inefficient if care isn't taken.

Here are the factors that I look at when deciding what tool to use to parse something:

level of the language, and of the parsing tool, on the Chomsky hierarchy.  Is it a regular language?  Is it context-free?  Is it context-sensitive?  If it's context-sensitive, I'd better make sure my parsing tool can handle it.

testability of parsers, including those for sub-rules.  It's pretty easy to build parsers that look right but are totally wrong.  Being able to independently test sub-parsers makes it far, far easier to get the whole parser right.  This goes hand-in-hand with composability:  building big parsers by putting small parsers together.

whether the language is ambiguous.  Some languages are ambiguous, and some tools can't deal with them.  If there are multiple valid parses, I probably want to be notified of that, possibly by an error or multiple results, instead of just getting a single parse and thinking it's the only one.

control over parse results.  What output do parsers produce -- a concrete parse tree?  Are the nodes strongly typed or stringly typed?  I find it very useful to have some control over how the parse tree is built, as it is being built; having to post-process the tree is often more painful and error-prone, in my experience.  An example is an integer parser -- should it return an integer or a string?

efficiency.  I don't know a whole lot about this, but there are definitely differences between different approaches, especially when there's a lot of backtracking.

error reporting.  At the very least, parse errors should be reportable with position and current rule information; a trace can also be useful but I haven't really seen any decent solutions to this problem (although I bet there are some).

expressivity of the parsing tool.  Does it make me jump through hoops to express simple things like a sequence of values separated by commas, with no trailing comma?  I'm a big fan of BNF, but not being able to extend it is frustrating, and can make grammars look far more complicated, and thus harder to maintain, than they actually need to.  Being able to capture patterns and abstract over them shouldn't be a luxury, but a requirement.


答:
These are my views on the question:

A good starting principle is to fail fast. Specifically, you should never write error handling code for any failure for which you don't know the exact cause.

After applying this principle you may add recovery code for specific error conditions that you encounter. You may also introduce several "safe states" to return to. Aborting a program is mostly safe, but sometimes you might want to return to another known good state. An example is how a modern OS handles an offending program. It only shuts the program down, not the whole OS.

By failing fast and slowly covering more and more specific error conditions you never compromise data integrity and steadily move towards a more stable program.

Swallowing errors, i.e trying to plan for errors for which you don't know the exact cause and therefore have no specific recovery strategy for, only leads to an increasing amount of error-skipping and circumventing code in your program. Since one cannot trust that previous data was correctly processed, you will start seeing spread out checks for incorrect or missing data. Your cyclomatic complexity will spiral out of hand and you will end up with a big ball of mud.

Whether or not you are aware of the failure cases is of less importance. But if you are for instance dealing with a network connection for which you know a certain amount of error states, postpone adding error handling until you also add recovery code. This is in line with the principles outlined above.


问:
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 should always ask yourself if a particular application needs an RDBMS. Too many applications are built with a design process that automatically assumes all the required tools and frameworks at the beginning. Relational databases are so common and many developers have worked on similar applications as before, that they're automatically included before the project starts. Many projects can get away with this, so don't judge too harshly.

You started your project without one, and it works. It was easier for you to get this up and running without waiting until you SQL. There is nothing wrong with that.

As this project expands and the requirements become more complicated, some things are going to become difficult to build. Until you research and test alternate methods, how do you know which is better? You can ask on Programmers and weed through the flames and 'it depends' to answer this question. Once you learn it, you can consider how many lines of code you're willing to write in your language to handle some of the benefits of a database. At some point, you're reinventing the wheel.

Easy is often relative. There are some frameworks that can build a web page and connect a form to a database table without requiring the user to write any code. I guess if you struggle with the mouse, this could be a problem. Everyone knows, this isn't scalable or flexible because god forbid you've tightly coupled everything to the GUI. A non-programmer just built a prototype; lots of YAGNI to be found here.

If you'd rather learn an ORM manipulated by your language of choice instead of learning SQL, go for it, but try to install, create a table and pull some data out of a popular database with SQL (Select * From ; isn't mindblowing stuff). It's easy to do. That's why someone created them in the first place. It doesn't seem like such a huge investment in order to make an informed decision. You could probably do a performance test as well.


问:
Validating Objects With XSDs: Is Re-Serializing Redundant or Negligible?
Context:

I've got a web service that deals with request / response objects. There are strict, externally-defined schemas constraining both the structure and the content of both requests and responses. I need to validate all requests as they are received and all responses before they are sent back (on the web service end of the wire).

I don't want to replicate the validation rules in code, so I'll be validating serialized request / response objects (XML), probably using XmlReader as a starting point (for speed). It'll be 1-way object --> XML validation method that screams if validation fails, otherwise the original object will be used for the actual work.

I'm using WCF, but with XMLSerializer as the schemas are complex and I need the additional XSD support.

Question:

1) Is there a way to avoid re-serializing the objects as they hit my end of the wire? Ideally I'd like to get at the XML before it's de-serialized on the way in, and after it's serialized, just before it goes, on the way out.

I'm aware of [OnSerializing] and [OnSerialized] annotations, but they won't work with XMLSerializer. I don't think I should be writing ReadXml() and WriteXml() using IXmlSerializable either - the schemas are complex and subject to change.

2) Given the XML documents are quite small (122kb seems to be the top end in the sample data set I have) am I right in asserting that the performance hit of re-serializing will be negligible?

3) Any better ideas?

答:
To answer my own question: yes re-serializing would have been redundant.

The answer I was looking for was to use Message Inspectors - job done.


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

答:
So there are several things that need to happen in order for such an event to occur:

A game has to have a sequence of packets that match the protocol for say launching a nuclear missile (or the packets the game sends gets corrupted somehow to match the protocol)

The packets have to be routed incorrectly to the server responsible for launching the nuke

The server's fail safes and verification mechanisms somehow fail.

The likelihood of this happening non-maliciously is slim to none. The possibility for an intentional hack is there but I'm assuming there are so many layers of security and double and triple checks that it would be nigh impossible to bypass them all.

An interesting sidenote, there was a predator drone that was intentionally hacked by sending it invalid GPS data causing it to crash in Iran. I don't know the details, but I don't think there is any encoding within the GPS system that a client can use to verify "yes this signal has come from a satellite hovering over the earth"