问:
JavaScript securely retrieve data from server
I made an android application for the creation of personal timetables. I need two things for the user interface: The grades list and the student lists of the senior grades. To retrieve those, I made a java websocket from which I can get the list. Since I don't want everyone to get the student lists from my server, I secured the connection (using a self signed certificate). Now I'm building a ui for this, similar to the ui on android.

My problem is: How can I securely get the student lists?

I know that I can't connect to a normal server socket in javascript.
Sorry if the answer is obvious, but that's the first time I'm developing a web application. I just don't know how to start off, I haven't found anything on the internet.

答:
Connecting

As for connecting from JavaScript, you can make HTTP(S) requests using normal client tools, either an XHR in plain JavaScript, or using framework objects like jQuery.ajax() from jQuery or $http from Angular. WebSockets are also available from supporting browsers. Here is a tutorial on how to get started with that.

Security

I want to address 3 separate security layers here.

First there is connection-level security. This answers the question: Can someone other than the client and the server see the data transmitted. Using HTTP, any device that can see your traffic (other wifi users, routers between client and server) can intercept the data and read it because it is plain text. HTTPS helps address this concern by encrypting the data so that even though it can be intercepted, it can't be understood (practically speaking). Also, HTTPS is still not considered secure unless you get a signed certificate. A signed cert is essentially being vouched-for by a trusted authority.

Second, there is Authentication. Can a particular client access my application? Having only HTTPS, any client (e.g. browser navigating to URL) can still access the data. You have to add an authentication (login) to your application so that you can tie that particular client to a valid user of the system. Common today is token-based authentication where you issue a token when the user successfully authenticates. Then the token is sent with each request to identify the user. To be secure, this requires HTTPS. Otherwise, the token can be read, copied, and used by any listener. Search terms here are OAuth, bearer token.

Third, there is Authorization. Having only Authentication, you can say it's a valid user of the system, but you still cannot say what that user is able to do in the system. If all users are capable of the same actions, then Authentication is enough. However, if some users have different operations available from others, then you also need Authorization to instruct your server what the user is allowed (authorized) to do. The common way to do this is either by Roles or Claims. When the user is authenticated, often the user's authorization (role or list of claims) is also loaded into memory. Subsequent requests with the same token can look up the user's authorizations to decide whether or not they can perform the given operation in the system. Search terms here are Role-based or Claims-based authorization.


问:
No central database
I have a client that is looking to get a website/mobile apps/desktop apps built that deal with very sensitive data (more sensitive than bank/card details). Because of the sensitive nature of the data, they do not want to save it in a central database but they still want their apps to synchronise (let's say I add some data into my mobile app, I then want to be able to go to my desktop app and see the same data).

I cannot think of a nice, reliable way of doing this and I am not sure there is one. Which is why I am here. Does anyone know how I could deal with this data?

One solution I was thinking about was to have a client side database on each app that would somehow sync between apps, I can see this being very unreliable and getting messy though.

答:
Your client's concern seems to be about the visibility of this data.  the first question to ask your customer is if the data was encrypted, where can it be stored?  Then, ask your customer what kinds of access controls they want in place before the data can be decrypted and processed - where can the decryption key be stored? is is a seperate key per user? etc...

If your customer doesn't want the data stored anywhere, do they want the user to enter it my hand each time?

ContentLicense: CC BY-SA 3.0

Title: No central database


问:
Find index of string in an array of strings where overlap could occur
I am having some trouble writing a variant of sub-string search. Essentially the goal is to write a method that can perform sub-string search except that the source data is in an array of Strings rather the one String.

I have looked around and can't find anyone who has managed to solve this elegantly.

Consider some input data such as:

```<code>final List<String> source = new ArrayList<String>();
source.add("abc");
source.add("def");
source.add("ghi");
source.add("jkl");
source.add("mnop");
</code>```

Now let's say I want to write a method that can return a Pair of the first location of where the target String appears. This Pair represents the first index of the String in the source array where the target appears and its index within that String where the target starts.

Examples with 0 based indices:

```<code>subStringArray(source, "def"); //returns Pair(1,0) - 2nd string - 1st index
subStringArray(source, "ef"); //returns Pair(1,1) - 2nd string - 2nd index
subStringArray(source, "fgh"); //returns Pair(1,2) - 2nd string - 3rd index
subStringArray(source, "hijklmno"); //returns Pair(2, 1) - 3rd string - 2nd index
subStringArray(source, "abcf"); //returns null or Pair(-1,-1);
</code>```

I know it would involve three for loops but I'm not sure how to handle the edge cases, i.e where the target String takes up multiple Strings in the source array.

I should note that I can't allocate more memory.

答:
Hmm, interesting. I think I would opt for a two-pass approach:

First, join all the strings together and check if your pattern exists in the data at all. If it's not found, you don't need to worry about examining the array.

Second, if a match is found, you need to find the array index containing the start of your pattern (if I read your question correctly). There are several ways of going about this. For instance you could shorten your pattern (by gradually clipping the tail end, bisecting it, or something else -- you consider it) until you find a match in an array index. You might even find it's contained entirely within one index, in which case, again, you're done.

If you've found an array index that contains some, but not all, of your pattern, you need to check the next array index (and the next, and the next, if required) until you've matched your entire pattern.

If you get a mismatch during this step, well, you only found a partial match, adn the actual match must be later. In that case, you must consider how much of your just-discarded match you can skip over before you start looking for the new match. For this, look at your pattern: if it contains repetitions ("aaahah!") then you can maybe only skip ahead a single character, but if it's not ("apples") then you can skip as many characters as your pattern is long -- check which array index you can continue looking at.

An alternative method: join the array using a delimiter (so you end up with "abc|def....|mnop) and figure out where to insert delimiter(s) in your target in order to find a match.

A third method: start with the first character of your pattern, and discard all aray indices that don't match it. Add another character from your pattern, and keep going until you've discarded your entire array. Then, go back one step (snip off the last character from your sub-pattern) and you can check the subsequent indices. (This will be slow for long patters.)

...Not that any of this works, either, without additional memory...


问:
Ways of creating expected object for assert
Recently, I started to use TDD. It's really cool and fun but creating expected object for assertEquals is very boring and tedious.

At the moment I see only two way for that:

Straightforward

Creating object in code using million of setters. Using that approach greater part of tests is creating expected object. I think it's not very cool.

Serialization

Writing expected object for example in JSON and then serialize it in test. I can't find disadvantages of that way except possibility of inconsistent state between my beans and test files.

EDIT

toString() (@Kilian Foth comment)

Some kind of serialization, but I think it deserves attention. Define a strictly controlled toString() and then assert equality with a literal string rather than a second object.

Configuring in DI container(inspired by @Spotted)

I remembered about DI. Does anybody configure expected bean in DI (Spring XML for example) and then inject it to test method? Is it bad and unefficient approach or something normal?

Are there any other techniques/approaches or special tools that can accelerate that process?

答:
An other alternative I'd like to suggest is the following:

Instead of checking that the whole result object matches the expected value, write several asserts that check the important properties of the object.

Now, some people claim that you should only have 1 assert in a test. They are right that you should assert 1 thing, but that does not necessarily mean that you only have 1 assert.

Example: suppose you have a testcase that checks that after a bank transaction, some money moved. (Example in pseudo-code):

```<code>function testMoneyMovedAfterTransaction():
    account1 = setupFakeAccount(balance=300)
    account2 = setupFakeAccount(balance=600)
    performTransaction(from=account1, to=account2, amount=100)
    assertEquals(account1.balance, 200)
    assertEquals(account2.balance, 700)
</code>```

See: two asserts, but I'm only asserting one thing: the money moved accounts, as requested.

Similarly, I might write a test for what happens when the balance is too low. That would be asserting that nothing happens to the balances, and you get an exception. That would take three asserts, but you're only asserting nothing changed.

Edit: if you're talking about 'templates' as in generated blobs of text: easiest might be to do a substring-search or regular-expression match against the generated text. For 'templates' as in generated data structures: an assert for individual fields might be the most robust.

Body:
An other alternative I'd like to suggest is the following:

Instead of checking that the whole result object matches the expected value, write several asserts that check the important properties of the object.

Now, some people claim that you should only have 1 assert in a test. They are right that you should assert 1 thing, but that does not necessarily mean that you only have 1 assert.

Example: suppose you have a testcase that checks that after a bank transaction, some money moved. (Example in pseudo-code):

function testMoneyMovedAfterTransaction():
    account1 = setupFakeAccount(balance=300)
    account2 = setupFakeAccount(balance=600)
    performTransaction(from=account1, to=account2, amount=100)
    assertEquals(account1.balance, 200)
    assertEquals(account2.balance, 700)

See: two asserts, but I'm only asserting one thing: the money moved accounts, as requested.

Similarly, I might write a test for what happens when the balance is too low. That would be asserting that nothing happens to the balances, and you get an exception. That would take three asserts, but you're only asserting nothing changed.

Edit: if you're talking about 'templates' as in generated blobs of text: easiest might be to do a substring-search or regular-expression match against the generated text. For 'templates' as in generated data structures: an assert for individual fields might be the most robust.


问:
C# Application GUI design dependent on configuration
I have built quite big WinForms application working in industry for a few years. It communicates with many HW devices. Application can be configured to use or not use some of these devices and GUI is modified by this configuration.
Now, even more devices (and application possible configurations) are going to be added, so I need to refactor whole application, maybe even write the most of it again and it will be very painful work as it was generally my the first bigger project.

I'm especially afraid of making GUI dependent on application configuration. At this moment, I have many controls in my Form.Designer.cs file (created in drag&drop designer), and I'm enabling/disabling some buttons, changing text of some labels, adding or removing panels etc in ArrangeControls() function according to configuration, also in Form.Designer.cs file.

This function is something like this:

```<code>void ArrangeControls(Config hwCfg)
{
    if (!hwCfg.dev1&& !hwCfg.dev2&& !hwCfg.dev3&& !hwCfg.dev4)
    {
        panelDevices.Dispose();
        lastPannel = panelTime;
    }
    else
    {
        if(hwCfg.dev1)
            ...
        else
            ...
    }
    ...
}
</code>```

This is very disgusting solution with few hundreds of lines at this moment and I even need to add more controls and more possible combinations of controls appearance.
Can you suggest me some pattern, how to get this problem under control?

答:
Make the "Configuration-to-GUI" mapping a process of two steps:

let each form provide a set of "low level" features and/or parameters which can be, for example, switched on and and off, or set to a certain value. The feature names/parameter names should typically not reflect a specific device, they should reflect the actual change or meaning in the Form. For example, there might be a feature flag bool showDevicePanel, or an integer parameter tableFoolastColumnWidth.

implement the mapping which device enables which features completely outside the Form's code, in a central place. You can try to utilize a decision table, or add some methods to your Config class, or provide a DSL for defining this mappings, or a mix of those things, whatever suits your needs best.

For example, your Config class might provide a property like

```<code>   public bool ShowDevicePanel
   {
        get{return dev1||dev2||dev3||dev4;}
   }
</code>```

and the ArrangeControls method might look like this:

```<code>void ArrangeControls(bool showDevicePanel, /* more parameters as needed*/)
{
    if (!showDevicePanel)
    {
        panelDevices.Dispose();
        lastPannel = panelTime;
    }
    // more arrangements on other parameters
}
</code>```

That way, you won't need to change the majority of Forms whenever you add a new device. In most cases, it will be sufficient to extend the mapping code and define the specific features and parameters for the new device in one place. Only when a new device needs a completely new feature or kind of parameter in a certain Form, you will have to change that Form.

Body:
Make the "Configuration-to-GUI" mapping a process of two steps:

let each form provide a set of "low level" features and/or parameters which can be, for example, switched on and and off, or set to a certain value. The feature names/parameter names should typically not reflect a specific device, they should reflect the actual change or meaning in the Form. For example, there might be a feature flag bool showDevicePanel, or an integer parameter tableFoolastColumnWidth.

implement the mapping which device enables which features completely outside the Form's code, in a central place. You can try to utilize a decision table, or add some methods to your Config class, or provide a DSL for defining this mappings, or a mix of those things, whatever suits your needs best.

For example, your Config class might provide a property like

   public bool ShowDevicePanel
   {
        get{return dev1||dev2||dev3||dev4;}
   }

and the ArrangeControls method might look like this:

void ArrangeControls(bool showDevicePanel, /* more parameters as needed*/)
{
    if (!showDevicePanel)
    {
        panelDevices.Dispose();
        lastPannel = panelTime;
    }
    // more arrangements on other parameters
}

That way, you won't need to change the majority of Forms whenever you add a new device. In most cases, it will be sufficient to extend the mapping code and define the specific features and parameters for the new device in one place. Only when a new device needs a completely new feature or kind of parameter in a certain Form, you will have to change that Form.


答:
For questions like this, it's easier to speak in code.  The following code is in C#, but you should be able to adapt it to whatever language you're using.

First, you need a method that can determine if your search candidate matches at a particular location (What you're calling a "pair") in the List of Byte Arrays:

    public bool IsMatch(List<byte[]> haystack, byte[] needle, int x, int y)
    {
        int index = 0; // Needle index

        for (int i = x; i < haystack.Count; i++)
            for (int j = y; j < haystack[i].Length && index < needle.Length; j++)
            {
                if (index >= needle.Length || haystack[i][j] != needle[index])
                    return false;
                y = 0;  // continue search at the beginning of the next byte array
                index++;
            }

        return true;
    }
```

<p><code>x</code> and <code>y</code> determine the starting location to begin the matching process (your Pair, essentially).  Now you just need to check for a match at every location in the haystack:</p>

<pre class="lang-cs prettyprint-override"><code>    public Tuple<int, int> Search(List<byte[]> haystack, byte[] needle, int x, int y)
    {
        for (int i= x; i<haystack.Count; i++)
            for (int j = y; j < haystack[i].Length; j++)
             {
                if (IsMatch(haystack, needle, i, j))
                    return new Tuple<int, int>(i, j);
                y=0;
             }

        return new Tuple<int, int>(-1, -1); // Not Found.
    }
</code>```

Call Search() repeatedly with new starting points (based on your previous search result) to get multiple results.

Some tests, to show that it works (you should write more, just to be sure):

    [TestMethod]
    public void Test()
    {
        byte[] needle = new byte[] { (byte)'f', (byte)'g', (byte)'h' };

        var haystack = new List<byte[]>
        {
            new byte[] { (byte)'a', (byte)'b', (byte)'c' },
            new byte[] { (byte)'d', (byte)'e', (byte)'f' },
            new byte[] { (byte)'g', (byte)'h', (byte)'i' },
            new byte[] { (byte)'j', (byte)'k', (byte)'l' },
            new byte[] { (byte)'m', (byte)'n', (byte)'o', (byte)'p' },
         };

        var result1 = IsMatch(haystack, needle, 1, 2 );

        Assert.AreEqual(true, result1);

        var result2 = Search(haystack, needle, 0, 0);
        Assert.AreEqual(1, result2.Item1);
        Assert.AreEqual(2, result2.Item2);
    }
```

Title: Find index of string in an array of strings where overlap could occur

Body:
I am having some trouble writing a variant of sub-string search. Essentially the goal is to write a method that can perform sub-string search except that the source data is in an array of Strings rather the one String.

I have looked around and can't find anyone who has managed to solve this elegantly.

Consider some input data such as:

```<code>final List<String> source = new ArrayList<String>();
source.add("abc");
source.add("def");
source.add("ghi");
source.add("jkl");
source.add("mnop");
</code>```

Now let's say I want to write a method that can return a Pair of the first location of where the target String appears. This Pair represents the first index of the String in the source array where the target appears and its index within that String where the target starts.

Examples with 0 based indices:

```<code>subStringArray(source, "def"); //returns Pair(1,0) - 2nd string - 1st index
subStringArray(source, "ef"); //returns Pair(1,1) - 2nd string - 2nd index
subStringArray(source, "fgh"); //returns Pair(1,2) - 2nd string - 3rd index
subStringArray(source, "hijklmno"); //returns Pair(2, 1) - 3rd string - 2nd index
subStringArray(source, "abcf"); //returns null or Pair(-1,-1);
</code>```

I know it would involve three for loops but I'm not sure how to handle the edge cases, i.e where the target String takes up multiple Strings in the source array.

I should note that I can't allocate more memory.

Body:
For questions like this, it's easier to speak in code.  The following code is in C#, but you should be able to adapt it to whatever language you're using.

First, you need a method that can determine if your search candidate matches at a particular location (What you're calling a "pair") in the List of Byte Arrays:

    public bool IsMatch(List<byte[]> haystack, byte[] needle, int x, int y)
    {
        int index = 0; // Needle index

        for (int i = x; i < haystack.Count; i++)
            for (int j = y; j < haystack[i].Length && index < needle.Length; j++)
            {
                if (index >= needle.Length || haystack[i][j] != needle[index])
                    return false;
                y = 0;  // continue search at the beginning of the next byte array
                index++;
            }

        return true;
    }

x and y determine the starting location to begin the matching process (your Pair, essentially).  Now you just need to check for a match at every location in the haystack:

    public Tuple<int, int> Search(List<byte[]> haystack, byte[] needle, int x, int y)
    {
        for (int i= x; i<haystack.Count; i++)
            for (int j = y; j < haystack[i].Length; j++)
             {
                if (IsMatch(haystack, needle, i, j))
                    return new Tuple<int, int>(i, j);
                y=0;
             }

        return new Tuple<int, int>(-1, -1); // Not Found.
    }

Call Search() repeatedly with new starting points (based on your previous search result) to get multiple results.

Some tests, to show that it works (you should write more, just to be sure):

    [TestMethod]
    public void Test()
    {
        byte[] needle = new byte[] { (byte)'f', (byte)'g', (byte)'h' };

        var haystack = new List<byte[]>
        {
            new byte[] { (byte)'a', (byte)'b', (byte)'c' },
            new byte[] { (byte)'d', (byte)'e', (byte)'f' },
            new byte[] { (byte)'g', (byte)'h', (byte)'i' },
            new byte[] { (byte)'j', (byte)'k', (byte)'l' },
            new byte[] { (byte)'m', (byte)'n', (byte)'o', (byte)'p' },
         };

        var result1 = IsMatch(haystack, needle, 1, 2 );

        Assert.AreEqual(true, result1);

        var result2 = Search(haystack, needle, 0, 0);
        Assert.AreEqual(1, result2.Item1);
        Assert.AreEqual(2, result2.Item2);
    }


答:
You need to back up a couple steps and, in consultation with your client, work out a threat model.  (Yes, that's a link to a 600-page book; yes, I am seriously recommending you read the entire thing.)

A threat model starts by asking questions like

Why does the app need to store this sensitive data in the first place?

Can you avoid storing it at all?

Can it be thrown away after a short time?

Does it truly need to be accessible to more than one device?

If it must be accessible on more than one device, does it need to be stored on more than one device?

Who are the people who are allowed to see each user's sensitive data?

Can this list be made shorter?

Who are the people who may come in contact with each user's sensitive data while trying to do their jobs, but have no need to know it?

Can this list be made shorter?

Can the data be rendered inaccessible to them without harming their ability to do their jobs?

If it can't be inaccessible, can it at least be made incomprehensible?  (This is what encryption does, in the abstract: it renders data incomprehensible.)

Who are the people who want to see the sensitive data, but are not allowed?

What opportunities do they have to get at the data?

What do they want to do with the data once they have it?

How angry will they be if they don't get what they want?

How much money, time, CPU cycles, and human effort are they willing to spend?

Do they care if anyone knows they have seen the data?

Do they want to access specific users' sensitive data, or will anyone's do?

What do they already know?

What do they already have access to?

Once you know the answers to these questions you will be in a much better place to figure out what to do.

Keep in mind that there might be more than one answer to each set of questions, especially the ones dealing with the attackers (the people who want the sensitive data but are not allowed to have it).  If you can't think of at least half a dozen different archetypal attackers, with different motivations, goals, and resources, you've probably missed something.

Also keep in mind that the attackers who cause you (and/or the client) the most trouble, are the most likely to make a giant splash in the media if their attack succeeds, or who do the largest amount of aggregate damage, probably are not the attackers who can cause the greatest harm to individual users if their attack succeeds.  Your client's company rationally cares more about aggregate damage, but the users rationally care more about harm to themselves.

Title: No central database

Body:
I have a client that is looking to get a website/mobile apps/desktop apps built that deal with very sensitive data (more sensitive than bank/card details). Because of the sensitive nature of the data, they do not want to save it in a central database but they still want their apps to synchronise (let's say I add some data into my mobile app, I then want to be able to go to my desktop app and see the same data).

I cannot think of a nice, reliable way of doing this and I am not sure there is one. Which is why I am here. Does anyone know how I could deal with this data?

One solution I was thinking about was to have a client side database on each app that would somehow sync between apps, I can see this being very unreliable and getting messy though.


问:
Bugs showing up with merge on the release branch
When trying to follow the the gitflow model, we have a branch for the releases.  However, we've had complicated merges when trying to merge from develop and bugs have crept in to that branch from this.

What are we doing wrong and how do we keep these merge bugs from showing up?

Our git tree looks like:

```<code>d  r  m
|  |  |
o  |  |
|\ |  |
| \|  |
|  1  |
o  |  |
|  2  |
|  |  |
o  3  |
| /|\ |
|/ | \|
o  |  4
|\ |  |
| \|  |
|  5  |
</code>```

where the o is a change on the development branch.  1 is where the development branch was merged into release, 2 and 3 are commits to fix bugs in the release branch, and then 4 is the release on master.  This then continues with 5 being the merge of development into the release branch again.

答:
Each branch has its role - its purpose. Its entire reason for being. Once that purpose is complete, the branch should be closed for further changes and merged back into the mainline.

Having a perpetual release branch means that the purpose of the branch is never complete, as it is perpetually open for changes. Each time you have a new release, you find yourself merging from the development branch into the release branch. And this isn't a merge of ideas - it is a complete replacement of the state of the release branch with the current head of development efforts. When it isn't a complete replacement of the state of the code from development (which is in theory, ready for release), it provides a place for bugs to creep in that differs between the release branch and the development branch.

That complete replacement of the state rather than a merge is a distinct hint that the old branch is done and this is a new one.  To make that clear to everyone, here is a different release branch.

Consider also the (not unlikely) situation where there are two releases on going at the same time.  The release effort takes two months to do (certification, testing, more testing, fixing bugs that show up in that release effort, recertification, packaging for the different builds).  And now, one month in, another release effort starts for the next release.  This is a different purpose - a different branch.

Or consider the situation where you have a release branch, which you then branch for each platform that you are going to deploy (making the tweaks to get it to work nicely on Mac, Windows, and Unix systems). And while release 1.0 may be out the door for Windows, the Mac and Linux efforts will take another chunk of time(while you are readying the 1.1 release).  Again, each of these is a separate release and a separate branch.

One of my favorite whitepapers on branching is that of Advanced SCM Branching Strategies.  While this has a focus on perforce (a centralized version control system at the time).  The concepts that it puts forward can be clearly mapped into the git-flow model.

In this whitepaper, the packaging role is the one that maps to the git-flow release branch.

The packaging role is often confused with the accumulation or, more commonly, mainline roles. Once the intended development and maintenance have been performed and any accumulation has been done, it is time to prepare the code for release. Such an effort may not be trivial, requiring a team of release engineers and additional fixes beyond those already performed. The policy on a packaging branch is significantly different from that on a maintenance branch, as the packaging role suggests, only the changes necessary to make the product releasable should be addressed.

If work is to proceed on the other product branches, as is likely to happen if patch levels of the product are to be produced, one does not want the release effort to stall progress toward the next patch level. Other packaging branching strategies could even keep minor versions running off of the same mainline, compounding the potential for a stall while the packaging activity takes place.

Using a separate branch to insulate the release effort from the ongoing development and maintenance, and vice versa, is recommended. In a multi-platform environment, it may be advisable to create one packaging branch per platform for the final porting effort. If the porting efforts are staggered, this allows the staggered releases to be reflected in the version hierarchy. If the porting efforts are simultaneous, accumulating the per-platform packagings to a master packaging branch, from which the final build would be performed, should also be considered. This should be determined in advance, as creating the separate packaging branches from the master packaging branch works best.

This is why you separate the release branch from the mainline branch, and also why you separate the release branches from each other.


问:
How to model a box with a key using DDD?
User can create a box with text inside.
When a box is created it will have a key (UUID) assigned.
This key is then will be sent to recipient.
When recipient activates the key, he receives a text inside corresponding box to email.

So given this requirements I found 2 aggregate roots:
Box and Key

Here is a box creation flow (without fails)

```<code>CreateBox -> BoxCreated
BoxCreated -> CreateKey // handled by process manager
KeyCreated -> NotifyRecipient // handled by process manager
</code>```

And activation flow (without fails)

```<code>ActivateKey -> KeyActivated
KeyActivated -> OpenBox // handled by process manager
OpenBox -> BoxOpened
BoxOpened -> SendContentToRecipient // handled by process manager
</code>```

I wonder if it's correct approach to model such a system?

Because in traditional data-centric architecture I would probably have just one entity Box with a property key. And to activate a key I would just SELECT * FROM Box WHERE key = $key mark it as activated and save it back.

答:
Seems to me the Box and Key are part of the same aggregate root.

Use Cases:

```<code>When a user requests a box be built
Then a box is created
 And a key fitting the box is created
 And a recipient key is created

Given a created box
  And a created matching key
  And a recipient notification with key
 When a recipient uses the key from the notification
 Then the box is opened (seal is broken? key is broken?)
  And the content of the box is delivered
</code>```

In such a case, the aggregate root (consistency boundary) here is the locksmith? :) The box and keys for it are issued from the locksmith or box factory.

Command/Event workflow could be:

```<code>BuildBox (with contents) -> BoxCreated
                            KeyCreated (not sure if needed?)
                            RecipientKeyCreated

OpenBox (with Key) -> KeyConsumed (one-time use?)
                      BoxOpened
                      ContentsRemoved

DeliverKeyToRecipient -> (side effects like email)
                         KeyDeliveredToRecipient (if it's important to know)

// process manager
RecipientKeyCreated -> DeliverKeyToRecipient
</code>```

You could try to deliver the key as part of the box building workflow, but often such concerns are external integrations or have other practical policies that you want to handle outside of the domain. Maybe they are even handled by a separate bounded context like Shipping.

Body:
Seems to me the Box and Key are part of the same aggregate root.

Use Cases:

When a user requests a box be built
Then a box is created
 And a key fitting the box is created
 And a recipient key is created

Given a created box
  And a created matching key
  And a recipient notification with key
 When a recipient uses the key from the notification
 Then the box is opened (seal is broken? key is broken?)
  And the content of the box is delivered

In such a case, the aggregate root (consistency boundary) here is the locksmith? :) The box and keys for it are issued from the locksmith or box factory.

Command/Event workflow could be:

BuildBox (with contents) -> BoxCreated
                            KeyCreated (not sure if needed?)
                            RecipientKeyCreated

OpenBox (with Key) -> KeyConsumed (one-time use?)
                      BoxOpened
                      ContentsRemoved

DeliverKeyToRecipient -> (side effects like email)
                         KeyDeliveredToRecipient (if it's important to know)

// process manager
RecipientKeyCreated -> DeliverKeyToRecipient

You could try to deliver the key as part of the box building workflow, but often such concerns are external integrations or have other practical policies that you want to handle outside of the domain. Maybe they are even handled by a separate bounded context like Shipping.


问:
Why is Akka good for concurrency?
I am new to Akka and actor framework - I am sure I am missing something obvious, please accept my apologies in advance.

I keep reading that one of the main points to choose Akka is the way it manages concurrency.

It is not clear to me why Akka is so special; I understand that there are many little actors which are very light and fast; however, how can this help me when two users save a form at the same time?

Wouldn't I still need some sort of concurrency lock (pessimistic/optimistic/etc..)?

答:
One of the advantages of message-processing models like actors and agents is that the traditional concurrency problems (primarily synchronization of shared state) are no longer a problem. The actor can keep private state and update it freely without locks. The actor framework ensures that only one message is processed at a time. With serialized processing, code can be written in a lock-free way.

In your example of users saving a form, assuming the actor was keeping a List of some data from each form, the actor can update the list without locks, because the framework guarantees that only one form will be processed at a time. Traditionally, you would have to lock around the List accesses or use a concurrent list.

Concurrency strategy is a slightly different matter and is still your responsibility (with no strategy being the most common strategy). To change your example slightly, let's say that both users try to update the SAME form instance at the same time. With no concurrency strategy, one's changes will overwrite the other (probably last one wins). That's fine, but at best this results in unexpected behavior for the user whose changes got overwritten. If they view the form they just changed, it will have unexpected values (from the other user). At worst (when we're not just talking about form updates, but things like shipping orders) it could result in losses of various kinds (time, revenue, etc.).

Using a concurrency strategy helps to identify these cases and be able to resolve them based on business rules. For instance Optimistic Concurrency has the user send the version of the form it is updating. When the actor goes to process the change, it notices that the 2nd user thinks it's updating Version 5 when the form is actually at Version 6 because of the first user's update. Now at least we can notify the 2nd user that the form has already changed since they started editing it. Or whatever rules the business wants to enforce there.

In the case of updating a form, you probably don't care as much about concurrency (depends, I guess). But in other cases, it may be a very important thing to at least be able to check and handle violations. You may even want to ignore the concurrency violation, like if the users changed different sections (to continue the form analogy). Or if the change has a large impact on the business (a big order), you want to accept it and resolve minor conflicts later (e.g. yearly contact info update hasn't been completed).

I believe Akka has a number of other dimensions like how it handles failures, supervisors, etc. that are important considerations for devops.

Title: Why is Akka good for concurrency?


答:
Make it somebody else's problem.

Store the data locally in each app, then give users the option to enable synchronization using their own account with a third-party service (Dropbox, Google Drive, etc). Also, think about encrypting any data uploaded to the third-party service (there are pros and cons to doing that).

This gives the appearance that users own their own data, since they have to opt-in to data synchronization. It makes the apps useful for people who don't want any sharing to happen. And it makes someone else responsible (technically and, potentially, legally) for the ongoing headaches of keeping any shared data safe.

Title: No central database


问:
Plotting electrical field lines on a 2d plane
How do you plot equipotential electrical field lines on a 2d plot in MATLAB. Would it be best to use either quiver or contourf? Some example points are:

p1 = (1,1) with 1 coulomb charge.

p2 = (2,2) with 2 coulomb charge.

p3 = (3,3) with 3 coulomb charge.

All information I've found online to do with super position only has scenarios for 2 points, and even then I dont really understand the principle behind plotting these values.

Never really done physics before, so this exercise has blind sided me. Thanks for any help!

答:
This question is ambiguously defined. Electrical field lines (as referenced in the title) are not the same as equipotential lines. Specifically the electric field E followed by electric field lines is related to the electric potential field V by E = −∇V.

In the case of electrical potential, this is a scalar field so equipotential lines are simply contours of constant value of that field. contourf is therefore an ideal choice to visualise this.

As for field lines, quiver will show you the size and direction of vectors in the electric field, but not the field lines. The easiest way to display these in a 2D plane is streamslice.

Calculating and plotting these fields in MATLAB is just a case of setting up the physical equations in a vectorised form and calculating them for a grid of coordinates through which MATLAB can draw contours and field lines.

Using the equation for electrical potential in the form used by rwong's link in the comments above:

```<code>k = 8.987E9; % Coulomb's constant
p = [1,1; 2,2; 3,3];
Q = [1; 2; 3];
[X,Y] = meshgrid(0:0.05:4); % Create a grid of coordinates where V is to be calculated

V = zeros(size(X)); % Start with zero electric potential
for ii = 1:numel(Q) % Superpose the electric potential field of each charge
    V = V + k * Q(ii) ./ hypot(p(ii,1)-X, p(ii,2)-Y);
end

hContour = contourf(X,Y,V);
hColorbar = colorbar;
ylabel(hColorbar,'Electric potential (V)')
</code>```

The default contour spacing will be very tightly packed around the point charges due to the singularities in electrical potential they create. If you have the Statistics Toolbox, you can quickly improve on this by finding contour levels with equal area between them using quantile:

```<code>hContour.LevelList = [0 quantile(V(:),10)];
</code>```

The electric field is simpler to derive from the existing potential field than it is from the raw vector equation:

```<code>[Ex,Ey] = -gradient(V);
validColumns = all(isfinite(Ex) & isfinite(Ey)); % Ignore columns where E contains infinite values due to the point charges since streamslice can't handle them
hold on
hLines = streamslice(X(:,validColumns),Y(:,validColumns),Ex(:,validColumns),Ey(:,validColumns));
set(hLines,'Color','r');
</code>```

Body:
This question is ambiguously defined. Electrical field lines (as referenced in the title) are not the same as equipotential lines. Specifically the electric field E followed by electric field lines is related to the electric potential field V by E = −∇V.

In the case of electrical potential, this is a scalar field so equipotential lines are simply contours of constant value of that field. contourf is therefore an ideal choice to visualise this.

As for field lines, quiver will show you the size and direction of vectors in the electric field, but not the field lines. The easiest way to display these in a 2D plane is streamslice.

Calculating and plotting these fields in MATLAB is just a case of setting up the physical equations in a vectorised form and calculating them for a grid of coordinates through which MATLAB can draw contours and field lines.

Using the equation for electrical potential in the form used by rwong's link in the comments above:

k = 8.987E9; % Coulomb's constant
p = [1,1; 2,2; 3,3];
Q = [1; 2; 3];
[X,Y] = meshgrid(0:0.05:4); % Create a grid of coordinates where V is to be calculated

V = zeros(size(X)); % Start with zero electric potential
for ii = 1:numel(Q) % Superpose the electric potential field of each charge
    V = V + k * Q(ii) ./ hypot(p(ii,1)-X, p(ii,2)-Y);
end

hContour = contourf(X,Y,V);
hColorbar = colorbar;
ylabel(hColorbar,'Electric potential (V)')

The default contour spacing will be very tightly packed around the point charges due to the singularities in electrical potential they create. If you have the Statistics Toolbox, you can quickly improve on this by finding contour levels with equal area between them using quantile:

hContour.LevelList = [0 quantile(V(:),10)];

The electric field is simpler to derive from the existing potential field than it is from the raw vector equation:

[Ex,Ey] = -gradient(V);
validColumns = all(isfinite(Ex) & isfinite(Ey)); % Ignore columns where E contains infinite values due to the point charges since streamslice can't handle them
hold on
hLines = streamslice(X(:,validColumns),Y(:,validColumns),Ex(:,validColumns),Ey(:,validColumns));
set(hLines,'Color','r');


问:
How do I efficiently send notifications for different events to different users based on their preferences?
I'm creating a notification system for particular events.

A user can set the criteria that match particular events (ie. New item, changed item, closed item etc) Items have different characteristics (ie. Minor, Major, Critical). So a user may set up a search for All New Critical Items.

What is the most efficient way to identify the ones that match the users' saved searches and send notifications to them every time an event happens?

One way would be to run ALL the saved searches for all users, every time an event happens and see which items are in those search results and send notifications.

The problem with this method I see is that it is inefficient (saved searches could become quite a few) and the complexity of this algorithm is directly proportional to the number of searches.

Does anyone know how websites, such as property websites do it? They send out emails for new properties that match users' searches.

I'm thinking of a way to map new events to users, given their search somehow without running all the searches.

答:
First, classify your listeners. Second, classify your events. Then, match up events to listeners.

I'm going to assume that you don't have a capability such as following a particular topic, since you didn't mention it.

Classify your listeners by grouping them up into criteria groups. All listeners looking for "New" x "Major" events are in one group. All listeners looking for "New" x "Critical" events are in another group, with overlapping listeners as needed. You will end up with 9 groups, the cross product of action and severity.

When an event occurs, you use the cross product of action and severity to select one of the groups. All of the listeners in the group should receive a notification.

This will have the minimum number of lookups and comparisons, given that user changing their preferences is much rarer than new events happening.


问:
What pattern should one use for multiple interpretations of the same data?
I have a set information that I am able to read in as raw data which corresponds to different physical quantities depending on which device provided that information. Every device contains the same amount of data and the same types, just different fields are interpreted differently. Here's how I have implemented it so far:

```<code>public abstract class SuperData {
    int voltage1;
    int voltage2;

    SuperData(int v1, int v2) {
        voltage1 = v1;
        voltage2 = v2;
    }

    public int getVoltage1 { return voltage1; }
    public int getVoltage2 { return voltage2; }
}

public class CarAData extends SuperData {
    CarAData(int v1, int v2) { super(v1, v2); }

    public int getKeyVoltage { return getVoltage1(); }
    public int getLightVoltage { return getVoltage2(); }
}

public class CarBData extends SuperData {
    CarAData(int v1, int v2) { super(v1, v2); }

    public int getStarterVoltage { return getVoltage1(); }
    public int getCigarretteVoltage { return getVoltage2(); }
}
</code>```

This is just a trivial example; in reality it is about 60 fields that are just a byte array coming over Bluetooth. I am using a factory to create the correct object based on another data stream but the problem is it requires the use of instanceof down the road to know which method to call.

So what pattern is the best way to represent data which has different meanings?

答:
You're describing a Variant Record or Discriminated Union.  They're not directly supported in Java, but as you've already discovered you can simulate them with class hierarchies.

instanceof shouldn't be a problem.  It's a bit of reflection voodoo, but you only have to do it once per record if you cast your object to the correct Type once you identify it.  If the reflection bothers you, include a 'Tag' method in the base class that returns a descriptor of some sort.

It's too bad you're not working in C#; C-like Union structures are supported directly in that language.


问:
What's the REAL benefit of using CDECL? (more specifically pushing instead of reg-ing)
So, I'm learning assembly, and I've come to know the ABIs and i got some basics tests working using the cdecl calling convention to use the c's stdlib under nasm.
But I've seen other Calling Conventions (like topspeed/Clarion/JPI/watcom/borland register(delphi), fastcall, etc).
And I wonder, what are the REAL benefits of using cdecl instead of Clarion.
More specifically Pushing instead of using the registers.

This are some of the benefits i imagined please let me know which of these apply.

I've read that cdecl is important because it allows to use variable parameters, but as I see it, I can do the same using registers.
The problems are to know the count, type and order of the params, but that problem exists on cdecl too. It can be inferred from the format string (in printf) or from the function signature. And if I run out of registers I can push the rest of the params.

I imagine that performance shouldn't be a big thing because cpus manufactures might have optimized everything that they could regardless of the calling convention of mayor use (and this time is cdecl?¿?).
But if I think of raw operations (and disregard caches and writeback buffers) I think it should be faster to use registers instead of the stack (which should be located in ram right?). I mean, is like "inc eax" vs "add eax, 1" (am I right?).

By pushing i create a memory space that goes off when I ret (just like creating a local variable).
That might seem handy (to have a local var just by the time of being called).

But, as most params (in my experience) are used as a read value, and very few times we need them as a variable, to store mutated values, and when you do you are actually dealing with complex structures that are passed as pointers anyway.

So I don't really see the value on creating a memory space BEFORE actually needing it.

As I see, if I do need a variable is better to have the option to create it (like in clarion), but if I don't it would be nice to be able to not create it (like you can't in cdecl).

You preserve the registers.

I can't even think of a positive side. AFAIK the registers are used for intermediary calculations, and as such are volatile in nature. If I think of them as volatile I could push/pop/mov them whenever i need to "hold" the value and only in such cases.
In that sense I see it as the most efficient use (I only access the ram when i need it).

But if I don't do that, and try to "preserve the registers":

callee: I have no certainty whatsoever what the callee code will do with a register (unless is being documented or they adhere to the same calling convention). By hoping it will preserve them, it imposes an artificial constraint on the callee. As the callee has no idea which registers need to be really preserved they'll tend to overpreserve unnecessary registers. (like pusha/popa in x86?) Which sounds really inefficient to me.

caller: the caller have no idea what registers will the callee [s]taint?[/s] use, so it'll just preserve all of them. It'll end up with the same inefficient result as before.

I noticed that linux syscalls as well as 8086 (from my old classes) use registers instead of stack to pass parameters. What happened there?

So those are my thoughts, thanks for all the clarification possible.

Notes:

I am learning, most of this are assumptions based on what i've readed/tried so far. i'll be glad if you correct me as needed (just be nice).

I do understand this are all x86 CC, and in 64 there is another (which i'm not familiar with).

I am not asking which is the "best", i just want to understand more and clarify my assumptions.

I am looking for benefits of the calling convention by itself (by contrasting with others). not by it's side-effects (like compilers and cpus being optimized or its ubiquity)

Basically a theoretical question to understand more of why that way was chosen

答:
Calling conventions depend somewhat on the platform.  On Linux, GCC provides the defacto standard.  This page goes into some detail about the pros and cons of various calling conventions on Linux (albeit with a bit of hyperbole):

Often you will be told that using C library (libc) is the only way, and direct system calls are bad. This is true, to some extent. In general, you must know that libc is not sacred, and in most cases it only does some checks, then calls kernel, and then sets errno. You can easily do this in your program as well (if you need to), and your program will be dozen times smaller, and this will result in improved performance as well, just because you're not using shared libraries (static binaries are faster)

In the Windows world, there are a number of calling conventions, some of which are Microsoft-specific, and some which are no longer supported.  This page explains some of the pros and cons of each.  In particular:

__cdecl is the default calling convention for C and C++ programs. Because the stack is cleaned up by the caller, it can do vararg functions. The __cdecl calling convention creates larger executables than __stdcall, because it requires each function call to include stack cleanup code.

The __stdcall calling convention is used to call Win32 API functions. The callee cleans the stack, so the compiler makes vararg functions __cdecl. Functions that use this calling convention require a function prototype.


问:
Vertical alignment: yea or nay?
For instance, non-vertically aligned:

```<code>Name:   Hamt
Version:  0.1.0
Cabal-Version:  >= 1.2
License:  BSD3
Author:  Jason Baker
</code>```

Or vertically aligned:

```<code>Name:           Hamt
Version:        0.1.0
Cabal-Version:  >= 1.2
License:        BSD3
Author:         Jason Baker
</code>```

Which do you prefer and why?

答:
Unfortunately being a style question, this is very subjective and you will likely have many conflicting results. Moreover, the style to use depends heavily on your usage of TABs or spaces.

As for my two cents, I prefer a variation of the second version. I like this best:

```<code>Name            : Hamt
Version         : 0.1.0
Cabal-Version   : >= 1.2
License         : BSD3
Author          : Jason Baker
</code>```

It is the most readable and easy to use version that I have tried. The only real downside is that I have to figure out what the widest field is, and sometimes end up having to expand all of them when one is too wide (this usually only happens with CSS). However there are a few points that need to be considered.

First, I usually prefer TABs as opposed to spaces, however the actual TAB setting varies; for example, I am accustomed to 4-space TABs for C(++) code or HTML and 2-space TABs for Pascal or Assembler code, whereas for some things like CSS, I have no preference for the TAB width. This variation complicates things enough, but then the editor I use throws in its own complications. Some editors let you set per-language TAB settings, but some don't (even some that have different profiles).

You can avoid this complication by forgoing TABs in favor of spaces. Since code is usually in a fixed-width font, using spaces works fine, whereas if you are formatting fields in a form, resumé, or other non-code text and are using a proportional font, you'll need TABs to keep things aligned.

I prefer TABs in general because even with fixed-width code, I find it frustrating to have to cursor through several spaces for each TAB. I recall that the old Borland IDEs had an option to cursor through TABs (specifically entire lengths of whitespace) as a single entity instead of as two, four, etc. spaces. That made it practical to insert TABs as spaces while making cursor navigation easy and fast. Unfortunately I have not seen any modern, Windows editors that can do that.

Finally, whether or not others will be using your code plays a big factor in the choice of style. I am usually the only one who uses my code, so I can format everything according to my taste without regard to the editors or settings of others. If you are working with others, you will need to take them into account as they will need to consider you.

In summary, readability is good and very desirable, however the settings and editors you and others that need to use the code will be important when making the decision. If you are alone, you may as well just use the format that is most readable. You may need to get used to using it, but it will likely pay off in the long run, especially when you need to come back to code you wrote a while back: readability is as important as comments in understanding what the code does. If you work with others, then you will want to work together to set out some sort of design guide for use by the team.

ContentLicense: CC BY-SA 2.5

Title: Vertical alignment: yea or nay?

Body:
Unfortunately being a style question, this is very subjective and you will likely have many conflicting results. Moreover, the style to use depends heavily on your usage of TABs or spaces.

As for my two cents, I prefer a variation of the second version. I like this best:

Name            : Hamt
Version         : 0.1.0
Cabal-Version   : >= 1.2
License         : BSD3
Author          : Jason Baker

It is the most readable and easy to use version that I have tried. The only real downside is that I have to figure out what the widest field is, and sometimes end up having to expand all of them when one is too wide (this usually only happens with CSS). However there are a few points that need to be considered.

First, I usually prefer TABs as opposed to spaces, however the actual TAB setting varies; for example, I am accustomed to 4-space TABs for C(++) code or HTML and 2-space TABs for Pascal or Assembler code, whereas for some things like CSS, I have no preference for the TAB width. This variation complicates things enough, but then the editor I use throws in its own complications. Some editors let you set per-language TAB settings, but some don't (even some that have different profiles).

You can avoid this complication by forgoing TABs in favor of spaces. Since code is usually in a fixed-width font, using spaces works fine, whereas if you are formatting fields in a form, resumé, or other non-code text and are using a proportional font, you'll need TABs to keep things aligned.

I prefer TABs in general because even with fixed-width code, I find it frustrating to have to cursor through several spaces for each TAB. I recall that the old Borland IDEs had an option to cursor through TABs (specifically entire lengths of whitespace) as a single entity instead of as two, four, etc. spaces. That made it practical to insert TABs as spaces while making cursor navigation easy and fast. Unfortunately I have not seen any modern, Windows editors that can do that.

Finally, whether or not others will be using your code plays a big factor in the choice of style. I am usually the only one who uses my code, so I can format everything according to my taste without regard to the editors or settings of others. If you are working with others, you will need to take them into account as they will need to consider you.

In summary, readability is good and very desirable, however the settings and editors you and others that need to use the code will be important when making the decision. If you are alone, you may as well just use the format that is most readable. You may need to get used to using it, but it will likely pay off in the long run, especially when you need to come back to code you wrote a while back: readability is as important as comments in understanding what the code does. If you work with others, then you will want to work together to set out some sort of design guide for use by the team.


答:
I'm going to write about the Actor Model in general (not just Akka) in comparison with other concurrency models such as the classical lock-based concurrency and the neat transactional memory.

Advantages

Easier concept to understand and use

Lock based concurrency is difficult; in particular is very difficult to get it right because there are many concepts to understand and use in order to be correct and efficient: locks, semaphores, threads, synchronization, mutual exclusion, memory barrier etc.

Actors, on the other hand are a more abstract concept; you have actors which send and receive messages. No need to grasp and use low-level concepts such as the memory barrier.

Enforces immutability

Mutability is a source of many errors and bugs in programming, especially in multi-threaded applications. Actor model solves this issue by enforcing immutability.

Less error prone

Because of the above two reasons

Efficient

Not so efficient as good written lock-based but in general more efficient than software transactional memory.

Easily scalable

Theoretically at least, the application should scale pretty well by adding more actors to perform your jobs. With lock-based is pretty difficult to scale.

Disadvantages

Not all languages easily enforce immutability;

Erlang, the language that first popularized actors has immutability at its core but Java and Scala (actually the JVM) does not enforce immutability.

Still pretty complex

Actors are based on an asynchronous model of programming which is not so straight forward and easy to model in all scenarios; it is particularly difficult to handle errors and failure scenarios.

Does not prevent deadlock or starvation

Two actors can be in the state that wait message one from another; thus you have a deadlock just like with locks, although much easier to debug. With transactional memory however you are guaranteed deadlock free.

Not so efficient

Because of enforced immutability and because many actors have to switch in using the same thread actors won't be as efficient as lock-based concurrency.

Conclusion

Lock-based concurrency is the most efficient but it's hard to program and error-prone; software transactional memory is the most clear, easy to program and less-error prone but it's also the least efficient. Actors are somewhere in between these two models with all aspects: easy of programming, efficiency and error proneness.

Title: Why is Akka good for concurrency?

Body:
I am new to Akka and actor framework - I am sure I am missing something obvious, please accept my apologies in advance.

I keep reading that one of the main points to choose Akka is the way it manages concurrency.

It is not clear to me why Akka is so special; I understand that there are many little actors which are very light and fast; however, how can this help me when two users save a form at the same time?

Wouldn't I still need some sort of concurrency lock (pessimistic/optimistic/etc..)?


问:
Is this the preferred way to do inheritance in JavaScript?
Hey there I'm not new to programming nor javascript but I'm new to the object oriented world of javascript as it differs from languages I know such as java, c# when it comes to object oriented apsects.

Basically I'd like to know is this the way to do inheritance in javascript, how can I improve it, and what pit falls to watch out for thanks

```<code>function Animal(name, age, color){
    this.name  = name;
    this.age   = age;
    this.color = color;
}

Animal.prototype.describeMe = function(){
      console.log("Hello I am " + this.name + " and I am " + this.age + " years old and my color is " + this.color);
};

function Dog(name, age, color, breed){
    Animal.call(this, name, age, color);
    this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);

Dog.prototype.whatAmI = function(){
     console.log("I am a dog");
}

var dog = new Dog("Max", 10, "red", "German Shepard");
dog.whatAmI();
dog.describeMe();
</code>```

答:
What you have there is one of several different, equally valid, approaches to do inheritance in ECMAScript 5.1.

I suspect hat as ECMAScript 2015 becomes more widespread, most uses of inheritance in ECMAScript will be quickly replaced with the new classes. Classes were added in ECMAScript 2015 to support common inheritance patterns. Despite their name, they are not actually classes, they are constructor functions, and they don't add any new language semantics, they are just syntactic sugar for constructor functions, closures, prototypes, property descriptors, etc. all of which already existed in ECMAScript 5.1 or exist in ECMAScript 2015 independent of classes. (In other words: they let ECMAScript stay true to ECMAScript, and don't try to turn it into Java.)

However, that syntactic sugar really is sweet:

```<code>class Animal {
  constructor(name, age, color) {
    this.name  = name;
    this.age   = age;
    this.color = color;
  }

  get description() {
    return "Hello I am " + this.name + " and I am " + this.age + " years old and my color is " + this.color
  }

  describeMe() {
    console.log(this.description);
  }
}

class Dog extends Animal {
  constructor(name, age, color, breed) {
    super(name, age, color);
    this.breed = breed;
  }

  whatAmI() {
   console.log("I am a dog");
  }
}

const dog = new Dog("Max", 10, "red", "German Shepard");
dog.whatAmI();
// I am a dog
dog.describeMe();
// Hello I am Max and I am 10 years old and my color is red
</code>```

This code is going to desugar to something very much like yours, except with some added closures for encapsulation. I also added a getter, which was not present in your version.

Note that much of this syntactic sugar for methods and getters (and setters, which I didn't demonstrate) is actually also available in object literals, not just in class declarations.

Body:
What you have there is one of several different, equally valid, approaches to do inheritance in ECMAScript 5.1.

I suspect hat as ECMAScript 2015 becomes more widespread, most uses of inheritance in ECMAScript will be quickly replaced with the new classes. Classes were added in ECMAScript 2015 to support common inheritance patterns. Despite their name, they are not actually classes, they are constructor functions, and they don't add any new language semantics, they are just syntactic sugar for constructor functions, closures, prototypes, property descriptors, etc. all of which already existed in ECMAScript 5.1 or exist in ECMAScript 2015 independent of classes. (In other words: they let ECMAScript stay true to ECMAScript, and don't try to turn it into Java.)

However, that syntactic sugar really is sweet:

class Animal {
  constructor(name, age, color) {
    this.name  = name;
    this.age   = age;
    this.color = color;
  }

  get description() {
    return "Hello I am " + this.name + " and I am " + this.age + " years old and my color is " + this.color
  }

  describeMe() {
    console.log(this.description);
  }
}

class Dog extends Animal {
  constructor(name, age, color, breed) {
    super(name, age, color);
    this.breed = breed;
  }

  whatAmI() {
   console.log("I am a dog");
  }
}

const dog = new Dog("Max", 10, "red", "German Shepard");
dog.whatAmI();
// I am a dog
dog.describeMe();
// Hello I am Max and I am 10 years old and my color is red

This code is going to desugar to something very much like yours, except with some added closures for encapsulation. I also added a getter, which was not present in your version.

Note that much of this syntactic sugar for methods and getters (and setters, which I didn't demonstrate) is actually also available in object literals, not just in class declarations.


问:
Starting on Web Project now - Do we choose HTML5/JS over Silverlight?
we are about to start on a Web Development project (the planning starts early 2011).

Do we choose HTML5/JS over Silverlight?

Are there any applications which now run on HTML5? Samples?

A simple Google Search led me here. Those look great (especially the Star Wars one!), but they are not what you call proper applications as such.

答:
That depends on what user platforms you're targetting. Do you want to limit your users to only Windows and Mac? If so, Silverlight might be one answer, as Silverlight is only supported for Windows and Mac.

If you want a broader audience, HTML5 is the way to go. However, you need to consider the fact that all browsers are not HTML5 compliant/compatible yet.

Therefore, to play safe, I suggest coding using HTML4 and gathering your userbase statistics and once enough have started using browsers supporting HTML5, then start upgrading your design to HTML5.

Also, did you consider if some of your users will be browsing your site from a mobile phone?


问:
What's the best/most efficent way to create a semi-intelligent AI for a tic tac toe game?
basically I am attempting to make a a efficient/smallish C game of Tic-Tac-Toe. I have implemented everything other then the AI for the computer so far. my squares are basically structs in an array with an assigned value based on the square. For example

```<code>s[1].value = 1;
</code>```

therefore it's a x, and then a value of 3 would be a o. My question is whats the best way to create a semi-decent game playing AI for my tic-tac-toe game? I don't really want to use minimax, since It's not what I need. So how do I avoid a a lot of if statments and make it more efficient.

Here is the rest of my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct state{ // defined
    int state; // 0 is tie, 1 is user loss, 2 is user win, 3 is ongoing game
    int moves;
};

struct square{ // one square of the board
    int value; // 1 is x, 3 is o
    char sign; // no space used
};

struct square s[9]; //set up the struct
struct state gamestate = {0,0}; //nothing

void setUpGame(){ // setup the game
    int i = 0;
    for(i = 0; i < 9; i++){
        s[i].value = 0;
        s[i].sign = ' ';
    }
    gamestate.moves=0;
    printf("\nHi user! You're \"x\"! I'm \"o\"! Good Luck :)\n");
}

void displayBoard(){// displays the game board
    printf("\n %c | %c | %c\n", s[6].sign, s[7].sign, s[8].sign);
    printf("-----------\n");
    printf(" %c | %c | %c\n", s[3].sign, s[4].sign, s[5].sign);
    printf("-----------\n");
    printf(" %c | %c | %c\n\n", s[0].sign, s[1].sign, s[2].sign);
}

void getHumanMove(){ // get move from human
    int i;
    while(1){
        printf(">>:");
        char line[255]; // input the move to play
        fgets(line, sizeof(line), stdin);
            while(sscanf(line, "%d", &i) != 1) { //1 match of defined specifier on input line
            printf("Sorry, that's not a valid move!\n");
            fgets(line, sizeof(line), stdin);
        }
        if(s[i-1].value != 0){printf("Sorry, That moves already been taken!\n\n");continue;}
        break;
    }
    s[i-1].value = 1;
    s[i-1].sign = 'x';
    gamestate.moves++;
}

int sum(int x, int y, int z){return(x*y*z);}

void getCompMove(){ // get the move from the computer

}

void checkWinner(){ // check the winner
    int i;
    for(i = 6; i < 9; i++){ // check cols
        if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
        if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
    }
    for(i = 0; i < 7; i+=3){ // check rows
        if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
        if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
    }
    if((sum(s[0].value,s[4].value,s[8].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
    if((sum(s[0].value,s[4].value,s[8].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
    if((sum(s[2].value,s[4].value,s[6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;}
    if((sum(s[2].value,s[4].value,s[6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;}
}

void playGame(){ // start playing the game
    gamestate.state = 3; //set-up the gamestate
    srand(time(NULL));
    int temp = (rand()%2) + 1;
    if(temp == 2){ // if two comp goes first
        temp = (rand()%2) + 1;
        if(temp == 2){
            s[4].value = 2; s[4].sign = 'o';
            gamestate.moves++;
        }else{
            s[2].value = 2; s[2].sign = 'o';
            gamestate.moves++;
        }
    }
    displayBoard();
    while(gamestate.state == 3){
        if(gamestate.moves<10);
            getHumanMove();
        if(gamestate.moves<10);
            getCompMove();
        checkWinner();
        if(gamestate.state == 3 && gamestate.moves==9){
            printf("The game is a tie :p\n");
            break;
        }
        displayBoard();
    }
}

int main(int argc, const char *argv[]){
    printf("Welcome to Tic Tac Toe\nby The Elite Noob\nEnter 1-9 To play a move, standard numpad\n1 is bottom-left, 9 is top-right\n");
    while(1){ // while game is being played
        printf("\nPress 1 to play a new game, or any other number to exit;\n>>:");
        char line[255]; // input whether or not to play the game
        fgets(line, sizeof(line), stdin);
        int choice; // user's choice about playing or not
        while(sscanf(line, "%d", &choice) != 1) { //1 match of defined specifier on input line
            printf("Sorry, that's not a valid option!\n");
            fgets(line, sizeof(line), stdin);
        }
        if(choice == 1){
            setUpGame(); // set's up the game
            playGame(); // Play a Game
        }else {break;} // exit the application
    }
    printf("\nThank's For playing!\nHave a good Day!\n");
    return 0;
}
</code>```

答:
Trivial, Basic, Simple concept of AI for Tic-tac-toe, which was my 1st test for my AI prototype years ago.

Game

N x N cells. N=3 => 9 cells

Every cell can have 3 states (Empty, 0, 1). Game has 3ˇ9 = 19683 states

Player must choose 1 cell

AI input: State of the game (1 of 81 states)

15 bits for combinations of the state (log2(3ˇ9))

Not: using 2 bits per cell state, 9x2 is 18 bits

AI Output: Cell (move)

Use 3 bits (use 1 of 8 free cells) - yes 9th cell wont be chosen, but we have 9 free cells only in first iteration and only if we start and in this moment it has the same meaning as cell[0]

Not: using 9 bits (1 bit per cell)

Not: using 4 bits (4-bit index of the cell)

AI Feedback: Game won or lost (1 bit)

AI internal

int fbs[MAX_STATES][MAX_MOVES]; // feedbacks

void Feedback(fb)  { fbs[lastState][lastMove] += f; }

U32 Output(state) {

try random move every N_RAND'th time (rand() % N_RAND == 0)

return lastMove = rand() % MAX_MOVES;

Find max(fbs[lastState][m=0..MAX_MOVES])

if found, return m; // risk with this to try opponents other moves.

else, force random

lastState = state; lastMove = m;

Notes: (you can skip those)

As rotations have same meaning, there are less meaningful states and could use less bits for those. But we may want AI to "find" those "meaningfulnesses" out by itself and optimize itself later

Output: Index of free cells (other outputs are impossible)

on 2nd iteration we can have as much as 5 options (log(5)>2bits), so 3b output is good.

There are less meaningful outputs (at 1st iteration: center, corner, side) - could have output as index of meaningful outputs

The impossible and not meaningful moves will be ignored later after "training" by weighting them down (as bad moves) automatically AI.

Could use 4 bit feedback for (lost/won in N steps)

If state not found - could interpolate from similar states instead of trying random

[State][Move] combined are 15+3 18b or less. So you have 157464 or less state-move combinations.

Using 1B resolution/precision for feedback is would use 157KB or RAM (if you move to more complex games, optimizing memory usage becomes you main job). It is wasting as you only wanna sort ~5 possible moves by their fb, so 3b would be enough, but with "arithmetical coding" it's still a big waste of 3rd bit. In the trained and optimized model just 1 bit is enough as you only want the best moves (1) and worse moves' feedback should go to (0) (RAM: 20KB), or just write down the best 3b moves for 19683 state (7.4KB), can be compressed better...

To make it smarter, you could add aging to the feedbacks, so that if game rules change, it (or should we call she) would start winning sooner.

Wiki: "138 terminal board positions"

Can do only 4-5 moves at max before ending in 1 of those 138 positions, means we have less than 5x138 decisions to make, means the best answers are <259B of data (possibly around 100B). Good AI would optimize its RAM usage from 157KB to 0.1KB. The best AI would zip this info probably to <30 bytes and use 157KB RAM for much greater problems.


问:
Java desktop app with mysql database
I'm currently in the process of learning Java and swing and in doing so am trying to create a desktop app.

As part of this app I have set up a mysql database which the app is connected to, however I'm uncertain as to how this would work if I was to distribute the app for other users, how would I create a database that they are able to use on their system if they don't have mySQL installed or the database initiated.

答:
You might have to use Sqlite as a database , because it is a standalone you have to just put inside in your source code only. It eliminates all coasting of mysql server set up and stuff like that !
 By virtue of using sqlite you can remove the overhead of installing mysql through various process. However sqlite accepts almost all create , insert ,delete and update sql queries, it is smart enough to export data and import as well. As far as database heat is concerned using sqlite is a better solution where relatively small data to be stored.In case of large amount of data storage you might have to opt mysql or even oracle odd so, but for relatively small storage of data you can use sqlite very effectually.</p>

Title: Java desktop app with mysql database


问:
Search by Location and Keywords
I have data set with ~5M entries/rows (~2GB). Every entry contains a location field (lat/lon coordinate-pair) and n keyword fields (keyword-1, keyword-2, ... keyword-n). The keyword-fields can all contain multiple keywords, but they are of different importance/"quality".

I need to perform a query on this data set that returns the k "best-matching entries for any given combination of (location, {keyword-1, keyword-2, ... keyword-n}), sorted by match quality.

Match quality is determined first by the count of keyword matches of keyword-1 keywords, then keyword-2 keywords, ... then keyword-n keywords and finally the the distance between the entry-location and the search-location

Currently (for n=3 and k=10) this is implemented inside mysql as a table with the location (and btree-indices on lat/lon) and a table for the (again btree-indexed) keywords. To perform the query a join over the 2 tables is done for keyword-1 keywords and the resultset is sorted and cut off, if the result set had less then k rows the query is repeated for keyword-2 keywords and so on.

This has worked fairly well so far, but as data and query volume increase, the response times have become worrisome. Currently a query takes about 300ms.

I'm unsure how to proceed next.

The "easy" solution would be to get more machines and spread the queries out over them, but then the data would be spread across multiple machines .. which isn't ideal since the data will have to be kept in sync and the load will have to be balanced and services would need to be discovered/located, etc..

I did look at various in-memory solutions, but none of them offer both location-based and keyword-based search or have mature implementations or can run in single-node mode.

If I were to implement this (arguably simple) search service myself, how do I approach it? Quadtrees/Hilbert-Curves/Geohashes seem easy enough to implement, but getting the memory allocation bit right probably still won't be trivial. And then after that, I'd still need to join the results together with those from the keyword search...

Do any of you have experiences with systems like these? Any recommendations on what to do?

答:
Personally I've done similar with a free-text search index (admittedly in Oracle, not MySQL). We created a new column containing all the reference words and simply told the DB to index it, then all queries were performed on that data. The ordering of it by importance was done afterwards in client code.

The free-text search indexing can set word weights, though this differs on implementation. A quick google says MySql has a full-text search index which can set weighting against words used in your query.

I don't know if that helps your specific case, but its a good place to start. Its also fast and flexible for more powerful queries you might use later (we applied a custom double-metaphone algorithm for sounds-like or misspelled searching for example)

Title: Search by Location and Keywords


问:
Which scenarios to use .NET Concurrent Collections effectively?
I am investigating how to introduce parallelism into an application to improve performance. In particular, I am looking at parallel for loops and their variants and my initial experiments show significant overhead to using collections from the System.Collections.Concurrent namespace.

Typical scenario

Want to iterate over a collection in Parallel, perform some computations per iteration and then route/add the results into an appropriate collection depending on the details of the iteration.

[If you don't use the Concurrent Collections you get errors due to the usual multi-threading & synchronization issues so you appear to be forced into using the Concurrent collections.]

Unfortunately my tests mostly/often show that the single-threaded simple solutions perform faster due to the overhead of using the Concurrent Collections - is this to be expected?

Tentative Conclusions

You would need to be doing a "very large" piece of work per iteration for the Concurrent Collections to perform better than a single threaded solution?

Code Example

As per requests in the comments:

open System.Collections.Generic
open System.Collections.Concurrent
open FSharp.Collections.ParallelSeq

type Data = {
    Name:string
    mutable Age:int
    Description:string
}

[<EntryPoint>]
let main argv =

    let xs = ResizeArray<Data>()
    let n = 1000000

    let rand = System.Random()

    // create some random data
    for i in 0..n do
        let f1 = rand.NextDouble()
        let f2 = rand.NextDouble()
        let data = {Name = "My Name" + f1.ToString() + f2.ToString(); Age = 38; Description = "Happy"}
        xs.Add(data)

    // single-threaded example
    let normalCollection = Dictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> Seq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        normalCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Single Threaded: %A" stopWatch.Elapsed

    System.GC.Collect(2)

    // single-threaded + concurrent Collection example
    let concurrentCollection = ConcurrentDictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> Seq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        concurrentCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Single Threaded + Concurrent Collection: %A" stopWatch.Elapsed

    concurrentCollection.Clear()

    System.GC.Collect(2)

    // multi-threaded example
    let concurrentCollection = ConcurrentDictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> PSeq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        concurrentCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Multi-Threaded: %A" stopWatch.Elapsed

    // Functional Style
    normalCollection.Clear()
    System.GC.Collect(2)
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    let ys =
        xs
        |> PSeq.map (fun x -> {x with Age = x.Age + rand.Next()} )
        |> Seq.iter (fun x -> normalCollection.[x.Name] <- x)
    stopWatch.Stop()
    printfn "Functional Style: %A" stopWatch.Elapsed

    printfn "%A" argv
    0 // return an integer exit code
```

Timing

Consistent over multiple runs...

n = 10,000 (small data set)

Single Threaded: 00:00:00.0048328

Single Threaded + Concurrent Collection: 00:00:00.0053433

Multi-Threaded: 00:00:00.0197919

Functional Style: 00:00:00.0073613

n = 10,000,000 (large data set)

Single Threaded: 00:00:04.0683213

Single Threaded + Concurrent Collection: 00:00:13.6469918

Multi-Threaded: 00:00:10.9768615

Functional Style: 00:00:04.6633076

答:
You're missing the point. The concurrent collections aren't there for performance so much. They're there so you don't need to try and do all the locking around a dictionary/queue yourself, since doing so is error prone and tedious. (And they're really there so you don't need to try and implement lockless dictionaries/queues yourself)

Using them effectively is as simple as "hey, I have a queue/dictionary/etc, and it needs to be accessed concurrently. Instead of reinventing the wheel, I will use these pre-built classes". You don't use them to introduce concurrency, you introduce concurrency because you need to, and these things help.


问:
Synchronous architecture with asynchronous repository
In order to keep clean architecture of my node.js microservice I have controllers, services and e.g. repositories.

I want a synchronous data flow: controller -> service -> repository -> service -> controller. In this flow (in simple user story) repository returns data to service and service to controller. But repository should process requests to external storage in a asynchronous way. All asynchronous code should exist only in repository, service should obtain raw data.

My current implementation:

UserController.js

```<code>module.exports.create = function() {
    console.log("In controller: before service call");

    let userDto = JSON.parse(this.request.body);
    let savedUser = userService.createUser(userDto);

    console.log("In controller: after service call");
};
</code>```

UserService.js

```<code>module.exports.createUser = function createUser(userDto) {

    let user = require('../domain/user/User');

    user.login = userDto.login;
    user.password = userDto.password;

    let userRepository = require('../infrastructure/user/UserRepository');

    Q.spawn(function* () {
        console.log("In service before promise resolve");

        let savedUser = yield userRepository.createUser(user);

        console.log("In service after promise resolve");

        return savedUser;
    });

    console.log("In service: after repository call");
};
</code>```

UserRepository.js

```<code>module.exports.createUser = function createUser(user) {
    console.log("In repository: before save call");

    return new Q.Promise(function(resolve, reject) {

        userEntity.save(function(err, savedUser) {

            console.log("In repository: inside callback after save call");

            if (err) {
                console.log("In repository: inside callback before reject");
                reject(Error('Błąd zapisu danych!'));
            } else {
                console.log("In repository: inside callback before resolve");
                resolve(savedUser);
            }
        });
    });
};
</code>```

Logs:

In controller: before service call

In service before promise resolve

In repository: before save call

In service: after repository call

In controller: after service call

In repository: inside callback after save call

In repository: inside callback before resolve

In service after promise resolve

I would like to get the following sequence of logs:

In controller: before service call

In service before promise resolve

In repository: before save call

In repository: inside callback after save call

In repository: inside callback before resolve

In service after promise resolve

In controller: after service call

答:
I am writing this answer having little to no technical knowledge on the capabilities of Node.js as a server architecture.  I am purely speaking to the high level design in a technology agnostic way.

What you are wishing to create is essentially a Synchronous-over-Asynchronous interface.  This is essentially where you provide a service to a client that promises on a given request, that they have a reasonable expectation of receiving a response from the server in X amount of time.  The Alternate expression of this use case is that no response is received in X amount of time and thus a timeout event occurs.

The Repository wraps an asynchronous interface of some kind that makes no guarantee of when you could receive a response. It could respond back in sub-millisecond or in 8 hours.

The disconnect is that your microservice is essentially making a promise to its client that it can't guarantee.  This is a fundamental flaw in the Sync-over-Async model but not an insurmountable one necessarily.

Essentially you first have to guarantee the order of execution of running processes such that you effectively wait on the Asynchronous interface to return a response and finish executing its callback before you leave the Repository.  If you don't do this then you will experience a racing condition like the example you described in your email.

Typically an application server will spawn a thread of execution for each incoming request to process.  The thread ends when a response has been formulated and sent (again, not sure if this is the same in Node.js).  What you need to do is halt the request thread until the callback has finished execution.

Secondly, when you halt the thread, you need to do so until a prescribed timeout has been reached.  In this way if you timeout waiting for the async process to return, you avoid the thread getting stuck and the server hanging.  You can then return a proper exception fault over your service to the client so that they can take action on it.


问:
Don't quite understand check and set in concurrency
I don't entirely understand check and set behaviour.. here is an example:

```<code>    public static void main(String[] args) {

    List<String> list = Collections.synchronizedList(new ArrayList<>());

    String abc = "123";

    if (!list.contains(abc)) {
        list.add(abc);

        // ... some several lines of code

        list.remove(abc);

    }

}
</code>```

What I don't quite understand...

So I understand that contains and add should be in a synchronized(list) block...

but what about remove?

if not, then what if it was:

```<code>if (list.contains(abc)) {
   list.add(abc);
   list.remove(abc);
}
</code>```

?

I understand that code doesn't make much sense but I just am using it as an example... Does remove have to be in the synchronized block here?

答:
Any time a collection can be accessed by multiple threads without locking at a higher level (e.g. on a per-transaction basis, rather than per-operation), there is a potential for things to go wrong. You can't perform operations conditionally on any property of the collection, because that property could change between testing and execution. You can't iterate over the collection, because it could change during the iteration process. All you can do is add items to it. Therefore, any time you find yourself wanting to use a synchronised collection, take a step back: what you're doing is probably the wrong way of solving your problem.

Synchronisation needs to be at a higher level than the collection, or you need to use a collection that implements the higher level logic your application needs, e.g. a queue.

For your specific example, the potential issue is that an object equal to the element being added could be added by another thread, causing the add operation in the code you quote to fail. The remove operation would then remove the element added by the other thread, which is likely not what you want (the code seems to have the intent of leaving the collection unchanged after it finishes, but changing temporarily during some operation).

Whenever possible, it is best to avoid sharing low-level access to mutable values between threads, and problems like this are the main reason why.


问:
How does the usage of MVC in web development fundamentally differ from the original usage of the pattern?
I recently read an answer regarding MVC and web development, mostly about how it was originally designed for older systems and has since been applied poorly in web development. That being said, I'm sure every pattern has by now been used poorly in web development. But I'd still like to make sure that I don't make the same mistakes in applying this pattern to web development, leading myself and potentially my team into having the same bad experience with MVC.

We now deal with an obscene web-mvc hybrid that, with its awful
  buzzword status, ill definition, and having
  semi-illiterate-programmers as a target demographic, makes a really
  bad publicity to software patterns in general.

MVC, thus, became separation of concerns distilled for people who
  don't really want to think too much about it.

As someone learning about MVC and considering using it in a web application, I'd like to know from an objective perspective how the MVC pattern should be applied to web development.

It's occurred to me that web development, having pre-existing methods for rendering content via the DOM, and with JavaScript being a loosely typed language, MVC probably relates very differently to web development than it does to older systems used when it was first popularized.

Fundamentally speaking, how does the usage of the MVC pattern's (proper) usage in web development differ from its usage in a non-web environment, with strictly typed languages and no DOM and browser rules for easy GUI rendering and alteration? In other words, does the fact that we're ususing

JavaScript, a loosely typed and very different language from the ones used when the MVC pattern was designed

and use the DOM + CSS, a predefined simplified method of rendering content, whereas before web development, applications used their own rendering engines or rendering libraries to display content, perhaps making the MVC pattern more necessary

change the way we should define and use the MVC pattern in a web development environment? Are there any fundamental differences in the original usage of MVC in a non web environment and using MVC in web development?

答: The original use of MVC in desktop GUI frameworks is fundamentally different from server-side MVC frameworks like RoR or ASP.Net MVC. The web MVC architecture is inspired by the original MVC (hence the name) but it is not the same pattern, since the request-response or the web is fundamentally different from an interactive desktop GUI. If you try to think of of it as the same pattern you will just get confused (as the guy you are quoting clearly is), so better to think of it as two different patterns for different architectures which just share the same name.