问:
Learning to Program in Assembly - Useful Resources
Following on from a previous thread, it has got me interested in learning a little about Assembly programming.  Not so much for wanting to program useful apps in, just to get a feel for low level programming to better understand what is happening.

Can anybody recommend any books or online resources for beginners?

Thanks.

答:
Recommended Book : The Art of Assembly Language Programming.

I also liked this site. Nice introduction to assembly programming!
I used this site as a reference while studying for my Microprocessors and Microcontrollers course.


问:
Architecture: Are form default values considered business logic and where should the logic to calculate them be placed?
An example of default form values on a search form might be:

Start Date - Today

End Date   - The last day of the next month

Obviously, these are fairly simple examples, but default values can get a lot more complex and potentially rely on "real business logic" (from an entity).

A search form is a good example because it does not have a corresponding entity.

So what is a good way to encapsulate complex default value logic? Perhaps the view model? Maybe create a new business object? Or should it just go in the view/controller responsible for rendering the form?

This is an ASP.NET Webforms application and my particular problem is where to put the logic to decide how the feed back regarding an event is categorized.

答:
StartDate and EndDate of what?.... the school year? Ok:

```<code>public class SchoolYear {
     StartDate = DateTime.Now;
     EndDate = new DateTime (2016, 6, 23);
}
</code>```

Object Oriented Programming is about, well, objects: Put properties in a class to appropriately describe/define what it is. Write methods against those properties to describe/define what it does.

As for "complex default logic". "Complex" or "default" notwithstanding, put the logic with the properties it goes with, hence both in an appropriate class. If "complexity" means a need for different class/objects to interact, OK, but each class/object is responsible for doing it's own thing.

A School Year certainly will not have the teaching staff defined in it, however a Teacher may well have his/her Calendar initialized with the SchoolYear.StartDate.

ContentLicense: CC BY-SA 3.0

Body:
StartDate and EndDate of what?.... the school year? Ok:

public class SchoolYear {
     StartDate = DateTime.Now;
     EndDate = new DateTime (2016, 6, 23);
}

Object Oriented Programming is about, well, objects: Put properties in a class to appropriately describe/define what it is. Write methods against those properties to describe/define what it does.

As for "complex default logic". "Complex" or "default" notwithstanding, put the logic with the properties it goes with, hence both in an appropriate class. If "complexity" means a need for different class/objects to interact, OK, but each class/object is responsible for doing it's own thing.

A School Year certainly will not have the teaching staff defined in it, however a Teacher may well have his/her Calendar initialized with the SchoolYear.StartDate.


问:
Why have many programmers moved to using exception handling for input or output?
Why have many programmers moved to using exception handling for input or output? For these programmers, what is the motivation behind this decision?</p>

答:
Behavioral Economics #101: because it's the easier way.

Exceptions are, in part, an acknowledgement that error-handling is hard and while we can recover from exceptions, it's much easier not to.

Exceptions are the programmer's way of saying "I have this ideal situation that must be matched and I'll not bother spending more lines nor time handling situations that are not ."  In essence, when you do a "catch-all" type of exception handling, you're giving up:

```<code>} catch(e) {
    print("Don't even know what error it is but **there's an error**. Exit / Retry.");
}
</code>```

(Besides "catch-all" exceptions, there's also the "one-by-one" longform style which is the exception  rather than the norm but not what folks are saying when they say "exception-handling".)

For adjunct reading, see https://en.wikipedia.org/wiki/Structured_programming#Exception_handling

Body:
Behavioral Economics #101: because it's the easier way.

Exceptions are, in part, an acknowledgement that error-handling is hard and while we can recover from exceptions, it's much easier not to.

Exceptions are the programmer's way of saying "I have this ideal situation that must be matched and I'll not bother spending more lines nor time handling situations that are not ."  In essence, when you do a "catch-all" type of exception handling, you're giving up:

} catch(e) {
    print("Don't even know what error it is but **there's an error**. Exit / Retry.");
}

(Besides "catch-all" exceptions, there's also the "one-by-one" longform style which is the exception  rather than the norm but not what folks are saying when they say "exception-handling".)

For adjunct reading, see https://en.wikipedia.org/wiki/Structured_programming#Exception_handling

ContentLicense: CC BY-SA 4.0


答: I find exceptions are cleaner for code style since I can wrap the code and deal with any errors in a specific location (the catch block), as opposed to littering my code with lots of if statements (if (result == -1)), to check for error conditions.

Body: Why have many programmers moved to using exception handling for input or output? For these programmers, what is the motivation behind this decision?</p>


问:
Why is a architecture with anemic models the JavaEE standard?
I took a JavaEE course today and I was presented to the "default" JavaEE architecture, which consists mainly of Entities, Services and DTOs.
The guy presenting the course explained that it was indeed a case of anemic models, but however this was the "in facto standard JavaEE architecture".

I am new to JavaEE, but I've head some experience with other languages. The first time I read about beans as components, I thought they would be great to create a DDD-like architecture.

It sounds strange to me that a "standard architecture" has a anemic domain (I, until now, thought it was a "bad smell").

Is there any technical reason or big advantage of using this architecture? Why an architecture that defines its models to be anemic is the current standard?

I asked him and he talked about transaction context, but I have to admit I didn't understood exactly what he meant.

答:
I see this in the .NET world as well and I have so far identified a handful of reasons as to why this happens (I also do not prefer anemic data models).

Old code. People didn't know better and it's too expensive to rewrite.

Misinterpretation of the DRY principle. People want to use their objects as contracts and send them over the wire as XML/JSON and then prefer to make them into simple DTO's - and instead of using these as contracts and then translating them to real domain objects at the boundaries people go to the anemic domain model antipattern instead in order to not have two objects representing the "same" object.

The application is actually not complex enough to warrant a domain model.

Now, in 1 and 3 an anemic domain model might actually be the right choice. Having a rich domain model can be a lot of work which may not actually provide enough value given your application. Many applications, even in the JavaEE world, are just glorified CRUD-layers on top of a database. If there aren't enough domain logic, anemic domain models can actually be the correct choice.

In 2 however I'd say that it's just bad practices. If you have an application with a domain that is rich enough to warrant a domain model then you should have one. According to SRP each object should have a single responsibility, DTO's by design already have one responsibility - represent the data transfer format between your system and an external system. You should not use them for anything else. There should be a mapping layer (which in these days are much faster to write than they've ever been before since there are plenty of frameworks/libraries that can remove a lot of the busywork in writing these) that maps from the DTO to your domain objects and vice versa - and then your application should only use these domain objects to perform its intended purpose. This also gives you the chance to refactor and change your implementation independently of changing your external contract - and this is a huge gain once you're in production.

But yes. It can be a lot of extra work, and the really hard part about this is looking at your domain and asking the question "Does this domain motivate going full on DDD?". And you really shouldn't underestimate that question, it's actually a really hard one.


答:
This does not mean J2EE applications are based on skimpy models it just that you can implement any more complex model using only entities, attributes and relationships.

In the same way you can implement any control structure (for each, while, do until) using only if and goto.

There is no need for the more sophisticated concepts to be part of the implementation.

The real problem is that while DDD may look pretty on a diagram no-one has come up with an elegant way to translate these concepts to code.

I used to be a big fan of generating code from models, but, now I have many doubts. The model is now source code, which needs to be under the control of the implementer/programmer if you want the system to work and perform well, however, the designers and modelers are used to hacking the model and traditionally have no concerns about any implementation issues. In effect the model which used to be a communication tool and the interface between designers and developers has become a battleground between the designers who want an elegant and accurate description of the requirements and the developers who need a precise and often quite ugly model to generate efficient code.

Title: Why is a architecture with anemic models the JavaEE standard?

Body:
I took a JavaEE course today and I was presented to the "default" JavaEE architecture, which consists mainly of Entities, Services and DTOs.
The guy presenting the course explained that it was indeed a case of anemic models, but however this was the "in facto standard JavaEE architecture".

I am new to JavaEE, but I've head some experience with other languages. The first time I read about beans as components, I thought they would be great to create a DDD-like architecture.

It sounds strange to me that a "standard architecture" has a anemic domain (I, until now, thought it was a "bad smell").

Is there any technical reason or big advantage of using this architecture? Why an architecture that defines its models to be anemic is the current standard?

I asked him and he talked about transaction context, but I have to admit I didn't understood exactly what he meant.


问:
Using JOIN keyword or not
The following SQL queries are the same:

```<code>SELECT column1, column2
FROM table1, table2
WHERE table1.id = table2.id;

SELECT column1, column2
FROM table1 JOIN table2
ON table1.id = table2.id;
</code>```

And certainly result in the same query plans on every DBMS I've ever tried.

But every so often, I read or hear an opinion that one is definitely better
than the other. Naturally, these claims are never substantiated with an
explanation.

Where I work, the second version seems to be favored by the majority of other
devs, and so I also tend toward that style to minimize surprise.  But In my
heart, I'm really thinking the first one (since that's how I originally learned
it).

Is one of these forms objectively better than the other?  If not, what would be the reasons to use one over the other?

答:
The old style has been deprecated, you shouldn't use it.

There shouldn't even be an argument over which one is better or not. New code shouldn't use the old syntax.

Title: Using JOIN keyword or not


问:
What does mathematics have to do with programming?
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...

答:
1) As you learn programming, you will come across technical jargon(i.e., algorithm). To analyse algorithm, one has to have an idea about the nature of polynomial, logarithmic and exponential functions.

2) Based on a computer science application, one has to have an idea on discrete maths and continuous maths to write meaningful solution. One can understand more on this by going through such courses like-

---> Mathematics for Computer Science

---> Coding the Matrix: Linear Algebra through Computer Science Applications.

For a beginner, I feel dynamic typed languages like python/scheme are the first best languages for programming. Static typed languages like Java/C++ are not the best to start with. Opencourseware published from "MIT/UOC-Berkeley/Stanford" can guide you better than a regular college curriculum. I bet you!!!


答:
Because exceptions (as opposed to error code return values) cannot be ignored.

The typical code for i/o calls before exceptions, was usually written in terms of printf/scanf/gets/puts.

These functions return values that allow the developer to check for errors, but that is not trivial.

Most developers, knowing the error handling is not trivial, simply ommit it; They tend to think a typical fscanf call should look like this:

```<code>int a;
FILE *f = /* ... */;
fscanf(f, "%d", &a);
</code>```

when it should probably look like this:

```<code>switch(fscanf(f, "%d", &a))
{
case EOF:
    // todo: handle EOF case
    break;
case 0:
    puts("could not read 'a'");
    break;
case 1:
    // handle success case
    break;
}
</code>```

This code can (to a point) be extracted into a function, parametrized and (probably) hidden inside a wrapper on scanf, or a macro (both of which have downsides).

If you do not write it though, your application simply doesn't handle the errors. On the other hand, exceptions give you more useful error information, propagate naturally up the call stack and cannot be ignored (if you do, they will stop your application).

Title: Why have many programmers moved to using exception handling for input or output?

Body:
Because exceptions (as opposed to error code return values) cannot be ignored.

The typical code for i/o calls before exceptions, was usually written in terms of printf/scanf/gets/puts.

These functions return values that allow the developer to check for errors, but that is not trivial.

Most developers, knowing the error handling is not trivial, simply ommit it; They tend to think a typical fscanf call should look like this:

int a;
FILE *f = /* ... */;
fscanf(f, "%d", &a);

when it should probably look like this:

switch(fscanf(f, "%d", &a))
{
case EOF:
    // todo: handle EOF case
    break;
case 0:
    puts("could not read 'a'");
    break;
case 1:
    // handle success case
    break;
}

This code can (to a point) be extracted into a function, parametrized and (probably) hidden inside a wrapper on scanf, or a macro (both of which have downsides).

If you do not write it though, your application simply doesn't handle the errors. On the other hand, exceptions give you more useful error information, propagate naturally up the call stack and cannot be ignored (if you do, they will stop your application).


答:
Remember first you are solving problems.  Imagine a simple solution, adding two numbers.  You should do the following.

Code the successful path in a test first.  Ie. given 2, 2 return 4, given 1,2 return 3 and so on.

Write the code to pass the test.

Figure out ways to break things. Ie  Given 1 raise exception Not enough args, Given A, 3 raise exception incorrect arg type.

That is the approach I always take.  Its very TDD but it works for me and I have to say I find it quicker than any other approach.  Exceptions are clean.  And in a language like python there would be no coding required to raise most of them.. 'a'+2 raises an exception for free :-)


问:
Is Perl used for web development?
I am a web developer. I have been using php for many years and I also know lots of other programming languages so I wanted to try making websites using them.

I know Perl and want to make a website using one of its frameworks (probably Dancer) but I've heard people saying that Perl isn't used for web development anymore and that there is no point in using it for a website. I have also been told that Perl has been replaced by php. Is Perl still used for server-side web development or has it been replaced by php?

答:
PHP, in my opinion, is a much faster and better choice for the web. We also have Javascript, which is blazing fast due to it's event-based nature. However Perl is still used and there are web frameworks for Perl in web use such as Catalyst.

There is also an emergence of Python being used in the web. Frameworks such as Django, which I have had personal experience with and I find it much faster than using Perl in the web. I should also mention Flask, which is a micro web framework designed for use with Python. This can also be an option.

It's really up to yourself what framework/language you use. Personal preference. In the end, if you're comfortable with Perl, use Perl. If you're confident in Javascript or PHP, use that. If you prefer Python overall, use Django.

Hope this helps!

Title: Is Perl used for web development?


问:
What do you do when you have to work on a project using a language that you hate?
I've recently been assigned to work on a project written in PHP. I can't change that, and have no intention of really trying.

However, this can't be an uncommon scenario. How do you motivate yourself to work on the project when the code you're looking at and producing constantly makes you want to cry?

EDIT:

It should be noted that this is pretty much the only on-campus job doing anything software related available at the moment, so "just change jobs" isn't really an option :(

答:
If it's a contract or short term project, or something you'll occasionally need to support, just bite the bullet and do it, of course.

If not, then look for another job or try to explain why that language could be a hindrance on the long term (if you can).

In the first case, it's about being professional and not whining about personal preferences. In the second case, it's about being happy with your job and life.

If what you need is motivation, I'd say start trying to find bits and pieces you enjoy in the language, and start a personal pet project with it so you have a stronger incentive to learn it more in depth. Try to do things that you like with it. If you like TDD, focus on improving the test coverage, etc...

But in the end, you'll have to bite the bullet.

ContentLicense: CC BY-SA 2.5


答: Some people still use it (I'm one of them). So, it hasn't been replaced. In fact, I switched to Perl from PHP.</p>

Title: Is Perl used for web development?

Body:
I am a web developer. I have been using php for many years and I also know lots of other programming languages so I wanted to try making websites using them.

I know Perl and want to make a website using one of its frameworks (probably Dancer) but I've heard people saying that Perl isn't used for web development anymore and that there is no point in using it for a website. I have also been told that Perl has been replaced by php. Is Perl still used for server-side web development or has it been replaced by php?


问:
Python 3 PyPy implementation?
I would like to use the PyPy Python JIT Implementation using Python 3. However I can only seem to install it using Python 2. Is there even an experimental implementation of PyPy for Python 3 I can try out? Are there plans to port it to Python 3? Or do I need to keep using Python 2 for it? I've gotten quite accustomed to Python 3 and I would like to use it as much as possible.</p>

答: My friend told me that there isn't a solution for this problem. You will propably have to stick with python 2 for now unless you want to implement it yourself.</p>

Title: Python 3 PyPy implementation?


答:
Mathematics is everything to do with programming. For example, in game programming you need to use matyhs for the physics and to do more less everything. To move the player's x position in Java you would do int x = x + speed * deltaTime or int x = x - speed * deltaTime But you might say that that is basic maths so lets move onto more advanced stuff. There is an algorithm for rating chess players called the Elo Algorithm.

If you still think that this is basic then try this. How do you calculate someones age when you are given a birth day, month and year. Subtract birth year from this year and then check if month is less than this month and if it isn't subtract 1.

It isn't magic it is hard work and good mathematics.

Title: What does mathematics have to do with programming?

Body:
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...


答:
Yes it is. DuckDuckGo is one company that I know of that started with Perl as the server side language. I believe they are still using Perl primarily.

https://github.com/duckduckgo

Title: Is Perl used for web development?


答:
Because it is more readable code.

For example (i love examples):

```<code>function myFunc(someInput:String) : OutputType
  if firstErrorCondition(someInput)
    throw new FirstConditionException
  if secondErrorCondition(someInput)
    throw new SecondConditionException
  if thirdErrorCondition(someInput)
    throw new ThirdConditionException
  // do some other fancy stuff and return value eventually
</code>```

What if here we will return a value instead of throwing exceptions? Let me see:

```<code>function myFunc(someInput:String) : OutputType
  if firstErrorCondition(someInput)
    return -1
  if secondErrorCondition(someInput)
    return -2
  if thirdErrorCondition(someInput)
    return -3
  // do some other fancy stuff and return value eventually
</code>```

Okay, it is still fine. But how clients code will looks?

```<code>OutputType result = myFunc(someInput)
</code>```

That's a common part of it. Exceptions:

```<code>try {
  OutputType result = myFunc(someInput)
  //other operations
} catch (FirstErrorCondition e) {
  //do some exception handling
} catch (SecondErrorCondition e) {
  //do some magic
} catch (ThirdErrorCondition e) {
  //or just inform user that is a problem
} finally {
  //close everything and clean up after some doing
}
</code>```

As a regular developer i can see what code is responsible for each part of error/exception.

```<code>OutputType result = myFunc(someInput)
switch(result) {
  case -1:
    //meh meh
  case -2:
    //meh meh
  case -3:
    //meh meh
  default:
    //and here we have a REGULAR code
}
</code>```

Other plus of exceptions: It can be ommited in client code but it will throw exception eventually when issue occured. It will not be silient, buggy and unreadeable code.

Body:
Because it is more readable code.

For example (i love examples):

function myFunc(someInput:String) : OutputType
  if firstErrorCondition(someInput)
    throw new FirstConditionException
  if secondErrorCondition(someInput)
    throw new SecondConditionException
  if thirdErrorCondition(someInput)
    throw new ThirdConditionException
  // do some other fancy stuff and return value eventually

What if here we will return a value instead of throwing exceptions? Let me see:

function myFunc(someInput:String) : OutputType
  if firstErrorCondition(someInput)
    return -1
  if secondErrorCondition(someInput)
    return -2
  if thirdErrorCondition(someInput)
    return -3
  // do some other fancy stuff and return value eventually

Okay, it is still fine. But how clients code will looks?

OutputType result = myFunc(someInput)

That's a common part of it. Exceptions:

try {
  OutputType result = myFunc(someInput)
  //other operations
} catch (FirstErrorCondition e) {
  //do some exception handling
} catch (SecondErrorCondition e) {
  //do some magic
} catch (ThirdErrorCondition e) {
  //or just inform user that is a problem
} finally {
  //close everything and clean up after some doing
}

As a regular developer i can see what code is responsible for each part of error/exception.

OutputType result = myFunc(someInput)
switch(result) {
  case -1:
    //meh meh
  case -2:
    //meh meh
  case -3:
    //meh meh
  default:
    //and here we have a REGULAR code
}

Other plus of exceptions: It can be ommited in client code but it will throw exception eventually when issue occured. It will not be silient, buggy and unreadeable code.


问:
Is String processing more complex than number processing in programming languages?
I feel that string processing is always more complex than Numbers or mathematical processing. Are our programming languages are designed this way that mathematical operations are pretty much straight forward while string operations are mostly include few methods applied to them. Or I just have a hard time with strings.

Note:Any experience and opinion are welcomed to have idea about the way our present languages handle different types of data.

Maths in itself is the language of nature similarly Strings are our formulation of information.

答:
This depends clearly on the programming language.

For example, when using a language focused on numeric processing (like Fortran), or when using a language like C where "String" is not an inbuild data type, or at least not implemented as seemlessly and without a concat operator like "+" or "&" and garbage collection (like in Pascal), then string processing can "feel" more complex than number processing.

However, even in old languages like Basic, or modern languages like C++, C# or Java, where strings are either a core datatype, or provided as if it was one, string processing is IMHO not more complex than dealing with any other core datatype. And this is even more true today for scripting languages like Perl or Python, which provide you with a powerful collection of string tools and functions, which make string processing very easy, once you learned those tools.


答:
I agree with remaining answer on one fact : That "exceptional return" does happen and needs to be handled.

But reason why exceptions exist is not that exceptional returns exist. It is possible to have "return values" for each of the possible error states, just like C does. The reason why exceptions are preferable to C-like error handling is that it is extremely rare that error from a function will be handled in immediate caller. It is much more common for error state to bubble up the stack until it gets into place where it can be reasonably handled. Also, single "handling" code will handle different method calls.

If you are using C-like error handling, you have to create extensive amount of code to do the bubbling and aggregation of errors all the way to the handler code. This requires discipline and rigor and drastically complicates return values from methods, where every possible exceptional return needs to have it's own value). Exceptions and infrastructure around them simply do all of this for you. And while I do agree exception handling too needs some level of discipline and rigor, it needs it much less.


答:
My tip would be to endure it, only if you see the benefit of learning anything from the language and all the processes or patterns that the project uses. You might gain something from it.

The alternative, if you're risk-averse enough, is to look for another job. Which is certainly a good idea if your lack of the motivation is dragged down not only because of the technology used, but by the lack of understanding for good practices from your coworkers. There should be better things to do than to have your abilities as a developer stagnate. If you're not learning anything or gain anything from your job: get a better job.

Title: What do you do when you have to work on a project using a language that you hate?

Body:
I've recently been assigned to work on a project written in PHP. I can't change that, and have no intention of really trying.

However, this can't be an uncommon scenario. How do you motivate yourself to work on the project when the code you're looking at and producing constantly makes you want to cry?

EDIT:

It should be noted that this is pretty much the only on-campus job doing anything software related available at the moment, so "just change jobs" isn't really an option :(


答:
I think there are two aspects to this, and your question was not entirely clear which direction you want to take.

String operations from the perspective of the programmer can be easy depending on the language. Perl, for example, has regular expressions and other string operations baked into the language. It is trivial to transform or search strings. Other languages such as C require standard library calls which are cumbersome to use.

Under the covers, string operations are necessarily more complex than numerical operations. CPUs have built-in instructions for integer math. What does that even mean in the context of a string? Modifying strings: concatenation, truncating, etc. This cannot be done in the context of a single CPU instruction or register, making the implementation more complex.

Furthermore, what encoding does your string use? While integers have fairly standard semantics (so do floating point numbers), strings have many encodings (normally some form of Unicode or an ANSI code page). Code that operates on Unicode strings must necessarily be more complex than code that operates on numbers. How do you concatenate a UCS-2 string with a UTF-8 string? Compare them? These operations are possible, but there are now multiple steps involved: decode to get the Unicode code point, then compare or concatenate code points. When creating a new string in such a case, what is the new encoding?

Title: Is String processing more complex than number processing in programming languages?

Body:
I feel that string processing is always more complex than Numbers or mathematical processing. Are our programming languages are designed this way that mathematical operations are pretty much straight forward while string operations are mostly include few methods applied to them. Or I just have a hard time with strings.

Note:Any experience and opinion are welcomed to have idea about the way our present languages handle different types of data.

Maths in itself is the language of nature similarly Strings are our formulation of information.


答:
In my opinion, we use numbers, don't process them. If you are doing some kind of numerical analysis (which I do often) in any language, you'll use the numbers as input for formulas, for example. This is of course not necessarily always true, but usually true.

Strings are "processed" more.

For example, you don't make a script to put numbers to lower case, or separate them in words, or take out certain parts. At least, is not that common.

So, I would say is not a language issue. Is just that numbers and strings have different uses, and are used in a different way. My two cents.

Also, I would like to make an emphasis that I think this is usually true, but not always. There have to be people who "process" numbers the way most people do strings, but is just not that common.


答:
Its down to memory - an integer variable, for example, will occupy a set number of bytes and will never grow or shrink. A 4 byte variable remains like that and is copied around the system as-is, This means passing one into a function copies the value directly.

Strings however, occupy a variable number of bytes and this makes them fundamentally different to simply primitive types like int. If you copy a string into a function, you're really copying a reference to the start of the string rather than the entire string itself. (some programming languages then mask this to make operating on the string appear like modifying an integer, for example changes made inside the function are lost when the function exists)

This memory issue also shows in how to tell if a variable is not assigned - a string can be null for example, whereas you'd have to use a special type to represent a nullable integer (in C# for example), showing the cracks in any system that tries to manipulate strings and ints the same.

Another aspect is the complexity of strings anyway - integers do not have replace, split or trim functionality to name just 3, so strings are just more complex by their nature.

And lastly, encodings are present - how a string gets presented and what the meaning of each character is changes depending on the system or encoding used.

So yes, strings are just different to the primitive types. That's just the way things are.


问:
Encapsulating business logic that goes beyond validations in MVC
I'm pretty clear business logic goes into Models. But on this question, they refer to business logic as pretty much low level validation (if the user signs up, ask for their e-mail).

What about business logic that goes beyond validation? For example, right now I'm working on a project where the user is able to generate a quotation after a form submission. Once submitted, the application will process several data (that are not related to said form) and create some more database rows. This process involves 3 different model entities, which clearly indicates placing the code for this process inside any of those model entity classes would be "wrong".

Right now I'm using Unit of Work pattern to encapsulate CRUD operations (database and mock for testing), but I have somewhere read about some called Service pattern, that encapsulates said UnitOfWork and possibly processes like described above.

What's the pattern used for this kind of logic?

答:
It still belongs in a model, just not a view model. Since MVC assumes you are working in the UI they omit a "V"... View-Model View Controller, VMVC does not have the same ring to it.

If your application is trivial, your view model and business model can be the same thing, and that's okay. But it sounds like you application is past that point.

```<code>public class Quote
{
   public string Prerequisite1 { get; set; }
   public string Prerequisite2 { get; set; }
   public string GenerateQuote()
   {
      //Logics
   }
}

//Controller:
Quote quote = new Quote();
quote.Prerequisite1 = viewModel.TextField1;
quote.Prerequisite2 = repository.GetFromDB();
string shownToUser = quote.GenerateQuote();
repository.SaveWhatYouNeedToSave(quote);
</code>```

Body:
It still belongs in a model, just not a view model. Since MVC assumes you are working in the UI they omit a "V"... View-Model View Controller, VMVC does not have the same ring to it.

If your application is trivial, your view model and business model can be the same thing, and that's okay. But it sounds like you application is past that point.

public class Quote
{
   public string Prerequisite1 { get; set; }
   public string Prerequisite2 { get; set; }
   public string GenerateQuote()
   {
      //Logics
   }
}

//Controller:
Quote quote = new Quote();
quote.Prerequisite1 = viewModel.TextField1;
quote.Prerequisite2 = repository.GetFromDB();
string shownToUser = quote.GenerateQuote();
repository.SaveWhatYouNeedToSave(quote);


问:
Explanation of how server-side programming languages are accessed
It is my understanding that any general-purpose programming language can be used for server-side development of a website.

Am I right in thinking that a server just needs some kind of interface such as CGI to make the server and the programming language work together? If so then why are some programming languages (such as php) more popular than others?

答:
A web server is a program written in any programming language that handles "web traffic" over socket(s) adhering to standards/application level protocols (HTTP, etc). Most programming languages offer you to create a socket.

Am I right in thinking that a server just needs some kind of interface such as CGI to make the server and the programming language work together?

There is no need to have dedicated server program and your application program - they can be the same (disregarding any performance-related issues).


答:
If your employer makes you work regularily using tools that you "hate" (which is a very strong term), then perhaps you are in the wrong job?

Being pragmatic is essential to profesionalism.


问:
Why python function programming functions are not collection methods?
In other words, is there a Python design related reason for it to be so?

Functions like map, filter, reduce etc. are just plain functions.

Is it just a poor design choice (if it is a good one, please explain)?
For example in scala, you can chain collection methods like smth.map(func1).reduce(func2). It seems much more convenient to me.

答:
I think this is just a historical artifact. These functions were introduced quite a while ago, when fluid interfaces were not all the rage. Since then everyone got used to them. (So yes, you can write it of as "bad design").

Could these functions could be retrofitted to lists? Possibly, but it was not and should not have been done.

First, There should be one-- and preferably only one --obvious way to do it.

Second, and most importantly, map, reduce and many other functions work not just with lists but with anything that's iterable. They work on tuples, sets, dicts, and, most importantly, any user-defined classes that implement iteration (via __iter__) or generators (via yield).

So, every iterable or generator should somehow receive their own implementations of map, reduce, and probably a bunch of other functions that accept an iterable / generator and return something compatible. This would require that any existing class that happen to be iterable not to expose names like map and reduce. Code-breaking changes are very much frowned-upon by Python maintainers and community alike.

Instead, you can wrap things into your own class that offers the additional interface, and enjoy either the fluid style you mention, or pipe style, or anything else.


答: I could see this being a recursive function in which you seek the top-left corner of the next possible rectangle.  Scan right and down, keeping track of the new rectangle width and height to determine the length to check in your next scan row/column.  When you've hit on both left edge and bottom edges, add result to result list, mark those "cells" as used, and reiterate.  When you find no empty cells, you're done.</p>

Title: How to draw rectangles for 2D arrays

Body:
I have an 2D boolean array that looks like this:

```<code>[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
</code>```

(0 = false, 1 = true)

I've found a way to combine neighbouring zeros on the horizontal plane like like:

```<code>[----------------------------]
[----------------------------]
[----------------------------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[----------------------------]
[----------------------------]
</code>```

The code for achieving this is as such:

```<code>for y = 0 to ySize
    for x = 0 to xSize
        if array[y][x] = 0
            set width = 1

            for x2 = x + 1 to xSize
                if array[y][x2] = 0
                    width++
                else
                    break

            add object at x, y and set width to width
            set x = x + width - 1
</code>```

So it loops the 2D array looking for zeros, and if it finds one, it loops until the end of the row to find where it is no longer a zero.

It then creates an object at the position where it first found a zero, and stretches it to fill the part until it is not a zero.

I want to adapt this code in order to make rectangles instead of long planks, like:

```<code> ____________________________
|                            |
|                            |   <------ rect at 0, 0 with size (10, 3)
|____________________________|
|       |[1][1][1]|          |
|       |[1][1][1]|          |
|       |[1][1][1]|          |   <------ rect at 6, 3 with size (4, 5)
|       |[1][1][1]|          |
|       |[1][1][1]|__________|
|       |                    |
|_______|____________________|   <------ rect at 3, 8 with size (7, 2)

   ^
   |
   |
  rect at 0, 3 with size (3, 7)
</code>```

So instead of making 15 horizontal planks, it makes 4 rectangles that surround the ones.

In short, I want to create an algorithm that will, when given an 2D array of ones and zeros, create rectangles around the ones.

For a smaller example:

```<code>             {
[0][0][0]         { 0, 0, 0 },
[0][1][0]         { 0, 1, 0 },
[0][0][0]         { 0, 0, 0 }
             }
</code>```

Will return the position and dimension of rectangles such as:

```<code>[-------]
[-][1][-]
[-------]

{
    {0, 0, 3, 1}, //rect at (0, 0) with width 3, height 1
    {0, 1, 1, 1}, //rect at (0, 1) with width 1, height 1
    {2, 1, 1, 1}, //rect at (2, 1) with width 1, height 1
    {0, 2, 3, 1}  //rect at (0, 2) with width 3, height 1
}
</code>```

What should this algorithm look like?

Edit: There should be some effort to minimize number of rectangles used (otherwise, it could just leave it as is).

Also, it doesn't matter if it prefers horizontal or vertical rectangles. Example:

```<code>[-------]
[-][1][-]
[-------]
</code>```

is the same as

```<code> _     _
| |[ ]| |
| |[1]| |
|_|[ ]|_|
</code>```

In the end, both have 4 rectangles surrounding the [1].


答:
Its a learning opportunity.

A couple of things spring to mind:

Firstly: how to do better in the toolset you're working with, just because what's already there is less than wonderful doesn't mean that what you produce has to be. You may even find things to like (although I struggle to remember any from Dibol...).

Secondly: weight of argument for not using that toolset in the future, if you can say that you used something in a non-trivial fashion, that it has these pros and those cons then you have a far better chance of persuading something that your negative opinion of same has value.

As a professional you have, substantially, to shut up and get on with it - the sooner its done the sooner you get back to using toys you like. That's not to say that you shouldn't express your unhappiness to your management at the start and at the end. But probably not in the middle.


答:
Which class would you put these methods on?

In python, I can use map on lists, tuples, dictionaries, files, strings, sets, arrays, etc. There is no collection base class to put a map,reduce,filter etc on.

Now, python could have had a collection class that all these different things inherited from. But that would really go against the "spirit" of python. In python everything is duck typed. Things work by virtue of the fact that you have the right methods. You can use map, reduce, and filter on anything that defines an __iter__. Having to subclass a collection class would go against that.

As it is, map/reduce/filter aren't really considered the pythonic solutions.

Instead of map(x, lambda y: y+1) use [y + 1 for y in x]

Instead of filter(x, lambda y: y % 2 == 0) use [y for y in x if y % 2 == 0]

Instead of reduce(x, lambda x,y: x+y) use

```<code>sum = 0
for y in x:
   sum += y
</code>```

Title: Why python function programming functions are not collection methods?

Body:
In other words, is there a Python design related reason for it to be so?

Functions like map, filter, reduce etc. are just plain functions.

Is it just a poor design choice (if it is a good one, please explain)?
For example in scala, you can chain collection methods like smth.map(func1).reduce(func2). It seems much more convenient to me.

Body:
Which class would you put these methods on?

In python, I can use map on lists, tuples, dictionaries, files, strings, sets, arrays, etc. There is no collection base class to put a map,reduce,filter etc on.

Now, python could have had a collection class that all these different things inherited from. But that would really go against the "spirit" of python. In python everything is duck typed. Things work by virtue of the fact that you have the right methods. You can use map, reduce, and filter on anything that defines an __iter__. Having to subclass a collection class would go against that.

As it is, map/reduce/filter aren't really considered the pythonic solutions.

Instead of map(x, lambda y: y+1) use [y + 1 for y in x]

Instead of filter(x, lambda y: y % 2 == 0) use [y for y in x if y % 2 == 0]

Instead of reduce(x, lambda x,y: x+y) use

sum = 0
for y in x:
   sum += y


问:
What is the explication for the difference execution time for the same instruction?
As you know when we run instruction in our code

like long a = b;

we will not have the same ticks each to be executed.

first exeution it take 2ticks;

second exeution it take 3ticks;

third exeution it take 2ticks;

It depends for memory state, caches, instruction pipeline, branch prediction.

For the memory state:

We will have different time execution because  the state of memory is not the same for situation 1,2,3,.. OS can do the allocation in 2 tick and next time it will need more time like 3 tick because lot of program change the state of the memory.

The example above was one of examples which they change the execution time, their are other examples that i need to understand,
like how can caches, instruction pipeline, branch prediction effect this variation.

Please can someone explain it to me.

And also I need to know if the time of affected by each operation is the kernel time or user time for the process which execute the instruction.

答:
If you're talking about the difference between 2 ticks and 3 ticks, it could simply be that, for a given execution, you started counting ticks early or late in a single tick cycle, and that the execution times are actually identical.

You should look into using timers with a higher precision than ticks; ticks are a very coarse measurement.


问:
filtering data from db
I've taken over a web application that someone else built.  It's a pretty simple application that queries ALL records from a db and displays them in a list.
They've also provided a way to 'filter' the data.  When the user enters in data into a "filter by" text box, via Ajax the system re-queries the database to only select records that begin with that data.
it's basically doing a

```<code>    "select * from widgets where name like '" + input_from_user + "'"
</code>```

Now we've gotten to the point where there are too many records being returned initially and I'm mullling over the follow design decisions.

Is the filter really working well?  Meaning, if we leave everything as is and query all records, as the user is filtering the data, why do I need to requery the database? Should I just "somehow" use the data I already have and filter that? For example, couldn't I somehow use javascript / jquery to filter client side?

If we want to introduce some sort of paging mechanism where the SQL statement itself is a)sorting by a certain field, b)limiting the results to the next 100 sorted records, do I still need a filter? I don't think so.
It's either paging, or filtering in my mind, especially if I limit the amount of data we show at a time to 5o -100 records (something small that will fit on one screen).

Here's what I was thinking of doing (pseudocode)

```<code>SELECT *
FROM MyTable
WHERE SomeColumn > LastValue
ORDER BY SomeColumn
LIMIT 100
</code>```

I wanted to throw it out there to see if anyone had any comments / suggestions / wanted to tell me that I'm way off base here.

Thanks.

答:
Filtering should be done in the database.  Databases are really good at filtering results using the WHERE clause.  One should always govern that amount of data being queried, paged and returned.  You don't want millions or rows going across the network and you don't want the database to page a result set that has a million rows as it is a lot of needless work, so put a limit on the total amount of records SQL should query and page and how many records should be returned on a page.

Paging can also employed.  Two types of paging, offset and keyset.  Offset is typically easier to employ, but keyset performance wise is more consistent.  One should research both before picking a solution as they work slightly differently.  Either can be acceptable.  Paging should be done in the query as well.  One can write offset and/or keyset queries by passing in a few extra parameters like page size, number of records to page, etc.

In conclusion, page and filter at the database.  Decide what the high water mark is for the number of records to filter and what the page size is.  If the high water mark is hit, send the users the page back and tell them to narrow the query result by adding in more specific search criteria as the query is returning too many results for the current filter.

One should be able to pick a page size and filter high water mark that meets the needs of the application without crippling the network and database.  Some examples are page size of 100 with max records of 10,000, or maybe 10 and 1,000.

If these values never change, consider caching the entire result set so the data is fetched just once on start up.

This will keep your DBA and network admin happy and will be a positive experience for your users.

Title: filtering data from db


问:
What is the function of URLs as "key" names in markup used for a RESTful API?
I just finished reading REST in Practice as my first* introduction to REST APIs. I found the book quite enlightening, but am left with one nagging question, and Google has yet to clear it up. This question gets close, but the answers fall short of answering my specific question, which is...

Given some hypertext markup for consumption with a RESTful API, such as this (in JSON-LD):

{
  "http://schema.org/name": "Manu Sporny",
  "http://schema.org/url": { "@id": "http://manu.sporny.org/" },
  "http://schema.org/image": { "@id": "http://manu.sporny.org/images/manu.png" }
}
```

What is the function of the URL/URI/IRI as a "key" name?  (Now I know that JSON-LD--with @context--and other markup languages, allow ways to generalize these IRIs-as-keys to be more human friendly, but that doesn't change the nature of the question.)

If I try to break my question down into smaller pieces, I come up with something like this:

Specifically, what is expected to live at the endpoint represented by that IRI?

All the discussion talks about disambiguating key names. But how is http://schema.org/name less ambiguous than name?

Is there some (theoretical?) centralized repository of key types that developers are expected to reference, so that these key names all point to some more-or-less common definition?

I hope this question makes enough sense to be answerable. I'm still in a bit of a "I don't know enough to ask what I don't know" state on this particular point.

*I, like many, thought I already knew what REST was, and believed that my previous, POST-only CGI scripts were representative of REST APIs...

答:
what is expected to live at the endpoint represented by that URI?

A resource of some kind.  Generally, you can identify the type of resource by examining the mime type.  Often, it's just a web page.

How is http://schema.org/name less ambiguous than name?

It lives specifically at the http://schema.org/ domain, and the domain itself is unique.  In other words, the domain name provides the disambiguation.

Is there some (theoretical?) centralized repository of key types that developers are expected to reference, so that these key names all point to some more-or-less common definition?

ICANN.


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
Product Backlog Hierarchy is pretty much dependent on the product size and its modularity (number of product areas defined).

For small Projects: Epic > Story is more than enough; and you call either the "feature".

Large projects might become alike to: Novel > Theme > Epic > Feature > Story

The best example might be the following:

Novel = MS Office

Theme = MS Word / MS Excel ...

Epic = Tables / Font Directory ...

Features = Basic Table / Table Color Scheme / Operations with Cells ...

Stories (for 'Basic Tables' Feature within 'Tables' Epic) = Add Table / Draw Table / Insert Raw / Insert Column ...

What I believe is beneficial to keep in mind when defining your own scaling for backlog is:

1. Story: a) always feasible within one sprint; b) not always testable for end-users

2. Epic / Feature: a) doesn't fit one sprint duration and needs to be decomposed; b) always should be testable for end-users; c) always shippable, can be monetized - get ROI calculated for it

3. When considering add or not Epic > Feature section or stick to Epic > Story: I'd recommend to insert Feature in between Epic and Story only when: Epic doesn't fit even 1 Release, so you need to define shippable element that will fit 1 Release duration.

Hope this is helpful.


答:
Some considerations regarding the second part of the question:

Is it just a poor design choice (if it is a good one, please explain)?
  For example in scala, you can chain collection methods like
  smth.map(func1).reduce(func2). It seems much more convenient to me.

I do not think that it is poor design: Python supports both procedural and object-oriented styles, and one of the two styles had to be picked for higher-order functions on collections. Ruby and Scala favour the object-oriented style and therefore they chose high-order methods.

Regarding the convenience of method chaining, you have a corresponding compact syntax in languages supporting currying, e.g. in Haskell you can write

```<code>(map func1 . filter func2) smthg
</code>```

Probably you can do something similar in Python (see e.g. PyMonad) even though it would not be the standard functions.

Body:
Some considerations regarding the second part of the question:

Is it just a poor design choice (if it is a good one, please explain)?
  For example in scala, you can chain collection methods like
  smth.map(func1).reduce(func2). It seems much more convenient to me.

I do not think that it is poor design: Python supports both procedural and object-oriented styles, and one of the two styles had to be picked for higher-order functions on collections. Ruby and Scala favour the object-oriented style and therefore they chose high-order methods.

Regarding the convenience of method chaining, you have a corresponding compact syntax in languages supporting currying, e.g. in Haskell you can write

(map func1 . filter func2) smthg

Probably you can do something similar in Python (see e.g. PyMonad) even though it would not be the standard functions.


问:
Algorithm to generate N random numbers between A and B which sum up to X
This problem seemed like something which should be solvable with but a few lines of code.

Unfortunately, once I actually started to write the thing, I've realized it's not as simple as it sounds.

What I need is a set of X random numbers, each of which is between A and B and they all add up to X. The exact variables for the problem I'm facing seem to be even simpler: I need 5 numbers, between -1 and 1 (note: these are rational (floating point) numbers), which add up to 1.

My initial "few lines of code, should be easy" approach was to randomize 4 numbers between -1 and 1 (which is simple enough), and then make the last one 1-(sum of previous numbers). This quickly proved wrong, as the last number could just as well be larger than 1 or smaller than -1.

What would be the best way to approach this problem?

PS. Just for reference: I'm using C#, but I don't think it matters. I'm actually having trouble creating a good enough solution for the problem in my head.

I also wanted to provide my current solution to the problem, but do remember that it's quite imperfect and it was created as a quick fix to the initial problem!

Generate 4 random numbers between -1 and 1

Create a "final" number X=SUM(previousNumbers)

If the final number is >1 or <-1, then:

Get the "amount" over 1 / under -1 and make the last number a 1 / -1

Find another number which can accept this amount and still inside the brackets

If no number can take the amount (it's too large / too small) then divide the amount in half and try again for each half

Randomize the order of the generated numbers and return them

This works in the sense that this algorithm generates 5 numbers which are between -1 and 1 and their sum is 1. However the downside is that quite often one of the generated numbers is a 1 (or -1), which doesn't feel very random.

答:
It is possible for each variable to be uniformly distributed on an interval while the joint distribution is satisfies a codimension 1 constraint. For example, if you pick (x,y,z) so that it is uniformly distributed on a unit sphere, then each coordinate is uniformly distributed on the interval [-1,1]. The coordinates are just not independent.

Even if you give up independence, it is not possible for 5 numbers uniformly distributed on [-1,1] to have a constant sum of 1. This is because expectation is linear for any random variables, not just for independent ones. If you have 5 random variables which are each uniformly distributed on [-1,1], their sum has average value 0, so it can't be the constant 1.

Some other answers suggest picking the first numbers to be uniform on [-1,1], and then fix the last few numbers. This usually gives up the symmetry between the numbers. You might be able to tell which numbers were generated without constraints, and which were used to make the sum fit, since the 5th number might be in [-1,1] but it might not have a uniform distribution.

Instead, you might take a conditional distribution. Because the problem is symmetric, the conditional distribution is symmetric. Imagine that you choose some epsilon>0, sample from [-1,1] 5 times independently, and then reject the 5-tuple if the sum is more than epsilon away from 1. This gives you some joint distribution within the unit 5-cube that is concentrated near the constraint hyperplane x0+x1+x2+x3+x4=1. Then let epsilon go to 0, and you get a limiting distribution. Since the probability that you get a point on the plane is too low (mathematically 0, but positive for, say, random 32 bit floats) to use rejection sampling directly, you need another method for producing this distribution.

It is equivalent to produce {xi/2 + 1/2} uniform on [0,1] with sum 3, or {xi/6+1/6} uniform on [0,1/3] with sum 1. So, produce 5 positive numbers summing to 1, and then reject the sample (repeat if any of these are greater than 1/3. (Afterwards, multiply these by 6 and subtract 1 to get numbers on [-1,1] summing to 1.) To produce 5 positive numbers summing to 1, one way is to generate 4 random numbers on [0,1], sort them (y0,y1,y2,y3), add 0 and 1 to the front and back, (0,y0,y1,y2,y3,1), and then take the differences (y0,y1-y0,y2-y1,y3-y2,1-y3). (Another method is to create 5 exponentially distributed random variables by taking -log(uniform), and renormalize by their sum.)

You have to be wary of rejection sampling in high dimensions since the probability of acceptance might be low, and then you have to iterate too many times. The probability that among the 5 numbers summing to 1, none of them is at least 1/3 can be found with inclusion-exclusion: 1-5(2/3)^4+10(1/3)^4 = 11/81 > 1/8. So, the average number of 5-tuples you need to generate by this method before you find one with no number greater than 1/3 is under 8, so on average, it takes fewer than 40 uniformly random numbers to generate a 5-tuple with sum 1 drawn from the conditional distribution. If the parameters of the problem change, you might prefer a more complicated method that avoids rejection sampling.


问:
Can relational database tables always be topologically sorted by their FK reference relation?
Suppose I have some conceptual, not physical, E-R diagram describing a relational database. I want to sort all the tables in the database using a topological sort, where the partial ordering between tables is Table 1 has a foreign key onto Table 2.

When clearing out tables after putting test data in them, I would need to delete Table 1 above first, then Table 2, in order to not violate FK references. A topological sort on the FK relation gives me an ordering to clear the tables in.

It is possible to have a table with an FK to itself, providing a simple counter example where there is a cycle, and subsequently no topological sort. However, this self relationship could also be represented using a join table, which lists 2 rows of the table, where one refers to the other, and in this case there would be a topological sort.

By replacing direct FK references between tables with join tables, is it always possible to arrive at a structure that can be topologically sorted?

答:
Well, if I understood correctly, if there is a cycle somewhere along the path then you can't have a topological sort. Even if you solve the cycle problem in the case of a FK from table A to itself (I didn't understand what you meant exactly with the term "join table" though, but it's certainly because of my lack of experience with databases) you could always have a cycle among N tables.

In the last case you should consider the resources necessary to solve that particular case (assuming you go with the "join table" approach). You could do a topological sort of a subset of tables though where you don't have cycles.


问:
Keeping client side model and server side in sync in SPAs
Since SPAs have most of their domain logic client side, how do you keep your domain model in sync with the back end?

For example, let's say I have a .NET WebAPI web service that uses the Entity Framework to communicate with SQL Server and one of my classes is called Product. Most of Product's domain logic will be client side.

Now I add a ProductType table to my DB, and I add a ProductTypeID column to my Products table. My EF Product class now has a new property called ProductTypeID. Do I now manually go into my JS files, find the definition for Product and add the ProductTypeID property?

While the client side doesn't need to know server side implementation specifics, it will need to know the shape of the model. How do you keep that in sync between server side and client side? Is it completely manual? How do you avoid errors like property name typos in JS?

答:
Generally you don't keep them in sync in that way unless there is a reason to do so. Your entire premise is flawed. Most of the domain logic in an SPA, like any application, should be in the server. Only logic pertaining to the user interface should be in the client.

Edit:

So just to be clear on terminology. I assume that when you say "domain logic" you mean the core business logic of the application, the thing that makes your application more than just CRUD operations on resources. It may very well be that your application only needs to store, retrieve, update, and delete some data, in which case I suppose all of the "logic" would be in the client.

But imagine a simple purchasing system where you have inventory items and users are able to add items to a shopping cart for purchase. Imagine then that you need to know whether or not an item is in inventory or out of stock and if it's out of stock your particular use case does not allow a purchase to take  place on an out-of-stock item. In this scenario I don't think you would be doing the right thing if you did not have this requirement checking logic in your back-end.

You would certainly want to disable the "Buy Now" button on the client if the item was out of stock, but allowing the back-end to process a purchase for the out of stock item simply because an enterprising teenager decided to submit a POST request using curl seems very wrong to me.

The reason for the client to know that the item is out of stock is different from the reason for the back-end to know it. The client needs to know it to disable a button but the back-end needs to know it to prevent an incorrect charge.

The client's model of the state of the system might just include a purchasable boolean if that is all that is needed, while the server's model may have to take into account a wide variety of reasons, not just whether or not the item is in stock--perhaps the item is not shippable to the current user's location or perhaps the current user has a 35% coupon in their account and the margin on the item is less than 35%.  Chances are that the reasons for an item being purchasable or not is more complex to the server than the client, and it's very unlikely that a business system would allow the business logic to be made available to anyone who can download the JS files for the site (every visitor!).

Perhaps the server in that case simply removes the item from the list of results in a query for the purchasable items. The client cannot by definition apply any business domain logic to this item because it does not know that the item exists in the first place.

What if you next want to deploy a native mobile application?   Are you going to recreate all of your business domain logic in each new client? What if the system has gotten so large that there are hundreds of rules?

One of the key takeaways of experienced software developers should be that there can and will be multiple models in a system.


问:
Open Source Licensing and Intellectual Property Rights
Is it possible for a developer to lose rights to work on a self-created, open-source-licensed project after an outside company, developer, or organization copyrights (or takes some other legal action regarding) the same project?

I haven't heard of this happening, but it seems entirely possible that someone could independently develop a project and then have the rights to continue working on said project (or an idea/language/technology) taken away...

For example, when a project like Minecraft (but open-source-licensed, in this case,) is developed, and is later bought by a company like Microsoft, does this mean that Microsoft can say that Mojang (or Notch, for that matter,) no longer has rights to work on further Minecraft development?

Another example would be Oracle who bought the open-source MySQL database.

In other words, are copyrights still necessary for intellectual property alongside open source licensing?

答:
Minecraft is actually an invalid example, as it was a proprietary commercial project.  If Microsoft purchases the IP rights to the project, and does not keep the Mojang developers on, then it's no different from any other proprietary project: you don't own the rights to what you work on, under "work made for hire" doctrine.

Having said that, for an actual open-source project, things are different.  When source code is released under a license, the genie can't be put back into the bottle.  There's a legal doctrine known as "promissory estoppel" which, in layman's terms, says that "but you promised!" is actually a valid legal argument, and so when someone publishes source code and says "here you go, community, use this as an open-source project," they can't take that back.

One of the most dramatic examples of this is the Firebird database.  A long time ago, Borland decided to release the source code to their InterBase RDBMS, but then, for whatever reason, they quickly had a change of heart.  But because the code had already been published, they couldn't take that back, and a development community continued to work on the InterBase source under the new name "Firebird".  Today, Firebird and InterBase are two similar but distinct products, both still under active development, one by the open-source community and the other as a commercial project run by Embarcadero, who bought the rights from Borland.

(Standard disclaimer: I am not a lawyer.  This is not legal advice.  This is just stuff I've picked up based on common sense and experience.)


问:
Passing context around AST nodes
I have various objects inside my AST, such as IfBlock, FunctionBlock, LogicExpression, etc. All of those objects share a context, which is basically a hashmap with some variables. It's a very simple language, created for learning purposes. I use this hashmap to make it possible that a FunctionBlock is able to modify a variable later used in an LogicExpression.

Right now, i'm just injecting the hashmap into all objects, via constructor. Is this the proper way? Isn't there a more elegant way to share such global context between objects?

答:
In the Boo language, which encourages playing around with ASTs via its metaprogramming facilities, there's an AST node class called CompileUnit that lies at the root of a compile tree.  Its children are Module nodes, which represent a single source file, and each Module contains tree nodes corresponding to the AST of the code in that file.

You could do something similar.  If your AST nodes have a Parent property (which they probably do anyway), and you place the context data at the root of the tree, it's trivial to get at it by declaring a GetRoot method on the base node class that walks the Parent chain all the way up.

Of course, this replaces your current situation, where access to the context is an O(1) operation, with a situation where access involves walking a linked list and thus is O(n).  It's a classic software engineering tradeoff: memory or speed?

Title: Passing context around AST nodes


问:
Why was the grave but not the acute accent included in ASCII?
While looking at the Unicode properties (code point, script, block, UTF-8 and UTF-16 encoding, etc.) of some characters, I stumbled upon major differences between ` ("GRAVE ACCENT") and ´ ("ACUTE ACCENT"):

```<code>Name          Code point  Script  Block               UTF-8
GRAVE ACCENT  U+000060    Common  Basic Latin         60
ACUTE ACCENT  U+0000B4    Common  Latin 1 Supplement  C2 B4
</code>```

It seems the ´ is not included in the block "Basic Latin" because it was not included in ASCII. What is the reason for including ` but not ´ in ASCII?

I've taken a look into RFC 20 - ASCII format for Network Interchange where it says:

```<code>Column/Row  Symbol  Name
2/7         '       Apostrophe (Closing Single Quotation Mark Acute Accent)
6/0         `       Grave Accent (Opening Single Quotation Mark)
</code>```

I cannot really make sense out of this. The apostrophe and the acute accent are two quite different characters and the people writing the document most likely knew that. What do these insertions in parentheses even mean?

I've also scanned through ASA X3.4-1963 (the original document) but could not find any reasoning for including `. Is there any?

答:
The apostrophe came first. later, when the grave accent was added, it was decided that the existing apostrophe character could also be used as an acute accent.

Here is a synopsis of the history of these characters:

Mar. 1961 -- The apostrophe character is included in the proposed standard code.

Oct. 1963 -- The grave accent was added to the draft standard, possibly to be used primarily as an accent mark, and it was noted that the apostrophe character could also be used as an acute accent.

This article: Character histories:
notes on some Ascii code positions by Jukka (Yukka) Korpela discusses some character history and provides additional references.


答:
Executive Summary

Excluding Big-Integers, Strings that are more than one character long are inherently more complicated than numbers because they:

are represented as a list (or shallow tree) of multiple numbers

can be alphabetized

have case sensitivity

have punctuation, accents, characters, and whitespace, which all need to be treated differently

have character encodings which add their own complexities.

could use a lot of memory (if large enough).

Big-Integers could be about as complicated as all-lower-case (or all-upper-case) ASCII or EBCDIC strings.

Details

What's a String?

A string is a list of characters.  Characters are just numbers and a character encoding that gives each character a number to represent it.  So a String is essentially a list of numbers.

What's a Number?

Excluding a few special-purpose computers at research facilities, every popular processor has built in integers (from 8 to 64-bits) and IEEE floating points (32- and 64-bits).  Popular processors have instructions for doing simple math: +, -, /, and * on these various kinds of ints and floats.  Popular programming languages have straight-forward syntax that gets compiled to these opcodes in very simple ways.

Bigger Numbers?

Many languages have a Big-Integer that stores values bigger than what fits in a hardware 64-bit integer.  Like Strings, they are essentially lists of numbers.  Sometimes BigInt is implemented as a String, but I hope that is rare today.  Like Strings, BigInts tend to be harder to use than simple hardware-supported numbers.  You can fill up memory with them, etc.  As an aside, tools like Spire cleverly promote Integers to BigIntegers as appropriate.

Character Encoding

Strings used to be encoded in EBCDIC, ASCII, WinAnsi, and a bunch of other formats that came out before Unicode.  With Unicode, there is UTF-8, UTF-16, UTF-32, and other ways of representing characters as one or more bytes.  Some character encodings are one-way compatible with others, but most are not.  ASCII has only 8-bit characters, but a String in UTF-8 is actually a shallow tree structure where each character is composed of 1-4 bytes (thank you @gnasher729).  And that's just representation of a single "code point" in bytes.  The logical characters themselves are sometimes composed of multiple code points (a base character plus an accent) so you have grapheme clusters to deal with (thank you @gnasher729).

Parting Thoughts

Anything can be as complicated as you want it to be.  Numbers can be positive, negative, or zero (IEEE floating points can also be negative zero).  They can be even, odd, prime, ratios, imaginary, irrational, transcendental, or have many other properties that have kept number theorists and set theorists busy for centuries and will continue to do so.

But character strings represent languages and you need fonts to render them, which have their own set of headaches (and licensing issues).  Chinese people whose ancient family names involve characters that are not otherwise part of their roughly 10,000 character alphabet are clambering to have their names included in Unicode.  There are lost languages, and arguments about whether made-up languages like Klingon need to be included in character sets.  I think when you add all that, plus regular expressions, then in general, Strings are more complicated than numbers.

Probably for every string complexity issue, a great student of Math could bring up various series, sets, divergence, and other complex issues.  But I think you are defining numbers as "ints, floats, and maybe Big-Integers" not as "polynomials, series, and beyond."


问:
What do you think about the Joel Test?
The Joel Test is a well known test for determining how good your team is. What do you think about the points? Do you disagree with any of them? Is there anything that you would add?</p>

答:
Jeff Atwood has The Programmer's Bill of Rights.

From the post:

Every programmer shall have two monitors

Every programmer shall have a fast PC

Every programmer shall have their choice of mouse and keyboard

Every programmer shall have a comfortable chair

Every programmer shall have a fast internet connection

Every programmer shall have quiet working conditions

This seems to have some items that I'd like to see on Joel's list.  Specifically in the area of hardware (dual monitor, fast PC, mouse/keyboard, comfortable chair, fast connection).

The only thing not mentioned is having a comfortable and adjustable desk.

This could all be added by changing:

Current #9: Do you use the best tools money can buy?

to

Improved #9: Do you use the best tools and equipment money can buy?

Title: What do you think about the Joel Test?


答:
The AST should only represent the syntax tree of your language. The objects making up the AST would generally not have any further functionality. Nice things like evaluating the AST or prettyprinting it can be implemented outside.

I generally use the Visitor Pattern for these external methods – given that I implement an accept_visitor method for each AST object, I can easily define various visitors that do the actually interesting stuff. One of these visitors could be an Evaluator, and that object would then hold the environment.

Here's an example in Scala, using pattern matching instead of the visitor pattern:

sealed abstract class Ast
case class Literal(value: Int) extends Ast
case class Var(name: String) extends Ast
case class Set(name: String, value: Ast) extends Ast
case class Add(left: Ast, right: Ast) extends Ast
case class Block(statements: Seq[Ast]) extends Ast

import scala.collection.mutable.HashMap
class Evaluator {
  val env: HashMap[String, Int] = new HashMap()
  def evaluate(ast: Ast): Int = ast match {
    case Literal(value) => value
    case Var(name) => env(name)
    case Set(name, value) => { val v = evaluate(value); env(name) = v; v }
    case Add(left, right) => evaluate(left) + evaluate(right)
    case Block(statements) => statements.map(s => evaluate(s)).last
  }
}

val ast = Block(Seq(
  Set("x", Literal(40)),
  Set("y", Literal(2)),
  Add(Var("x"), Var("y"))
))

new Evaluator().evaluate(ast) //=> 42
```

Later, you might have nested scopes. The easiest solution to represent these nested scopes is to maintain a list of hash maps. If a variable is not found in the innermost hash map, we traverse the list of scopes until either the variable was found or we reach the end of the list. In such a case, care has to be taken when setting variables – new variables should be put in the innermost scope, whereas existing variables should be updated even when they are in an outer scope.

Title: Passing context around AST nodes

Body:
I have various objects inside my AST, such as IfBlock, FunctionBlock, LogicExpression, etc. All of those objects share a context, which is basically a hashmap with some variables. It's a very simple language, created for learning purposes. I use this hashmap to make it possible that a FunctionBlock is able to modify a variable later used in an LogicExpression.

Right now, i'm just injecting the hashmap into all objects, via constructor. Is this the proper way? Isn't there a more elegant way to share such global context between objects?

Body:
The AST should only represent the syntax tree of your language. The objects making up the AST would generally not have any further functionality. Nice things like evaluating the AST or prettyprinting it can be implemented outside.

I generally use the Visitor Pattern for these external methods – given that I implement an accept_visitor method for each AST object, I can easily define various visitors that do the actually interesting stuff. One of these visitors could be an Evaluator, and that object would then hold the environment.

Here's an example in Scala, using pattern matching instead of the visitor pattern:

sealed abstract class Ast
case class Literal(value: Int) extends Ast
case class Var(name: String) extends Ast
case class Set(name: String, value: Ast) extends Ast
case class Add(left: Ast, right: Ast) extends Ast
case class Block(statements: Seq[Ast]) extends Ast

import scala.collection.mutable.HashMap
class Evaluator {
  val env: HashMap[String, Int] = new HashMap()
  def evaluate(ast: Ast): Int = ast match {
    case Literal(value) => value
    case Var(name) => env(name)
    case Set(name, value) => { val v = evaluate(value); env(name) = v; v }
    case Add(left, right) => evaluate(left) + evaluate(right)
    case Block(statements) => statements.map(s => evaluate(s)).last
  }
}

val ast = Block(Seq(
  Set("x", Literal(40)),
  Set("y", Literal(2)),
  Add(Var("x"), Var("y"))
))

new Evaluator().evaluate(ast) //=> 42

Later, you might have nested scopes. The easiest solution to represent these nested scopes is to maintain a list of hash maps. If a variable is not found in the innermost hash map, we traverse the list of scopes until either the variable was found or we reach the end of the list. In such a case, care has to be taken when setting variables – new variables should be put in the innermost scope, whereas existing variables should be updated even when they are in an outer scope.


问:
Java front-end, PHP/MySQL back end methodology
I have been basically out of the programming world for about 10 years, with only a bit of dabbling here and there with small Java utilities and one large Access database I wrote for someone, and some VBA macros here and there.

Now I've come back with a project I would like to work on, and I'm very confused about the whole new web-programming scene. I am trying to write a web based multi-user database, and I'm not so familiar with the technologies used.

So I figured that I should go with what I'm familiar with. I know a bit of PHP and lots of SQL, so that's a good start for the backend. And I hate CSS and javascript, so I'll try to use a standard Java desktop application for the front-end (which is anyways more appropriate for this database then a web-based front-end). I don't know C# at all and am not willing to learn it just for this project, though I am curious to learn it eventually.

I've spent many hours on it, and I've familiarized myself with Jackson for JSON processing, and even made a fancy command queue that sends requests and receives responses to the server on a separate thread and deals nicely with errors.

But I'm finding the whole process quite tedious. For every little table I make in the database, I need to make a Swing JFrame, then I have to connect the user interface with the underlying Java class that holds the data, then I have to make the requests that put the data into the appropriate JSON, which often involves little fiddling with Jackson annotations, then I have to make the PHP that takes the data and makes it into an SQL query. And same for the other direction, I have to make a request to the server that asks for the data, I need to write php to make to appropriate SELECT queries, pack it into JSON (at least json_encode does that quite nicely, though it's complicated if there are one-to-many relationships involved) get the information back into my java class, and then to get that displayed in the GUI. And all along the way data has to validated and errors dealt with.

I feel like this is way too much work for such a simple thing. I'm used to Access, where you just make a query, and then displaying the results and allowing the user to edit them is just a matter of running a wizard and moving around the controls a bit. And I feel like a lot of what I've done already with my command processing queue is probably re-inventing the wheel - every web-based application needs something like that.

Am I missing something?

答:
Since you are not developing a website or a web application, but a desktop application which stores its data on a server, there are indeed a few layers you can skip.

A common approach, in this situation, is to use web services.

When a service should be lightweight and interoperable (that is, you can use it with ease from virtually every programming language), the service can take a form of REST. The drawback is that not every server-side language makes it possible to create REST services painlessly, without writing too much code.

Another form a web service can take is SOAP. In .NET Framework, this was a de facto standard option for web services for a long time, although recently, there is a major shift towards REST; for instance, SharePoint itself relies more and more on REST instead of previously ubiquitous WCF services. I could imagine that the situation is similar with Java and PHP.

The benefit of SOAP is that you probably don't have to write any code at all. In .NET Framework, you declare your web service interfaces server-side and let the framework generate the WSDL (the detailed schema of the service) and process the requests and the responses. Then you import the service client-side, without the need to write a single line of code.

The drawback of SOAP is that it is usually much heavier compared to REST. Responses are also usually larger, which impacts the bandwidth.

In your case, consider the web service as an interface to your database. Since you don't want anyone to be able to select everything from your users' table or delete all your tables, the web service is a way to tell who can access what.

This is different from simply giving access to an SQL database with a fine-grained configuration of permissions, so that a given user can access and do only a very limited amount of things. With a web service, you can also sanitize inputs, control how much resources are accessed by a user, use cache to boost performance, access resources outside the database, etc.

Of course, you can simply even the step of writing the service interface if the only thing you need is to bind the service to the database. In .NET Framework, WCF Data Services are used for that (the project is originally called Microsoft Astoria; search for this name if you want articles which are not too technical). I'm sure Java and PHP have something similar.


问:
What is the need for 'discoverability' in a REST API when the clients are not advanced enough to make use of it anyway?
The various talks I have watched and tutorials I scanned on REST seem to stress something called 'discoverability'. To my limited understanding, the term seems to mean that a client should be able to go to http://URL - and automatically get a list of things it can do.

What I am having trouble understanding - is that 'software clients' are not human beings. They are just programs that do not have the intuitive knowledge to understand what exactly to do with the links provided. Only people can go to a website and make sense of the text and links presented and act on it.

So what is the point of discoverability, when the client code that accesses such discoverable URLs cannot actually do anything with  it, unless the human developer of the client actually experiments with the resources presented? This looks like the exact same thing as defining the set of available functions in a Documentation manual, just from a different direction and actually involving more work for the developer. Why is this second approach of pre-defining what can be done in a document external to the actual REST resources, considered inferior?

答:
I had the pleasure a while ago to work with an API that had documentation that was very, very hard to understand.

Once I managed to get an actual reply from the server, it was possible to compare the documentation with the server reply and use that to decipher the documentation (and yes, deciphering it was the right term). The problem was that if a request was sent to the server that wasn't exactly correct according to the spec, you would just get an error, and with the unreadable documentation, figuring out how to send the correct requests was close to impossible. There were also different versions of the API documentation which didn't agree with each other and probably didn't agree with the API itself; that didn't help.

If there had been one command that I could send to the server, returning a list of all possible commands and how exactly to send them, that would have been extremely helpful. Discoverability is not just for clients, it's also useful for software developers.


答:
When a browser makes an HTTP request, it looks like this:

```<code>GET /search?q=cats HTTP/1.0
Host: www.google.com
Connection: close
</code>```

… to which the server should send a response that looks like this:

```<code>HTTP/1.0 200 Success
Content-Type: text/html; charset=UTF-8
Content-Length: 1337

<!DOCTYPE html>
<html>
  <head><title>cats - Google Search</title>
  <body>
    <h1>About 415,000,000 results</h1>
    …
  </body>
</html>
</code>```

Any code running on the server that listens for requests on a TCP socket, reads the request, and replies with the appropriate response will suffice.  One dumb way is just to spit out a canned response to anyone who connects to TCP port 80, using a shell script:

```<code>$ nc -l 8000 <<'RESPONSE'
HTTP/1.0 200 Success
Content-Type: text/html; charset=UTF-8
Content-Length: 1337

<!DOCTYPE html>
<html>
  <head><title>cats - Google Search</title>
  <body>
    <h1>About 415,000,000 results</h1>
    …
  </body>
</html>
RESPONSE
</code>```

Of course, that technique only barely appears to comply with the HTTP protocol.

A step up from that canned response is this simple Python program, which uses the http.server library in Python 3.

```<code>#!/usr/bin/python3

import http.server

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        payload = '<!DOCTYPE html>... insert cats here ...'.encode('UTF-8')
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=UTF-8')
        self.send_header('Content-Length', len(payload))
        self.end_headers()
        self.wfile.write(payload)

http.server.HTTPServer(('', 80), Handler).serve_forever()
</code>```

The HTTP server can be written in any language; that is just an example.  Obviously, this example is very rudimentary.  The payload is hard-coded — the program completely disregards the contents of the request — the URL, query string, Accept-Language header, etc.  You could add code to generate meaningful responses based on the request, but then the code would get very complex.  Besides, programmers would rather focus on writing the web application, not having to worry about the details of how to handle an HTTP request.

A more appropriate solution would be to use a web server, such as Apache HTTPD, IIS, or nginx.  A web server is just a program that listens on the relevant TCP sockets, accepts multiple requests (possibly simultaneously), and decides how to generate a response based on the request URL, headers, and other rules.  Ideally, many of the details, such as SSL, access control, and resource limits are taken care of via configuration rather than code.  Much of the time, the web server will formulate a response that consists just of content from files in the filesystem.

For dynamic content, though, the web server can be configured to execute some code to generate the response.  One mechanism for doing that is with CGI — the server sets some environment variables based on the request, executes a program, and copies its output to the TCP socket.  A slightly more sophisticated solution would be to have a module that adds support to the web server for calling code in another programming language (e.g. mod_php for Apache).  Yet another option is to write the web server in the same language as the web application, in which case the request dispatch is just a function call.  That is the case with node.js and Java servlet engines such as Apache Tomcat.

The choice of technology is really up to you, and depends on the programming language you prefer to use, the hosting environment that is available to you, performance requirements, popular opinion, and passing fads.  CGI, for example, has not been favoured lately, since the need to launch external programs limits scalability.

Title: Explanation of how server-side programming languages are accessed

Body:
It is my understanding that any general-purpose programming language can be used for server-side development of a website.

Am I right in thinking that a server just needs some kind of interface such as CGI to make the server and the programming language work together? If so then why are some programming languages (such as php) more popular than others?

Body:
When a browser makes an HTTP request, it looks like this:

GET /search?q=cats HTTP/1.0
Host: www.google.com
Connection: close

… to which the server should send a response that looks like this:

HTTP/1.0 200 Success
Content-Type: text/html; charset=UTF-8
Content-Length: 1337

<!DOCTYPE html>
<html>
  <head><title>cats - Google Search</title>
  <body>
    <h1>About 415,000,000 results</h1>
    …
  </body>
</html>

Any code running on the server that listens for requests on a TCP socket, reads the request, and replies with the appropriate response will suffice.  One dumb way is just to spit out a canned response to anyone who connects to TCP port 80, using a shell script:

$ nc -l 8000 <<'RESPONSE'
HTTP/1.0 200 Success
Content-Type: text/html; charset=UTF-8
Content-Length: 1337

<!DOCTYPE html>
<html>
  <head><title>cats - Google Search</title>
  <body>
    <h1>About 415,000,000 results</h1>
    …
  </body>
</html>
RESPONSE

Of course, that technique only barely appears to comply with the HTTP protocol.

A step up from that canned response is this simple Python program, which uses the http.server library in Python 3.

#!/usr/bin/python3

import http.server

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        payload = '<!DOCTYPE html>... insert cats here ...'.encode('UTF-8')
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=UTF-8')
        self.send_header('Content-Length', len(payload))
        self.end_headers()
        self.wfile.write(payload)

http.server.HTTPServer(('', 80), Handler).serve_forever()

The HTTP server can be written in any language; that is just an example.  Obviously, this example is very rudimentary.  The payload is hard-coded — the program completely disregards the contents of the request — the URL, query string, Accept-Language header, etc.  You could add code to generate meaningful responses based on the request, but then the code would get very complex.  Besides, programmers would rather focus on writing the web application, not having to worry about the details of how to handle an HTTP request.

A more appropriate solution would be to use a web server, such as Apache HTTPD, IIS, or nginx.  A web server is just a program that listens on the relevant TCP sockets, accepts multiple requests (possibly simultaneously), and decides how to generate a response based on the request URL, headers, and other rules.  Ideally, many of the details, such as SSL, access control, and resource limits are taken care of via configuration rather than code.  Much of the time, the web server will formulate a response that consists just of content from files in the filesystem.

For dynamic content, though, the web server can be configured to execute some code to generate the response.  One mechanism for doing that is with CGI — the server sets some environment variables based on the request, executes a program, and copies its output to the TCP socket.  A slightly more sophisticated solution would be to have a module that adds support to the web server for calling code in another programming language (e.g. mod_php for Apache).  Yet another option is to write the web server in the same language as the web application, in which case the request dispatch is just a function call.  That is the case with node.js and Java servlet engines such as Apache Tomcat.

The choice of technology is really up to you, and depends on the programming language you prefer to use, the hosting environment that is available to you, performance requirements, popular opinion, and passing fads.  CGI, for example, has not been favoured lately, since the need to launch external programs limits scalability.


问:
Average number of comparison for sort algorithms
I need to write different sort algorithms such as

bubbleSort

insertionSort

selectionSort

quickSort

mergeSort

And measure how many average comparison does each one for N number (averaging between N! tests). But I need some final results to compare my program results.

Is there any table giving the average of comparisons of these algorithms for a few N numbers?

This is what I have got for average of array length 10:

```<code>    Selection sort: 63
    Bubble sort: 49.4144
    Insertion sort: 31.5
    Merge sort: 31.6667
    Quick sort: 30.7706
</code>```

答:
One great resource: http://bigocheatsheet.com/

I can tell you right off the bat that:

Bubble Sort is in worst case, O(N2)

Insertion Sort is in worst case,  O(N2)

Selection Sort is in worst case, O(N2)

Quick Sort is in worst case, O(N2), yet is typically O(n log n)

Merge Sort is in worst case, O(n log n)