问:
Randomly generate directed graph on a grid
I am trying to randomly generate a directed graph for the purpose of making a puzzle game similar to the ice sliding puzzles from Pokemon.

This is essentially what I want to be able to randomly generate: http://bulbanews.bulbagarden.net/wiki/Crunching_the_numbers:_Graph_theory.

I need to be able to limit the size of the graph in an x and y dimension. In the example given in the link, it would be restricted to an 8x4 grid.

The problem I am running into is not randomly generating the graph, but randomly generating a graph, which I can properly map out in a 2d space, since I need something (like a rock) on the opposite side of a node, to make it visually make sense when you stop sliding. The problem with this is that sometimes the rock ends up in the path between two other nodes or possibly on another node itself, which causes the entire graph to become broken.

After discussing the problem with a few people I know, we came to a couple of conclusions that may lead to a solution.

Including the obstacles in the grid as part of the graph when constructing it.

Start out with a fully filled grid and just draw a random path and delete out blocks that will make that path work.

The problem then becomes figuring out which ones to delete to avoid introducing an additional, shorter path. We were also thinking a dynamic programming algorithm may be beneficial, though none of us are too skilled with creating dynamic programming algorithms from nothing. Any ideas or references about what this problem is officially called (if it's an official graph problem) would be most helpful.

Here are some examples of what I have accomplished so far by just randomly placing blocks and generating the navigation graph from the chosen start/finish. The idea (as described in the previous link) is you start at the green S and want to get to the green F. You do this by moving up/down/left/right and you continue moving in the direction chosen until you hit a wall.
In these pictures, grey is a wall, white is the floor, and the purple line is the minimum length from start to finish, and the black lines and grey dots represented possible paths.

Here are some bad examples of randomly generated graphs:

Here are some good examples of randomly generated (or hand tweaked) graphs:

I've also seemed to notice the more challenging ones when actually playing this as a puzzle are ones which have lots of high degree nodes along the minimum path.

答:
it's ice, you will move unless you hit a rock.

the only way to change direction is to hit a rock.

if you hit a rock you have to change directions.

cycles are good, for obvious reasons.

there can be multiple starts, and multiple ends.

more advanced properties:

the cells without adjacent rocks are not reachable (some can be traversed)

walls are rocks too, if you remove them, you can decide to wrap around.

you can use sub-grids as patterns ("tiling" 3x3, 3x4, 5x5, ...etc)

you can overlay a puzzle MxN tile on top of non-traversable MxN area and add a rock to redirect in/out of it.

rotation or symmetry of a tile can be interesting

you can expand a tile by inserting icy rows / columns

example:

```<code>S=start, E=end, o=rock, .=ice

3 . 2 o        3 . . 2 o         . . . . . o o
4 . . E   ~=   4 . . . E   ~=    . . . . . 2 E
o . . .        o . . . .         . . . . . . .
S . 1 o        S . . 1 o         S . . . . 1 o
</code>```

example of combining tiles:

```<code>3 . . 2 o       o 2 . . 3      3 . . 2 o 7 . . 6
4 . . . E   +   E . . . 4  =   4 . . . . . . . 5
o . . . .       . . . . o      o . . . . . . . o
S . . 1 o       o 1 . . S      S . . 1 o 8 . . E
</code>```

you might like the game Tsuro, it uses tiles to generate a random board.

Body:
it's ice, you will move unless you hit a rock.

the only way to change direction is to hit a rock.

if you hit a rock you have to change directions.

cycles are good, for obvious reasons.

there can be multiple starts, and multiple ends.

more advanced properties:

the cells without adjacent rocks are not reachable (some can be traversed)

walls are rocks too, if you remove them, you can decide to wrap around.

you can use sub-grids as patterns ("tiling" 3x3, 3x4, 5x5, ...etc)

you can overlay a puzzle MxN tile on top of non-traversable MxN area and add a rock to redirect in/out of it.

rotation or symmetry of a tile can be interesting

you can expand a tile by inserting icy rows / columns

example:

S=start, E=end, o=rock, .=ice

3 . 2 o        3 . . 2 o         . . . . . o o
4 . . E   ~=   4 . . . E   ~=    . . . . . 2 E
o . . .        o . . . .         . . . . . . .
S . 1 o        S . . 1 o         S . . . . 1 o

example of combining tiles:

3 . . 2 o       o 2 . . 3      3 . . 2 o 7 . . 6
4 . . . E   +   E . . . 4  =   4 . . . . . . . 5
o . . . .       . . . . o      o . . . . . . . o
S . . 1 o       o 1 . . S      S . . 1 o 8 . . E

you might like the game Tsuro, it uses tiles to generate a random board.


问:
Why do we need REST service security if we have HTTPS
I refer to this excellent article http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/ which speaks of amazon like security for web service. However I was asked a question in the team of why do we need it if we already use HTTPS. I was unable to answer as it really seems to me they may be right although gut tells me otherwise.

Also is there places when providing REST services where HTTPS may not work? Like 3rd party websites?

If anyone has experience in securing Web Services over the public interwebs please shed some light with your experience.

Thanks in advance.

EDIT: To clarify I am not speaking of user authentication but more of client authentication. The user authentication can be assumed to be plain text over HTTPS+ REST.

My worry is that this still allows anyone to use the web service without my client to access it since everything is plai text although over HTTPS the client end point can still use my web service without the client application.

答:
HTTPS is about securing the channel, not proving who the caller is, or the many other things you need to consider.  Authentication, authorization and transport layer encryption are only a small part of what you need to consider.  Many of the known vulnerabilities relating to web applications apply very much to REST apis.  You have to consider input validation, session cracking, inappropriate error messages, internal employee vulnerabilities and so on.  It is a big subject.

Robert

OwnerDisplayName: Vangel

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Is taking frequent breaks really that beneficial when programming?
I keep reading that it is recommended for a programmer to take frequent breaks while programming, and the usual recommendation I see is 5 minutes every half hour or 10 minutes every hour.

I gave it a try, but quite often I find something interesting during those 5 minutes, and it takes me away from what I was working on for longer than I planned. Either that, or my mind gets focused on something else and I find it hard to get back into my work and don't focus very well.

Is it really that beneficial to take frequent breaks while programming? Am I doing something wrong for it to be decreasing my productivity instead of increasing it?

答: Yes, best ideas always are income when you have a BREAK like smoking cigarettes or driving a car.

ContentLicense: CC BY-SA 2.5


问:
What is the justification for Python's power operator associating to the right?
I am writing code to parse mathematical expression strings, and noticed that the order in which chained power operators are evaluated in Python differs from the order in Excel.

From http://docs.python.org/reference/expressions.html:

"Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1*2 results in -1."*

This means that, in Python:
2**2**3 is evaluated as 2**(2**3) = 2**8 = 256

In Excel, it works the other way around: 2^2^3 is evaluated as (2^2)^3 = 4^3 = 64

I now have to choose an implementation for my own parser. The Excel order is easier to implement, as it mirrors the evaluation order of multiplication.

I asked some people around the office what their gut feel was for the evaluation of 2^2^3 and got mixed responses.

Does anybody know of any good reasons or conciderations in favour of the Python implementation? And if you don't have an answer, please comment with the result you get from gut feel - 64 or 256?

答:
Wikipedia (and my math teacher) tells me: Stacked exponents are applied from the top down.

This is reflected the way Python evaluates it. Microsoft is wrong (once more)

And Ruby evaluates it as Python, so it's correct without doubt, since Matz can't be wrong.


问:
Criteria for selecting timeout value?
Situation: a piece of software reads frames of data from a file in a seperate thread and puts it on a queue, emptied by another thread. That second thread periodically checks on the queue and fails rather gracefully, by showing an error message stating the read timed out, if no data is available within a certain amount of time. Initially this timeout was set to 200mSec. There was no real reasoning behind that constant though, but it worked fine. We measured on a couple of machines and for large data frames, larger than what would be used by customers, a read took like 20mSec whith no other load on the machine.

However one customer now gets timeout errors now and then (on the second try all is fine, probably the file is in cache or the virus scanner leaves it alone). The programmers are like 'well, yeah, but that customer's machine is full of cruft, virus scanners, tons of unneeded background processes etc'. Of course the customer is like 'hey this should just work, shouldn't it'? While the programers have a point, since the software is heavy enough to validate the need for a dedicated machine, that does not make the customer happy.

Increasing the timeout to 2 seconds, for example, solves the problem. But I'd like to make a proper decision now instead of just randomly pick some magic constant that is probably ok in 99% of cases. What criteria should be used for that? We could just pick a large number, but that feels wrong. (and then we end up with a program that has the horrible bahaviour of hanging when trying to read from a disconnected drive for instance, whereas we'd rather make it show an error right away). Or we could make the timeout value a user setting, but then we need to ducument it clearly and even then not all customers are tech savy enough to really understand what it does. Or we could try and wait until another customer reports timeouts and increase the value again. And again. Until we find something ok for 99.99% of the cases.. Any good practice for this type of situation?

答:
I wouldn't overanalyse this one. I would opt for the user setting. This way you or your helpdesk will be able to help a customer on the fly without any hassle.

If you need to help customers adjust this setting lots of times it's time to automate it. You could use some heuristic like increasing the timeout value each time a timeout occurs, remembering the value that does work etc...

Title: Criteria for selecting timeout value?


问:
How should I create lo-fi (non-interactive) UI prototypes?
I'm currently working on throwing together some basic prototypes, partly to gather requirements and partly to design the final UI.

At the moment I'm trying building up the screen using Post-it notes, with yellow notes for information and pink for actions (buttons or menus). The idea being that you can easily move, remove and add information. But I'm sure there are more efficient methods out there.

What is the recommended way for developers to efficiently create non-interactive UI prototypes?

And why?

I tried some pen, paper and Post-it note versions and they went down like a lead balloon (likely my drawing skills). In the end I used Balsamiq, which thus far is liked by most users and they get it is prototype. Alas, some people are still having problems with the idea that first one should get an idea of what the application should do via some lo-fi prototypes and really want to "see something on the screen" before committing to anything.

答:
My first mock-ups are always pencil & paper or whiteboard, but once the basics are nailed down I usually move to HTML.  I have a bunch of placeholder images that simply say "Header", "Banner", "Image", "Chart" and the like.  Some simple CSS for laying things out somewhat sanely and I'm done.  A little JS tacked on to a control can give you some semblance of functionality, and people just seem to "get it" better.

The only problem with this is that I'm probably the world's worst living UI designer, and sometimes have to remind people that I'm just gathering requirements, not showing them what the completed thing will look like.  I often set the background to pink or something, so whenever anyone asks "Does it have to be pink?" I can counter with "This is just a mock-up, the real thing will look different" (or "You'll have to discuss that with the designer").


问:
How important are unit tests in software development?
We are doing software testing by testing a lot of I/O cases, so developers and system analysts can open reviews and test for their committed code  within a given time period (e.g. 1 week).  But when it come across with extracting information from a database, how to consider the cases and the corresponding methodology to start with? </p>

<p>Although that is more likely to be a case studies because the unit-testing depends on the project we have involved which is too specific and particular most of the time.  What is the general overview of the steps and precautions for unit-testing? </p>

答:
Setting up the database for testing is a pre-condition for your test, albeit potentially more complicated than initializing some strings in memory.  Deleting your setup information could be a post-condition (or not).  You need a working database to test against, but there are many ways to accomplish that.

I agree with ElYusubov that it's easier to do good testing when you don't need any setup or teardown code and can run tests in any order, but some things require setup, and running a suite of tests after performing a complicated setup seems very reasonable to me.

In JUnit you would use something like:

```<code>@Before
public void setUp() {
    this.println("@Before setUp");
    this.myManagedResource = new ManagedResource();
}

@Test
public void test1() {
    this.println("@Test test1()");
}

@After
public void tearDown() throws IOException {
    this.println("@After setUp");
    this.myManagedResource.close();
    this.myManagedResource = null;
}
</code>```

Body:
Setting up the database for testing is a pre-condition for your test, albeit potentially more complicated than initializing some strings in memory.  Deleting your setup information could be a post-condition (or not).  You need a working database to test against, but there are many ways to accomplish that.

I agree with ElYusubov that it's easier to do good testing when you don't need any setup or teardown code and can run tests in any order, but some things require setup, and running a suite of tests after performing a complicated setup seems very reasonable to me.

In JUnit you would use something like:

@Before
public void setUp() {
    this.println("@Before setUp");
    this.myManagedResource = new ManagedResource();
}

@Test
public void test1() {
    this.println("@Test test1()");
}

@After
public void tearDown() throws IOException {
    this.println("@After setUp");
    this.myManagedResource.close();
    this.myManagedResource = null;
}


问:
Understanding the levels of computing
Sorry, for my confused question. I'm looking for some pointers.

Up to now I have been working mostly with Java and Python on the application layer and I have only a vague understanding of operating systems and hardware. I want to understand much more about the lower levels of computing, but it gets really overwhelming somehow. At university I took a class about microprogramming, i.e. how processors get hard-wired to implement the ASM codes. Up to now I always thought I wouldn't get more done if learned more about the "low level".

One question I have is: how is it even possible that hardware gets hidden almost completely from the developer? Is it accurate to say that the operating system is a software layer for the hardware? One small example: in programming I have never come across the need to understand what L2 or L3 Cache is. For the typical business application environment one almost never needs to understand assembler and the lower levels of computing, because nowadays there is a technology stack for almost anything. I guess the whole point of these lower levels is to provide an interface to higher levels. On the other hand I wonder how much influence the lower levels can have, for example this whole graphics computing thing.

So, on the other hand, there is this theoretical computer science branch, which works on abstract computing models. However, I also rarely encountered situations, where I found it helpful thinking in the categories of complexity models, proof verification, etc. I sort of know, that there is a complexity class called NP, and that they are kind of impossible to solve for a big number of N. What I'm missing is a reference for a framework to think about these things. It seems to me, that there all kinds of different camps, who rarely interact.

The last few weeks I have been reading about security issues. Here somehow, much of the different layers come together. Attacks and exploits almost always occur on the lower level, so in this case it is necessary to learn about the details of the OSI layers, the inner workings of an OS, etc.

答:
The keyword for thinking about these things is abstraction.

Abstraction just means deliberately ignoring the details of a system so that you can think about it as a single, indivisible component when assembling a larger system out of many subsystems. It is unimaginably powerful - writing a modern application program while considering the details of memory allocation and register spilling and transistor runtimes would be possible in some idealized way, but it is incomparably easier not to think about them and just use high-level operations instead. The modern computing paradigm relies crucially on multiple levels of abstraction: solid-state electronics, microprogramming, machine instructions, high-level programming languages, OS and Web programming APIs, user-programmable frameworks and applications. Virtually no one could comprehend the entire system nowadays, and there isn't even a conceivable path via which we could ever go back to that state of affairs.

The flip side of abstraction is loss of power. By leaving decisions about details to lower levels, we often accept that they may be made with suboptimal efficiency, since the lower levels do not have the 'Big Picture' and can optimize their workings only by local knowledge, and are not as (potentially) intelligent as a human being. (Usually. For isntance, compiling HLL to machine code is nowadays often done better by machines than by even the most knowledgeable human, since processor architecture has become so complicated.)

The issue of security is an interesting one, because flaws and 'leaks' in the abstraction can often be exploited to violate the integrity of a system. When an API postulates that you may call methods A, B, and C, but only if condition X holds, it is easy to forget the condition and be unprepared for the fallout that happens when the condition is violated. For instance, the classical buffer overflow exploits the fact that writing to memory cells yields undefined behaviour unless you have allocated this particular block of memory yourself. The API only guarantees that something will happen as a result, but in practice the result is defined by the details of the system at the next lower level - which we have deliberately forgotten about! As long as we fulfill the condition, this is of no importance, but if not, an attacker who understands both levels intimately can usually direct the behaviour of the entire system as desired and cause bad things to happen.

The case of memory allocation bugs is particularly bad because it has turned out to be really, really hard to manage memory manually without a single error in a large system. This could be seen as a failed case of abstraction: although it is possible to do everything you need with the C malloc API, it is simply to easy to abuse. Parts of the programming community now think that this was the wrong place at which to introduce a level boundary into the system, and instead promote languages with automatic memory management and garbage collection, which loses some power, but provides protection against memory corruption and undefined behaviour. In fact, a major reason for still using C++ nowadays is precisely the fact that it allows you to control exactly what resources are acquired and released when. In this way, the major schism between managed and unmanaged languages today can be seen as a disagreement about where precisely to define a layer of abstraction.

The same can be said for many other major alternative paradigms in computing - the issue really crops up all the time where large systems have to be constructed, because we are simply unable to engineer solutions from scratch for the complex requirements common today. (A common viewpoint in AI these days is that the human brain actually does work like that - behaviour arising through feedback loops, massively interconnected networks etc. instead of separate modules and layers with simple, abstracted interfaces between them, and that this is why we have had so little success in simulating our own intelligence.)

Title: Understanding the levels of computing


问:
Is Perforce as good at merging as DVCSs?
I've heard that Perforce is very good at merging, I'm guessing this has to do with that it tracks changes in the form of changelists where you can add differences across several files in a single blow. I think this implies Perforce gathers more metadata and therefore has more information to do smarter merging (at least smarter than Subversion, being Perforce centralized).

Since this is similar to how Mercurial and Git handle changes (I know DVCSs track content rather than files), I was wondering if somebody knew what were the subtle differences that makes Perforce better or worse than a DVCS like Mercurial or Git.

答: It depends on how you use Perforce. I seen the 'everyone has a branch' approach and 'everyone uses the same branch' approach. I worked as a Release Engineer in a company that used to former approach and never had any issues.</p>


问:
Separating java projects
I have a large java project, and we use maven for our build cycle. This one project is used extensively - in other projects, in various applications, some of which are contained in it and some which are elsewhere... To be honest, it's a bit of a mess (various bits added on at different times for specific purposes), and I'd like to clean it up a bit. Also, it's not fully tested (lots of bits have been added on without proper unit and integration testing), and there are some tests that take a long time to run or don't actually pass... (uh-oh) - so tests are switched off in the maven build cycle (again, uh-oh).

I am thinking about separating this large project into smaller specific projects, such that the 'final' sub-project (or several sub-projects) would pick up the various sub-projects that it would need.

My thinking is as follows:

if I separate the big project into various sub-projects, this makes it clear what each project's responsibility is.

by separating into sub-projects, I can then clean up the testing of each sub-project individually, and turn on the testing for that sub-project in the maven build cycle.

I am slightly concerned about what impact this might have on the build time.

Would imposing a structure on the large project (i.e. into smaller sub-projects) slow the compiler down?

Also, I have a slight concern on what impact this might have editing time in IDEs (we principally use Intellij). Intellij seems to build each project in turn through the dependency tree - i.e. if C depends on B depends on A, and I change A, it won't try to build B unless A compiles, and so on. Arguably that's advantageous, but I have found that if - for example, I change an interface in A that is widely used in B and C, it takes some time to fix all the errors from that change...

Another question is how to use factory classes. Some aspects of the project depend on external jars. Occasionally (thankfully not often) these are updated, and we have to migrate. We tend to handle this by using a Factory class which points to the correct versions of the external code (so we don't have to change all the implementations throughout the code base).

At the moment this is all in the large project, but I am thinking that by switching to sub-
projects, I could develop a new project for the implementation of new external code, make sure that sub-project is fully functional and tested, and then switch the dependencies / factory class in the user project. However, this is made more complicated by the extensive use of interfaces throughout the large project. For example

sub-project A - contains interfaces

sub-project B - depends on A for interfaces and old external jar

sub-project C - depends on B (and thus A and old external jar), and contains a Factory class that uses B's implementations of interfaces

If I need to change the external jar of B, I can:

create sub-project B_ii - again depends on A, and now the new external jar

once fully functional, I can add C's dependency to B_ii, and change the Factory class to use the new implementations of interfaces.

when that's all working, I can then remove C's dependency to original B, and if desired, remove sub-project B.

Is that a sensible way of going about this?

So, in general, my questions are:

Does anyone have any experience of breaking up large projects? Are there any tips/tricks that you would be willing to share?

What impact did this have on your development and build times?

What advice could you offer on structuring such a break-up of such a project?

答:
I'm going to take a quick first cut at this (great Q BTW!):

Would imposing a structure on the large project (i.e. into smaller
sub-projects) slow the compiler down?

Not by enough that it matters, the overhead is actually in Maven invocations.

Also, I have a slight concern on what impact this might have editing
time in IDEs (we principally use Intellij). Intellij seems to build
each project in turn through the dependency tree - i.e. if C depends
on B depends on A, and I change A, it won't try to build B unless A
compiles, and so on. Arguably that's advantageous, but I have found
that if - for example, I change an interface in A that is widely used
in B and C, it takes some time to fix all the errors from that
change...

Different IDEs have their different strengths with regards to Maven bindings and dependency management. The current state of play seems to be that it mostly just works on the latest Eclipse, Netbeans and IntelliJ - but you will have to teach your developers the emergency double whammy of "Refresh source files from disk and rebuild all related maven projects".

I find I'm having to do that less and less these days though.  Having an SSD drive makes a massive difference here BTW.

snip factory classes paragraphs

Dependency management is incredibly important, regardless of what technology (Maven/Ivy/whatever) use use to help you implement it.

I'd start by getting the extensive reporting out of the Maven dependency plugin and take stock of what you've got.  Generally speaking you set the dependency in the dependency management of the POM as high up the food chain as possible, but no higher.  So if two of your submodules use an external dependency, then haul that into their parent POM and so on and so forth.

Upgrading external JARs should always be done as a proper mini-project.  Evaluate why you're upgrading, alter source code to take advantage of any new features/bug fixes etc.  Just bumping the version without this analysis and work will get you into trouble.

So, in general, my questions are:

Does anyone have any experience of breaking up large projects? Are there any >tips/tricks that you would be willing to share?

Interfaces and Dependency injection are your friend.

Michael Feather's book on dealing effectively with legacy code is a must read.

Integration tests are your friend

Splitting the sub projects into foo-api (interfaces only!) and foo-core and having modules only depend on the foo-api helps a great deal and enforces separation

Jboss Modules and/or OSGi can help enforce clean separation

What impact did this have on your development and build times?

Very minor impact on dev and build times - a massive gain in time for our overall continuous delivery pipeline.

What advice could you offer on structuring such a break-up of such a project?

Do the little things right and the big things tend to fall out cleanly afterwards.  So split things off bit by bit - don't do a massive restructure of the whole lot unless you've got a high percentage of coverage with your integration tests.

Write integration tests before the split - you should more or less get the same result(s) after the split.

Draw diagrams of the modularity you have now and where you want to get to.  Design intermediate steps.

Don't give up - some Yak shaving now builds the foundation for being able to "rapidly build and refactor without fear" Shameless plug -> from Ben and I's The Well-Grounded Java Developer.

Best of luck!

Title: Separating java projects


问:
What does the python Codecs module do?
I just read through the documentation on the Codecs module, but I guess my knowledge/experience of comp sci doesn't run deep enough yet for me to comprehend it.

It's for dealing with encoding/decoding, especially Unicode, and while to many of you that's a complete and perfect explanation, to me that's really vague. I don't really understand what it means at all. Text is text is text in a .txt file? Or so this amateur thought.

Can anyone explain?

答:
Having understood why Unicode is necessary (recommended reading: link, link :thanks @DanielB for the excellent links) and that character encodings are what computers use to represent real world characters, it becomes clear that when Python is reading or writing bytes representing text from a stream (which can be a file, a pipe, a socket, ...), it needs to know which character encoding is being used so those bytes are meaningful as human readable text.

Python uses ascii as the default encoding. The ascii encoding is inadequate for almost all languages (including English: there's no £  in ascii!): so you need to specify an alternate encoding when writing to streams if you intended to use any characters not part of ascii.

When reading from streams, you need to know which encoding was used to write to the stream and use the same encoding to read from it, otherwise the decoded result will be wrong. Try writing a string with Cyrillic characters with the ISO-8859-5 codec and reading it back with the UTF-8 codec: you'll see they don't match, because different byte sequences mean different characters in the two encodings.

So to answer your specific question,

```<code>out_file = open('example.txt', 'w')
</code>```

is actually opening the file for writing using the ascii codec implicitly. If you want to specify another codec, you need to either use the encoding parameter of the open function in Python 3.x:

```<code>out_file = open('example.txt', 'a', 'utf-8')
</code>```

or if you are still using Python 2.x (the latest is Python 2.7.3 at the time of this writing), you need to use the functions from the codecs module:

```<code>out_file = codecs.open('example.txt', 'a', 'utf-8')
</code>```

since open in Python 2.x doesn't allow you to specify an encoding (you can use it to read the byte stream into a byte string in memory though, and then decode that string).

Title: What does the python Codecs module do?

Body:
Having understood why Unicode is necessary (recommended reading: link, link :thanks @DanielB for the excellent links) and that character encodings are what computers use to represent real world characters, it becomes clear that when Python is reading or writing bytes representing text from a stream (which can be a file, a pipe, a socket, ...), it needs to know which character encoding is being used so those bytes are meaningful as human readable text.

Python uses ascii as the default encoding. The ascii encoding is inadequate for almost all languages (including English: there's no £  in ascii!): so you need to specify an alternate encoding when writing to streams if you intended to use any characters not part of ascii.

When reading from streams, you need to know which encoding was used to write to the stream and use the same encoding to read from it, otherwise the decoded result will be wrong. Try writing a string with Cyrillic characters with the ISO-8859-5 codec and reading it back with the UTF-8 codec: you'll see they don't match, because different byte sequences mean different characters in the two encodings.

So to answer your specific question,

out_file = open('example.txt', 'w')

is actually opening the file for writing using the ascii codec implicitly. If you want to specify another codec, you need to either use the encoding parameter of the open function in Python 3.x:

out_file = open('example.txt', 'a', 'utf-8')

or if you are still using Python 2.x (the latest is Python 2.7.3 at the time of this writing), you need to use the functions from the codecs module:

out_file = codecs.open('example.txt', 'a', 'utf-8')

since open in Python 2.x doesn't allow you to specify an encoding (you can use it to read the byte stream into a byte string in memory though, and then decode that string).


问:
What types of processes have to be reflected in flowchart?
In visual programming, there are many events which support our application tasks. So, along with user defined processes, should these also be in flowchart or not?

What about the constructors of classes, are they supposed to be shown in flowchart or not?

答:
Generally speaking, all Inputs (via I/O box), Outputs (via I/O box), Processings(via Proceesing box) and Decisions (via Diamond box) should be reflected in your flowchart.

Talking about events, they can be depcited somewhat via the diamond box if you like. For example:

if (user/system does that) then

```<code> do this
</code>```

else

```<code> do this
</code>```

For constructors, you need to use Object Diagram. As constructors are class methods whose sole purpose is to keep the object in a valid state when instantiated.

Body:
Generally speaking, all Inputs (via I/O box), Outputs (via I/O box), Processings(via Proceesing box) and Decisions (via Diamond box) should be reflected in your flowchart.

Talking about events, they can be depcited somewhat via the diamond box if you like. For example:

if (user/system does that) then

 do this

else

 do this

For constructors, you need to use Object Diagram. As constructors are class methods whose sole purpose is to keep the object in a valid state when instantiated.


问:
Naming conventions for newtype deconstructors (destructors?)
Looking into Haskell's standard library we can see:

```<code>newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }

newtype WrappedMonad m a = WrapMonad { unwrapMonad :: m a }

newtype Sum a = Sum { getSum :: a }
</code>```

Apparently, there (at least) 3 different prefixes used to unwrap a value inside a newtype: un-, run- and get-. (Moreover run- and get- capitalizes the next letter while un- doesn't.) This seems confusing.

Are there any reasons for that, or is that just a historical thing?

If I design my own newtype, what prefix should I use and why?

答:
The convention regarding capitalization is that the first letter of each word is capitalized. So the "w" in "unwrap" is lower-case because "unwrap" is one word, i.e. it's "unwrap [the] monad", not "un wrap [the] monad".

The reason that runStateT is named runStateT is that this best describes how the function is used - it's used to execute/run a state transformer. It wouldn't make sense to call the other deconstructors in your example runSomething because they're not used to run or execute anything.

The distinction between get and unwrap seems a bit more arbitrary (at least for records with only one member), but in this case I think the word unwrap was simply chosen because it fits nicely with the name WrappedMonad.

In the end I'd say that it's not necessary to pick a name that unmistakably marks a function as being a destructor because that's not really relevant. So the "convention" for naming deconstructors is simply to pick one that best describes what it does and how it's supposed to be used.


问:
What's the proper term for a function inverse to a constructor - to unwrap a value from a data type?

Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.)

Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell):

```<code>newtype Wrap = Wrap { unwrap :: Int }
</code>```

Here Wrap is the constructor and unwrap is what?

The questions are:

How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term?

And to clarify, is this/other terminology applicable to other functional languages, or is it used just in the Haskell?

Perhaps also, is there any terminology for this in general, in non-functional languages?

I've seen both terms, for example:

... Most often, one supplies smart constructors and destructors for these to ease working with them. ...

at Haskell wiki, or

... The general theme here is to fuse constructor - deconstructor pairs like ...

at Haskell wikibook (here it's probably meant in a bit more general sense), or

```<code>newtype DList a = DL { unDL :: [a] -> [a] }
</code>```

The unDL function is our deconstructor, which removes the DL constructor. ...

in The Real World Haskell.

答:
Destructor is the term used by C++ and maybe other languages that I don't know of. They are used to release ressources created by the constructor so they do the exact opposite of it. Maybe the concept does not translate literally to Haskell, but the term seems to be used at some places.

EDIT: Considering your edit to the question, I would call it an unwrapper then... I was able to answer the original question but now it has driven away from my knowledge so don't take this edit too seriously.


答: I think destructor is the broader term. Some languages like Java and VB.NET have a finalizer.  https://stackoverflow.com/questions/171952/is-there-a-destructor-for-java</p>

Title: What's the proper term for a function inverse to a constructor - to unwrap a value from a data type?

Body:
Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.)

Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell):

```<code>newtype Wrap = Wrap { unwrap :: Int }
</code>```

Here Wrap is the constructor and unwrap is what?

The questions are:

How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term?

And to clarify, is this/other terminology applicable to other functional languages, or is it used just in the Haskell?

Perhaps also, is there any terminology for this in general, in non-functional languages?

I've seen both terms, for example:

... Most often, one supplies smart constructors and destructors for these to ease working with them. ...

at Haskell wiki, or

... The general theme here is to fuse constructor - deconstructor pairs like ...

at Haskell wikibook (here it's probably meant in a bit more general sense), or

```<code>newtype DList a = DL { unDL :: [a] -> [a] }
</code>```

The unDL function is our deconstructor, which removes the DL constructor. ...

in The Real World Haskell.


答:
The reason why in mathematics stacked exponents are applies from the top down is that the other way you just get multiplication of exponents:</p>

```<code>(((2^3)^4)^5) = 2^(3 * 4 * 5)
</code>```

Title: What is the justification for Python's power operator associating to the right?

Body:
I am writing code to parse mathematical expression strings, and noticed that the order in which chained power operators are evaluated in Python differs from the order in Excel.

From http://docs.python.org/reference/expressions.html:

"Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1*2 results in -1."*

This means that, in Python:
2**2**3 is evaluated as 2**(2**3) = 2**8 = 256

In Excel, it works the other way around: 2^2^3 is evaluated as (2^2)^3 = 4^3 = 64

I now have to choose an implementation for my own parser. The Excel order is easier to implement, as it mirrors the evaluation order of multiplication.

I asked some people around the office what their gut feel was for the evaluation of 2^2^3 and got mixed responses.

Does anybody know of any good reasons or conciderations in favour of the Python implementation? And if you don't have an answer, please comment with the result you get from gut feel - 64 or 256?

Body:
The reason why in mathematics stacked exponents are applies from the top down is that the other way you just get multiplication of exponents:

(((2^3)^4)^5) = 2^(3 * 4 * 5)


问:
Best practices for versioning project after dependency upgrade
Say, my project have dependency N with version 1.0.0.
Then something have changed, and I should depend on newer version - let it be 1.0.1.

OK, I'm incrementing dependency version, nothing else changes in my code.
It looks like I should increment my own projects' version, but how exactly I should increment?

Should I increment only third number (so-called revision), or best practices here are more complicated. For example, may be, if we are changing projects' dependency minor value, we should do the same thing in the project itself?

答: If you're only updating the dependency, that's a minor revision (barely any change to your code) so I would only update the third numeral.  The second numeral is usually reserved for major updates (big bug fixed, new features, balance issues, etc) and the first one for a completely new version of the software.</p>


答:
I'm not aware of any best practices for this situation, so here's my take:

An updated dependency should be reflected in your version; let's take the example of MAJOR.MINOR.REVISION numbering scheme.

Any version change in a dependency should at least increment your REVISION number, but a bigger change, such as a MAJOR or MINOR change in the dependency version, should cause you to increment your MINOR version.

Although MAJOR version changes in dependencies often come with API changes, I wouldn't increment your own MAJOR version unless you've made more changes than just updating to a new MAJOR version of a dependency.

Title: Best practices for versioning project after dependency upgrade

Body:
Say, my project have dependency N with version 1.0.0.
Then something have changed, and I should depend on newer version - let it be 1.0.1.

OK, I'm incrementing dependency version, nothing else changes in my code.
It looks like I should increment my own projects' version, but how exactly I should increment?

Should I increment only third number (so-called revision), or best practices here are more complicated. For example, may be, if we are changing projects' dependency minor value, we should do the same thing in the project itself?


问:
DI and hypothetical readonly setters in C#
Sometimes I would like to declare a property like this:

```<code>public string Name { get; readonly set; }
</code>```

I am wondering if anyone sees a reason why such a syntax shouldn't exist. I believe that because it is a subset of "get; private set;", it could only make code more robust.

My feeling is that such setters would be extremely DI friendly, but of course I'm more interested in hearing your opinions than my own, so what do you think?

I am aware of 'public readonly' fields, but those are not interface friendly so I don't even consider them. That said, I don't mind if you bring them up into the discussion

Edit

I realize reading the comments that perhaps my idea is a little confusing. The ultimate purpose of this new syntax would be to have an automatic property syntax that specifies that the backing private field should be readonly. Basically declaring a property using my hypothetical syntax

```<code>public string Name { get; readonly set; }
</code>```

would be interpreted by C# as:

```<code>private readonly string name;
public string Name
{
    get
    {
        return this.name;
    }
}
</code>```

And the reason I say this would be DI friendly is because when we rely heavily on constructor injection, I believe it is good practice to declare our constructor injected fields as readonly.

答:
As mentioned in the comments, properties are just syntactic sugar. When they are turned into methods, "readonly" would no longer be syntactically correct.

You can expose a private variable through a read-only property for the desired effect:

```<code>private readonly string _name;

public string Name {
    get {
        return _name;
    }
}

public MyObject(string injectedName) {
    _name = injectedName;
}
</code>```

Edit:

How do you envision your idea would work (if it was possible)? Your readonly property wouldn't work in an initialization list because the constructor is already finished executing at that point.

Body:
As mentioned in the comments, properties are just syntactic sugar. When they are turned into methods, "readonly" would no longer be syntactically correct.

You can expose a private variable through a read-only property for the desired effect:

private readonly string _name;

public string Name {
    get {
        return _name;
    }
}

public MyObject(string injectedName) {
    _name = injectedName;
}

Edit:

How do you envision your idea would work (if it was possible)? Your readonly property wouldn't work in an initialization list because the constructor is already finished executing at that point.


问:
Off-shore bug fixing
If a prospective employer told you they "outsourced bug fixing because developers hate fixing bugs", What would you think? What might be your concerns?</p>

答:
This policy actually exists subconsciously in some companies.  I work for an outsourcer; myself and my colleagues are more proficient programmers than the guys onsite, they ask us to teach them how to use tools etc., but the other side of that is that we will spot problems in their code more quickly than they do.

Generally the client's programmers are physically located in the same building as at least some of the users, so they are more likely to get context that doesn't reach across hemispheres.  We find it works well, the missing part for me is that they are not reviewing our code so when the contract finishes they may have some surprises or questions, not due to any shoddy practices on our part necessarily but just the usual problems you have when taking over someone else's project.

In any case I'm glad that in our case it's not an official policy, as such I think it would erode the onsite programmers to being little more than BAs.

Title: Off-shore bug fixing


问:
Responding to end users about bugs they found
I have an issue tracking system, but sometimes users report bugs directly to me in an email.

If I'm responding to a bug report in an email, what's a good etiquette to use? Do I thank them for reporting the bug? Do I apologize for it ? Is there a good template anywhere?

答:
Thank them for reporting the bug.

And perhaps:

Point them at the issue tracker, explaining to them that although bug reports via email are welcome, reporting them in the issue tracker is more efficient (you'd get to them faster),

If the bug is known, tell them about it (in layman's terms). If it's already in the issue tracker, point them at it.

If the bug is brand new, register it in the issue tracker yourself and explain to them how they can follow its progress.


答:
Thank them for bringing it up to your attention.

Reply back with the defect number from the bug tracker.  Yes, that means you need to enter the bug yourself.

Verify that you have all the details you need to recreate the bug.

Bonus points if you can give them an estimate of its priority and when you might be able to fix it.  It's also fair to explain your prioritization process and state that you'll update the defect ticket after investigation and prioritization.

Double bonus points for politely pointing out that there is a bug tracker that they could use in case they didn't want to wait on an email reply.

Title: Responding to end users about bugs they found

Body:
I have an issue tracking system, but sometimes users report bugs directly to me in an email.

If I'm responding to a bug report in an email, what's a good etiquette to use? Do I thank them for reporting the bug? Do I apologize for it ? Is there a good template anywhere?


问:
Java web app, with plugin framework and ability to connect to source for updates
I've searched all around for some good sources, but either have been searching for the wrong keywords, or I'm just missing something. I'm looking to redevelop a web app I've been using for some time now. Many parts are out of date, and we're constantly throwing in little hacks to attempt to give it new life.

So what I'd like to do is re-engineer it from the ground up, built on some sort of plug-in framework. Before I continue, I'm more or less an intermediate Java programmer. In some ways, I'm hoping to use this project as a big learning experience.

I've read a lot about OSGi, and it seems that's the most complete framework. Ideally, I would like an end result web app which I can run one instance as my hosting environment, and other instances can connect to it to grab new and updated plug-ins. Eventually I'll want to lock down these plug-ins based on some undecided criteria of who can get them (basically some will simply be updates, others will provide new functionality and should be "purchased" through an external system). But that will probably be handled in a later phase. There should be an administration view for managing bundles in a hot environment (looking to avoid having to restart the server for an update).

I know all these things are possible, I'm just trying to find some good resources for reference. All the OSGi tutorials I'm finding seem to be too simplistic. If anyone here can guide me in the right direction on any or all of the items I'm looking for, it would be much appreciated. Also, this is my first post, so I'll take any comments/criticisms about the content of my post. Thanks!

答:
Any developer wants to create a killer application with a lot of features. But I learned from lean start-up methodology that you can take it easy. First create an application with minimal functionality, launch the first version of application and wait for feedback.

If your application has success and the code increases that it's clear that you CAN need a plugin framework to let another programmers to extend you application or for a better code organisation. In this step you choose a library that resolves your immediately needs that doesn't has a big learning curve.

What I want to say it's that it's good to think big but do it step by step.

In my applications I used a tiny java library PF4J created by me. No xml, only java code.

From my point of view OSGi is OK, it's a standard, it's powerful but it's too complex for small and medium application and for this reasons I don't recommend it for what you want to achieve.


答:
In OOP, a constructor is a function or language construct that creates and initializes a new object ('constructs' the object), and a destructor is its dual, a function or language construct that cleans up after the object (by releasing any resources it holds) and deletes it.

However, since Haskell (unlike, say, C++) has garbage collection and doesn't support mutable state or other side effects (at least not directly), there is absolutely no reason for a destructor notion in the OOP sense. Also, Haskell constructors, unlike OOP constructors, have more applications than just object creation; they are also heavily used in pattern matching (see below for an example).

In your code example, 'unwrap' is a record field, and depending on how it is used, I might refer to it as an accessor, or maybe even a getter (although the latter is also used in a lens context, so it might actually be a bit confusing).

I have never heard the term 'destructor' (or 'deconstructor') used in a Haskell context myself; as Andres F. notes, however, it is sometimes used to refer to a function that undoes the wrapping introduced by a constructor. To my understanding, a record getter may serve as a destructor, but so could regular functions, provided that they get a value back out of a more complex data type. Examples include maybe and either from the Prelude.

Note that unwrap, in your example, can be several things:

a function (just like any other): you can, for example, do map unwrap [ Wrap 23, Wrap 42 ]; this usage is roughly equivalent to a getter method in OOP.

a record field specifier in a record construction: let w = Wrap { unwrap = 23 }

a record field specifier in a record update: let w' = w { unwrap = 23 }; this is similar to setter methods in OOP (if you squeeze a lot).

a record field specifier in pattern matching: f Wrap { unwrap = a } = a

It's probably best to think of Haskell constructors as something altogether different from OOP constructors. I suggest you (re-)read a good book on the Haskell programming language for a better understanding - "Real World Haskell" is really good, and I've heard good things about "Learn You A Haskell". Both should have good explanations about constructors and record syntax in particular.


问:
Count function on tree structure (non-binary)
I am implementing a tree Data structure in c# based (largely on Dan Vanderboom's Generic implementation). I am now considering approach on handling a Count property which Dan does not implement.

The obvious and easy way would be to use a recursive call which Traverses the tree happily adding up nodes (or iteratively traversing the tree with a Queue and counting nodes if you prefer). It just  seems expensive. (I also may want to lazy load some of my nodes down the road).

I could maintain a count at the root node.  All children would traverse up to and/or hold a reference to the root, and update a internally settable count property on changes. This would push the iteration problem to when ever I want to break off a branch or clear all children below a given node. Generally less expensive, and puts the heavy lifting what I think will be less frequently called functions.

Seems a little brute force, and that usually means exception cases I haven't thought of yet, or bugs if you prefer.

Does anyone have an example of an implementation which keeps a count for an Unbalanced and/or non-binary tree structure rather than counting on the fly?  Don't worry about the lazy load, or language. I am sure I can adjust the example to fit my specific needs.

EDIT: I am curious about an example, rather than instructions or discussion. I know this is not technically difficult...

答:
You seem to have answered you own question. Have each node hold the count of its descendents plus one (itself). Every time you remove a node you decrement each count on the path back to the root. When inserting you instead increment each count on that path. This way each node contains the total number of nodes in its sub-tree. This will work fine for n-ary trees.

You can even perform the increment/decrement on the way down the tree if you are sure that the node you are inserting/deleting doesn't/does exist.

EDIT: Removing a node in the middle of the tree. Say you have a tree (labeled with the counts):

```<code>     |
    A(a)
   /   \
 B(b)  C(c)
</code>```

Let's say you delete A and the rules say B should move up to fill it's place. As we said before you would decrement the counts on the path to the root, but you also need to update B's count as it is the new root of the subtree. You have to add C's count to B's:

```<code>     |
   B(b+c)
  /     \
...    C(c)
</code>```

Body:
You seem to have answered you own question. Have each node hold the count of its descendents plus one (itself). Every time you remove a node you decrement each count on the path back to the root. When inserting you instead increment each count on that path. This way each node contains the total number of nodes in its sub-tree. This will work fine for n-ary trees.

You can even perform the increment/decrement on the way down the tree if you are sure that the node you are inserting/deleting doesn't/does exist.

EDIT: Removing a node in the middle of the tree. Say you have a tree (labeled with the counts):

     |
    A(a)
   /   \
 B(b)  C(c)

Let's say you delete A and the rules say B should move up to fill it's place. As we said before you would decrement the counts on the path to the root, but you also need to update B's count as it is the new root of the subtree. You have to add C's count to B's:

     |
   B(b+c)
  /     \
...    C(c)


答:
I think your problem is that you're automatically assuming a getter for each injected property.

Auto-properties with private setters are for types where you have

```<code>public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person (string name, int age)
    {
        Name = name;
        Age = age;
    }
}
</code>```

and very little logic. This means it doesn't matter if you can, technically speaking, set your auto-properties outside of the constructor. You probably won't. And, as far as an external class goes, you're still immutable.

But you don't use DI to generate objects like this one.

You use DI to inject services that you apply logic to, like this:

```<code>public Foo : IFoo
{
    private IBar _bar;
    private IGrommit _grommit;

    public Foo(IBar bar, IGrommit grommit)
    {
        _bar = bar;
        _grommit = grommit;
    }

    public string GrommitMyBarForAName()
    {
        return _grommit.DoStuff(bar).Name;
    }
}
</code>```

In these cases, you should not automatically add an accessor for _bar, just because you can. You don't want to give public access to it, not even readonly.

There will be cases when you feel you have to but, in those cases, you should first reconsider your design. It's probably wrong.

If you're absolutely positive that you should, then add a standard accessor, but this should not be a common enough situation that you feel a need to complain that there should be a syntax to allow you to have an auto-property for it.

Title: DI and hypothetical readonly setters in C#

Body:
Sometimes I would like to declare a property like this:

```<code>public string Name { get; readonly set; }
</code>```

I am wondering if anyone sees a reason why such a syntax shouldn't exist. I believe that because it is a subset of "get; private set;", it could only make code more robust.

My feeling is that such setters would be extremely DI friendly, but of course I'm more interested in hearing your opinions than my own, so what do you think?

I am aware of 'public readonly' fields, but those are not interface friendly so I don't even consider them. That said, I don't mind if you bring them up into the discussion

Edit

I realize reading the comments that perhaps my idea is a little confusing. The ultimate purpose of this new syntax would be to have an automatic property syntax that specifies that the backing private field should be readonly. Basically declaring a property using my hypothetical syntax

```<code>public string Name { get; readonly set; }
</code>```

would be interpreted by C# as:

```<code>private readonly string name;
public string Name
{
    get
    {
        return this.name;
    }
}
</code>```

And the reason I say this would be DI friendly is because when we rely heavily on constructor injection, I believe it is good practice to declare our constructor injected fields as readonly.

Body:
I think your problem is that you're automatically assuming a getter for each injected property.

Auto-properties with private setters are for types where you have

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person (string name, int age)
    {
        Name = name;
        Age = age;
    }
}

and very little logic. This means it doesn't matter if you can, technically speaking, set your auto-properties outside of the constructor. You probably won't. And, as far as an external class goes, you're still immutable.

But you don't use DI to generate objects like this one.

You use DI to inject services that you apply logic to, like this:

public Foo : IFoo
{
    private IBar _bar;
    private IGrommit _grommit;

    public Foo(IBar bar, IGrommit grommit)
    {
        _bar = bar;
        _grommit = grommit;
    }

    public string GrommitMyBarForAName()
    {
        return _grommit.DoStuff(bar).Name;
    }
}

In these cases, you should not automatically add an accessor for _bar, just because you can. You don't want to give public access to it, not even readonly.

There will be cases when you feel you have to but, in those cases, you should first reconsider your design. It's probably wrong.

If you're absolutely positive that you should, then add a standard accessor, but this should not be a common enough situation that you feel a need to complain that there should be a syntax to allow you to have an auto-property for it.


问:
What to choose API based server or Socket based server for data driven application
I am working on a project which has a Desktop Application for MAC/COCOA, a native application for iPhone another native application in iPad. All the application do almost same thing. The applications are data driven applications. Every communication to server is made via a restful API developed in PHP.
When a user logs in a lot of data is fetched from server. And to remain in sync with server polling is done.
As there are lot of data to poll it makes application slower and un-reliable.

A possible solution that comes into my mind is to use Socket based server.

My question is that will it reasonably improve the performance?
And which technology (of sockets) will be good as a server side solution for data driven application? I have heard a lot about Node.js. Please give your suggestions.

答:
Do you want to replace the REST based PHP API, or just complement it?

You mention performance as a goal, but we really need to know more about your use case to recommend any specific technology. Are you transmitting complex data structures, and is there heavy server load? In case of complex data structures, you could try out Protocol Buffers from Google. If your data structures are less complex and you don't need i.e. binary support, you can use XML or JSON, depending on if you need validation.

Since you already know about Node.js, you must also know its strengths. They are: Asynchronous I/O mainly so that you can serve more clients. But performance is not only the number of clients you can serve per server. It is also a question of how hard each client strains the server. If you have a lot of number crunching going on, it might make sense to write the server in C++ or Java, languages that typically number crunch more efficiently than JavaScript.

If the performance issues you are having are solely based on network transfer speed, of course you won't gain anything by using Node.js, since pretty much every server will saturate the available bandwidth.

Since you mention that you want to stay in sync with the server after pooling is done, you definitely need some kind of socket library if your communication is birectional and/or you want to avoid pooling.


答:
I would suggest to keep a count in the same class that you deifne your Insert and Remove functions.</p>

```<code>public class TreeStruct{
    private int _count;
    private Object rootNode;

    public int count{ return count;}

    public void Insert(object obj){
        //insert object to tree
        _count++
    }

    public void Remove(object obj){
        //remove object from tree
        _count --;
    }
}
</code>```

Title: Count function on tree structure (non-binary)

Body:
I am implementing a tree Data structure in c# based (largely on Dan Vanderboom's Generic implementation). I am now considering approach on handling a Count property which Dan does not implement.

The obvious and easy way would be to use a recursive call which Traverses the tree happily adding up nodes (or iteratively traversing the tree with a Queue and counting nodes if you prefer). It just  seems expensive. (I also may want to lazy load some of my nodes down the road).

I could maintain a count at the root node.  All children would traverse up to and/or hold a reference to the root, and update a internally settable count property on changes. This would push the iteration problem to when ever I want to break off a branch or clear all children below a given node. Generally less expensive, and puts the heavy lifting what I think will be less frequently called functions.

Seems a little brute force, and that usually means exception cases I haven't thought of yet, or bugs if you prefer.

Does anyone have an example of an implementation which keeps a count for an Unbalanced and/or non-binary tree structure rather than counting on the fly?  Don't worry about the lazy load, or language. I am sure I can adjust the example to fit my specific needs.

EDIT: I am curious about an example, rather than instructions or discussion. I know this is not technically difficult...

Body:
I would suggest to keep a count in the same class that you deifne your Insert and Remove functions.

public class TreeStruct{
    private int _count;
    private Object rootNode;

    public int count{ return count;}

    public void Insert(object obj){
        //insert object to tree
        _count++
    }

    public void Remove(object obj){
        //remove object from tree
        _count --;
    }
}


答: There are several terms for the concept. Deconstructing is what I believe is common in Haskell circles, it is what Real World Haskell calls it.  I believe the term destructuring(or destructuring bind) is common in Lisp circles.</p>


问:
Setting source IP with posix sockets
Is it possible for an application to request a socket (tcp) and have it set the source address without using raw sockets? (the addresses would be bound to the interfaces. [no spoofing]).
This would be a tcp client connection, not bind()ing to a specified address.</p>

答: No, it is not possible without bind or raw sockets.

Title: Setting source IP with posix sockets


问:
How far should an entity take care of its properties values by itself?
Let's consider the following example of a class, which is an entity that I'm using through Entity Framework.

```<code>- InvoiceHeader
    - BilledAmount (property, decimal)
    - PaidAmount (property, decimal)
    - Balance (property, decimal)
</code>```

I'm trying to find the best approach to keep Balance updated, based on the values of the two other properties (BilledAmount and PaidAmount).

I'm torn between two practices here:

Updating the balance amount every time BilledAmount and PaidAmount are updated (through their setters)

Having a UpdateBalance() method that the callers would run on the object when appropriate.

I am aware that I can just calculate the Balance in its getter.
However, it isn't really possible because this is an entity field that needs to be saved back to the database, where it has an actual column, and where the calculated amount should be persisted to.

My other worry about the automatically updating approach is that the calculated values might be a little bit different from what was originally saved to the database, due to rounding values (an older version of the software, was using floats, but now decimals).
So, loading, let's say 2000 entities from the database could change their status and make the ORM believe that they have changed and be persisted back to the database the next time the SaveChanges() method is called on the context.

It would trigger a mass of updates that I am not really interested in, or could cause problems, if the calculation methods changed (the entities fetched would lose their old values to be replaced by freshly recalculated ones, simply by being loaded).

Then, let's take the example even further.

Each invoice has some related invoice details, which also have BilledAmount, PaidAmount and Balance (I'm simplifying my actual business case for the sake of the example, so let's assume the customer can pay each item of the invoice separately rather than as a whole).

If we consider the entity should take care of itself, any change of the child details should cause the Invoice totals to change as well.

In a fully automated approach, a simple implementation would be looping through each detail of the invoice to recalculate the header totals, every time one the property changes.
It probably would be fine for just a record, but if a lot of entities were fetched at once, it could create a significant overhead, as it would perform this process every time a new invoice detail record is fetched.
Possibly worse, if the details are not already loaded, it could cause the ORM to lazy-load them, just to recalculate the balances.

So far, I went with the Update() method-way, mainly for the reasons I explained above, but I wonder if it was right.
I'm noticing I have to keep calling these methods quite often and at different places in my code and it is potential source of bugs.

It also has a detrimental effect on data-binding because when the properties of the detail or header changes, the other properties are left out of date and the method has no way to be called.

What is the recommended approach in this case?

答:
That's what I would call data duplication:

If c = a + b, then why do you need to store c? unless the computation is expensive, of course, but then it wouldn't be automatic.

Keeping such numbers in sync becomes a nightmare, involving:

Unwanted amount of updates

Complexification of the UI eventing

Extra db/network load

And some more.

My solution: don't do it. Recompute it when you want to display it, use Binding mechanisms to do so (available in WPF, SL and Javascript AFAIK).

OwnerDisplayName: Kharlos Dominguez


问:
How can I view github tasks which are not assigned to a person?
On the main Issues page, you can click Everyone's Issues, or Assigned to me.

If you want to view the tasks assigned to a particular person, you can click the search icon, and on the left choose the assigned to anyone drop-down, then choose from a list of assignees.

But how to I list all the items which are not assigned to anyone?

答:
Use the API: http://developer.github.com/v3/issues/

For example, to get all issues on kripken/emscripten with no assignee:

```<code>curl "https://api.github.com/repos/kripken/emscripten/issues?assignee=none"
</code>```

Body:
Use the API: http://developer.github.com/v3/issues/

For example, to get all issues on kripken/emscripten with no assignee:

curl "https://api.github.com/repos/kripken/emscripten/issues?assignee=none"


问:
What is the proper way to create a cross-fade effect?
When creating an image slider, using a cross fade is one of more popular effects. Various sliders use differing techniques to create such an effect. Major techniques I've found so far are:

Method 1: Use an overlay and underlay
 and fade in and out each other's visibility.

Method 2: Create a
 matching the exact size of the slider during initialization, play with its z-index property, and then fade each other.

Using method-1, it needs creating two unneeded and over exploited block elements most commonly a div. First the background property is applied to the underlayed-div then the overlayed-div is faded out and subsequently changed in z-index property to be positioned lower that other one.

Using method-2, it creates only one extra div and now container's background is changed and the overlay div is faded out. Implementing this effect now limits the transition effect that can be build (but this is not the question in hand).

The reason why I believe this could be better is because extra elements will always have to be added to give the effect. Due to this reason, creating effects like that of nivo-slider requires creating 12 to 15+ divs to give the effect.

Adding up to number of elements to create the element does not seem to be the right way.

Are the methods I mentioned above used so much, because there aren't any other ways? There has to be better ways that to create the cross-fade effect.

So my question is simple,
Is there a better way to create this effect? If yes, What are they?

答:
The truth of the matter is, the web wasn't designed for that.  It wasn't designed for 90% of what it does today.  Hacks and web development are closely tied.  The best solution is almost always the one that works.

The web is moving towards standardizing the dynamic nature of what's already out there (HTML5, canvas in your case like thorston mentioned) but it's not there yet and won't be for a long time.

Is there a better way to create this effect?  Yes, a video editing software would be vastly superior and easier for what you're trying to do.  But you are trying to make a website not a video, albeit with properties analogous to video, so not really.  Go with what works, even if it isn't 100% intuitive.


问:
Does software rot refer primarily to performance, or to messy code?
Wikipedia's definition of software rot focuses on the performance of the software. This is a different usage than I am used to; I had thought of it much more in terms of the cleanliness and design of the code—in terms of the code's having all the standard quality characteristics: readability, maintainability, etc. Now, performance is likely to go down when the code becomes unreadable, because no one knows what is going on. But does the term software rot have special reference to performance? or am I right in thinking it refers to the cleanliness of the code? or is this perhaps a case of multiple senses of the term being in common usage—from the user's perspective, it has do with performance; but for the software craftsman, it has to do more specifically with how the code reads?

答:
The term is not performance related, at least not anywhere I have seen it used.

It is specifically about code that is not maintained well and becomes... dirty... rotten. It is about code whose design has not been updated as changes were made and is difficult to read and understand.


答:
Lets face it. "Software rot" is not a well-defined technical concept.  It is more of a pejorative description of what happens when software is poorly maintained.

The Wikipedia page represents one view, but there are clearly alternative views.  And you could say that the different views reflect the different priorities and concerns of the person holding the views:

Someone who is focussed on making software fast will be more inclined to look for evidence of "software rot" in performance.

Someone who is focussed on design / architecture (e.g. because they need to add new functionality or fix functionality bugs), will see "software rot" from that perspective.

And, it is not really useful to say whose perspective is more right.  (It is kind of like arguing whether turquoise is more green or more blue.)

Title: Does software rot refer primarily to performance, or to messy code?

Body: Wikipedia's definition of software rot focuses on the performance of the software. This is a different usage than I am used to; I had thought of it much more in terms of the cleanliness and design of the code—in terms of the code's having all the standard quality characteristics: readability, maintainability, etc. Now, performance is likely to go down when the code becomes unreadable, because no one knows what is going on. But does the term software rot have special reference to performance? or am I right in thinking it refers to the cleanliness of the code? or is this perhaps a case of multiple senses of the term being in common usage—from the user's perspective, it has do with performance; but for the software craftsman, it has to do more specifically with how the code reads?


答: I'd say that the term "software rot" refers generally to suitability for the task at hand. Software may become less suitable for its intended task due to layer upon layer of bug fixes, new features, and minor tweaks. Taken together, those can adversely affect both maintainability and performance. Also, the needs of the organization will likely change over time, and the software may be forced into roles that it was never really designed for. All these factors result in the software becoming less suitable to the organization's needs, and that can happen even with a concerted effort to maintain the software.</p>


答:
Wikipedia says that software rot and code rot are the same.  I disagree.

Code rot is the gradual loss of readability and maintainability as more and more changes are made to the code.

Software rot is the gradual loss of performance as software is moved from one environment emulator to another.  One example is all of the Data General PDP software running on emulators. Actually, it's the environment that's rotting, not the software.


问:
How important is it for a programmer to know how to implement a QuickSort/MergeSort algorithm from memory?
I was reviewing my notes and stumbled across the implementation of different sorting algorithms.

As I attempted to make sense of the implementation of QuickSort and MergeSort, it occurred to me that although I do programming for a living and consider myself decent at what I do, I have neither the photographic memory nor the sheer brainpower to implement those algorithms without relying on my notes. All I remembered is that some of those algorithms are stable and some are not. Some take O(nlog(n)) or O(n^2) time to complete. Some use more memory than others...

I'd feel like I don't deserve this kind of job if it weren't because my position doesn't require that I use any sorting algorithm other than those found in standard APIs. I mean, how many of you have a programming position where it actually is essential that you can remember or come up with this kind of stuff on your own?

答:
The exact implementation is not very important. But the principle behind mergesort / quicksort  - recursion, partitioning etc, are very basic one and every programmer should understand. These algorithm are actually very simple to describe in words once you understand.

It's not really a problem of whether you can look it up or whether you can google it, it is whether programmer understand these problem solving techniques and able to apply to other situations.


问:
How to start competitive programming?
I have been practicing coding for a while, but the problem is that it takes me a lot of time to write a solution for the problems. I want to ask if competitive programming can help me in improving this.

If yes, then how should I start and from which web sites could I use (like TopCoder)? I obviously won't be able to solve very hard problems for now. What should I do?

If no, what else should I do?

I also have another problem that I want to learn coding but the thing is that I feel that I am not very good at it. What should I do? It's like bugging me from inside.

I know some people may not find this question informative but please at least allow me to get an answer.

答:
As a beginning programmer, you should be much more concerned with the quality of your code then the speed of writing it.  You should be working on projects on your own to expand your skills.  You could follow that up with reviewing open source projects to see how others write code and maybe start contributing to an a open source project.

In my 25+ years of developing code on various platforms and business domains, I have never found a case where the speed of my code writing was more important than the quality and stability of my code.

Title: How to start competitive programming?


答:
[can] competitive programming help me in improving [the speed]?

Yes, it can, and given sufficient time, it certainly will. However, speed is not the most important skill that you are going to improve. From my experience of participating with TopCoder for 10+ years, the most important skill that you are going to take from competitive programming is an ability to write simple code snippets correctly the first time, without using a debugger.

How should I start and from what site like TopCoder?

Use practice rooms for Division 2. Level 1 of Div 2 are typically "typing contests", in the sense that you figure out a solution right away, so your task becomes coding it as quickly as possible. Most real-life assignments are like that. You will quickly realize that debugger is the biggest "time drain", so you will naturally attempt to complete your code without debugging it. This will be frustrating in the beginning, but it will improve with time. It will take a few hundred level-1 problems to get good at it, so don't give up.

Debugging in your head is the skill that is going to help you in your real job: while the coding speed is not important, an ability to write correct code snippets without debugging will help you make a transition from good to outstanding.

Title: How to start competitive programming?

Body:
I have been practicing coding for a while, but the problem is that it takes me a lot of time to write a solution for the problems. I want to ask if competitive programming can help me in improving this.

If yes, then how should I start and from which web sites could I use (like TopCoder)? I obviously won't be able to solve very hard problems for now. What should I do?

If no, what else should I do?

I also have another problem that I want to learn coding but the thing is that I feel that I am not very good at it. What should I do? It's like bugging me from inside.

I know some people may not find this question informative but please at least allow me to get an answer.


问:
Why am I seeing so many instantiable classes without state?
I'm seeing a lot of instantiable classes in the C++ and Java world that don't have any state.

I really can't figure out why people do that, they could just use a namespace with free functions in C++, or a class with a private constructor and only static methods in Java.

The only benefit I can think of is that you don't have to change most of your code if you later decide that you want a different implementation in certain situations. But isn't that a case of premature design? It could be turned into a class later, when/if it becomes appropriate.

Am I getting this wrong? Is it not OOP if I don't put everything into objects (i.e. instantiated classes)? Then why are there so many utility namespaces and classes in the standard libraries of C++ and Java?

Update:
I've certainly seen a lot examples of this in my previous jobs, but I'm  struggling to find open source examples, so maybe it's not that common after all. Still, I'm wondering why people do it, and how common it is.

答:
In object oriented languages where classes are not objects, you can do a lot more with an object than a class.

You can pass an object as a parameter, you can substitute a type compatible object, you can implement an interface (I imagine there are languages in which classes are objects but you can do some of these things, but in any case...).  All of these things are pretty important so the default decision is usually to make a class instantiable.

For some classes the capabilities granted by instantiation seem unlikely to be needed.  You probably won't need to swap out one implementation of Cosine for another, for example.  It turns out it's mostly utility functions that don't need these capabilities, so it's mostly utility functions that have classes that aren't instantiable.


问:
Plan variable and call dependencies
I'd like to write down the design of my program to understand the dependencies and calls better. I know there are class diagrams which show inheritance and attribute variables.

However I'd also like to document the input parameters to method functions and in particular which calls the methods function executes inside (e.g. on the input parameters).

Also sometimes it might be useful to show how actual objects are connected (if there is a standard structure).

This way I can have a better understanding of the modules and design before starting to program. Can you suggest a method to do this software design? It should be one-to-one to programming code structure so that I really notice all quirks beforehand (instead of high-level design where thing are hard to implement without further work).
Maybe some special diagram or tool or a combination?

It is static dependency and call design rather than time dependent execution monitoring.

(I use Python if you have any specialized recommendations).

答:
However I'd also like to document the input parameters to method functions and in particular which calls the methods function executes inside (e.g. on the input parameters).

You're either solving the wrong problem or beginning at the wrong level of abstraction.

Consider the following quote:

"Bad programmers worry about the code. Good programmers worry about data structures and their relationships."

...And ask yourself, "Why do I need to worry about all of the methods and all of the input parameters in an application?"

Title: Plan variable and call dependencies


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm from Sweden and both me and my colleagues code in English. I think this is a good thing, but sometimes it can be difficult to come up with English equivalents to customer specific terms and expressions.

My reasons for writing code in English:

Allmost all programming languages I have ever used have been written in English (mixing languages would make the code harder to read for me)

Most popular frameworks and third party extension are written in English (again, mixing languages would only be a distraction)

Swedish characters (åäö) are usually not allowed when naming variables and functions

If the other team members are from different countries we can still collaborate

If I need support from a platform vendor it is is much easier for them to help me if they can understand my code

It is easier to outsource support


问:
Java or C++ for university CS courses?
I'm in the throes of getting myself enrolled in school to get a CS degree. The school I am looking at actually offers both Java- and C++-based for the introductory software development courses (object-oriented programming, design patterns, that sort of thing). It is student's choice which track to follow, but there is only time to follow one.

Knowing what you know now, if you had the choice, would you lay down your CS curriculum foundation in Java or C++?

My current debate currently looks like this:

A good friend (who has a PhD in AI) is touting Java as the better choice regardless of what I do, if only to open up more job opportunities later, though he might be biased since all of his work has been in Java (he loves it). I live in the Boston, MA, USA area and I see an equal amount of Java and C work.

On the flip side, although I haven't entirely yet settled on what I want to do with the degree when I'm done, my preference would be to develop for the Mac, which I am doing now albeit in a limited capacity. To that end, I'm getting some limited exposure to C++ already, but I've had none with Java, and looking at my projects at my day job I don't see a need to use it anytime soon, "soon" measured by at least two years.

I probably should note that I'm an adult going back to school after 20 years (I currently have no degree of any kind) so I'm looking to maximize the opportunity and time spent as best I can. I'm kind of leaning towards C++ but I'm still ambivalent, and some outside, objective advice would help here.

Or I could just be thinking too hard about it.

UPDATE: It turns out the language selection wasn't so clear cut as I originally surmised. While a couple of core courses focused on Java, some of the other core courses work in primarily C and Java, but also a few others thrown in for good measure. In fact, my rest of my semester is going to be in Objective-C after spending time in Java and Javascript. Last semester was C, Javascript, and PHP, plus a few others thrown in as assignments required. Since things were pretty much split down the middle overall, and I am still getting answers to this, I am now trying to work my curriculum such that I meet all of the requirements for the degree but to absorb as many languages as I can reasonably handle. So far, my grades have not suffered trying to do this.

答:
I'd personally go with C++ as it will give you insights into how parts of Java work under the hood (Pointers for example).  Moving to Java from C++ is fairly trivial, whereas moving the other way around is arguably more difficult.

The truly difficult thing about the Java eco-system is it's vast number of frameworks, libraries etc - they're unlikely to cover all of that at University anyhow.

At the end of the day it's not going to matter that much what language you choose, as long as you learn the principles.

My JUG is going to kill me for endorsing C++ ;-)

Title: Java or C++ for university CS courses?


问:
Can WinRT really be used at just the boundaries?
Microsoft (chiefly, Herb Sutter) recommends when using WinRT with C++/CX to keep WinRT at the boundaries of the application and keep the core of the application written in standard ISO C++.

I've been writing an application which I would like to leave portable, so my core functionality was written in standard C++, and I am now attempting to write a Metro-style front end for it using C++/CX. I've had a bit of a problem with this approach, however. For example, if I want to push a vector of user-defined C++ types to a XAML ListView control, I have to wrap my user-defined type in a WinRT ref/value type for it to be stored in a Vector^. With this approach, I'm inevitably left with wrapping a large portion of my C++ classes with WinRT classes.

This is the first time I've tried to write a portable native application in C++. Is it really practical to keep WinRT along the boundaries like this? How else could this type of portable core with a platform-specific boundary be handled?

答:
You don't have to use C++/CX, instead you can use the WRL (Windows Runtime Library) which is like the old ATL templates, not the 'pretend' C++ that is C++/CX. Its the "low level" approach from MS to consuming WinRT objects and is completely standard C++ like Grandad used to write!

It might not be as "nice" as C++/CX but that's a matter of opinion - my personal opinion is that C++/CX is the 3rd attempt at an extended C++, and is a 3rd failure. Ignore it and hope it goes the same way as the other 2 incarnations.


问:
Why should I declare a class as an abstract class?
I know the syntax, rules applied to abstract class and I want know usage of an abstract class

Abstract class can not be instantiated directly but can be extended by other class

What is the advantage of doing so?

How it is different from an Interface?

I know that one class can implement multiple interfaces but can only extend one abstract class. Is that only difference between an interface and an abstract class?

I am aware about usage of an Interface. I have learned that from Event delegation model of AWT in Java.

In which situations I should declare class as an abstract class? What is benefits of that?

答:
There is chance too few methods are common to some class (business logic). And remaining methods are different. In that kind of scenarios you can implement all the common methods in one class, and declare the remaining as abstract. Then you should declare the class as abstract.

Sometimes you don't allow to create the object to the class directly. That kind of class you need to declare the class as abstract.


问:
What's the proper term for a function inverse to a constructor - to unwrap a value from a data type?

Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.)

Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell):

```<code>newtype Wrap = Wrap { unwrap :: Int }
</code>```

Here Wrap is the constructor and unwrap is what?

The questions are:

How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term?

And to clarify, is this/other terminology applicable to other functional languages, or is it used just in the Haskell?

Perhaps also, is there any terminology for this in general, in non-functional languages?

I've seen both terms, for example:

... Most often, one supplies smart constructors and destructors for these to ease working with them. ...

at Haskell wiki, or

... The general theme here is to fuse constructor - deconstructor pairs like ...

at Haskell wikibook (here it's probably meant in a bit more general sense), or

```<code>newtype DList a = DL { unDL :: [a] -> [a] }
</code>```

The unDL function is our deconstructor, which removes the DL constructor. ...

in The Real World Haskell.

答: Since there doesn't seem to be any cross-language convention, I usually call them extractors, because that's the term that Scala uses for that general notion, and because it's not likely to be confused with any existing usage.


答: I had always thought of software rot as a condition that occurs when you don't use software for a period of time.  Somehow, the software morphs into a state where it is unbuildable.  Then when you get it to a point where you can build it, it doesn't work with the inputs and outputs like it previously did.  It's almost as if the code actually degraded in form even though it's stored digitally.


问:
How to find out if a company has insane policies
When interviewing for a job, is there a delicate yet accurate way to find out if they have insane policies, like "no open source", or "no installing software without permission", "not upgrading software until it's about to lose support", or "no visiting blogs"?</p>

答:
I don't think you can be too subtle, you can perhaps ask:

"The last place I worked at utilised some open source libraries - I found that useful as I was able to delve in and fix problems directly instead of waiting for a Vendor to get back to me.  I can also understand that there can be legal concerns on using such libraries, do you have a  policy here?"

"I assume that our machines are looked after by some sort of tech support?  What's the process I'd have to go through if I had to install (for example) a trusted free text editor that supports Hex encoding?"

"I'm really passionate about my craft and I keep up to date with the luminaries in my field - what's the policy on visiting work related websites such as Oracle tech blogs etc?"


问:
Making simple forms in web applications
How do you work with forms in your web applications?

I am not talking about RESTful applications, I don't want to build heavy front-end using frameworks like Backbone.

For example, I need to add "contact us" form. I need to check data which was filled by user and tell him that his data was sent.
Requirements:

I want to use AJAX.

I want to validate form on back-end side and don't want to duplicate the same code on front-end side.

I have my own solution, but it doesn't satisfy me. I make an AJAX request with serialized data on form submit and get response. The next is checking "Content-type" header.

html -> It means that errors with filling form are exists and response html is form with error labels. -> I will replace my form with response html.

json and response.error_code == 0 -> It means that form was successfully submited. -> I will show user notification about success.

json and response.error_code != 0 -> Something was broken on back-end (like connection with database).

other - I display the following message :

We have been notified and have started to work with that problem. Please, try it later.

The problem of that way is that I can't use it with forms that upload file.

What is your practise? What libraries and principles do you use?

答:
First of all, you have to make sure that your form submission will work without AJAX. A lot of people browse the web with Javascript disabled, rendering useless any AJAX request (they won't work).

Then when you are satisfied with your form submission and validation, you can start to add fancy things like AJAX. jQuery (among others) is an awesome library that makes it very easy to write cross-browser compatible javascript. You might want to look into it as it supports AJAX and makes it very easy to work with.

What you have defined as your current mechanism seems to be ok. Maybe you can explain what you don't like about it?

Title: Making simple forms in web applications