答:
I'm assuming that you're using .NET for development since you mentioned MSSQL as your database but my recommendations apply to O/RMs available for other platforms as well.

CRUD Soft Deletes and Auditing

For your first issue, CRUD operations and filtering of "soft deletes". The O/RM itself provides a foundation that allows for more complex scenarios to be achieved. Many developers use the patterns and principles of Domain Driven Design when leveraging an O/RM.

One pattern that will help in your scenario is the Repository pattern. The idea of the repository pattern is that it acts like a collection of your Entities (objects that are backed by your database). You can pass it filters (in .NET LINQ expressions) and it returns the objects that match your filter. The beauty of the .NET implementation is that when you back it with Entity Framework or NHibernate, the LINQ expressions get converted to SQL and executed on the database rather than in memory.

"So how does this help me with soft deletes?" you ask.

Your repository can provide a filter that is appended to every query by default. And calling delete on your repository can be implemented by setting the "IsDeleted" property on the Entity rather than deleting it from the DB.

Audit tables can be implemented by triggers if you must. Or for a more advanced solution, there is the Event Sourcing design. With Event Sourcing, you keep a running tally of events that happen in the application. So for instance if you want to find out why the price on a product in your inventory changed, you can look at the event history and see when and why it was changed as well as by whom.

Exposing Services

Once you have created your Domain Model, there is nothing preventing you from creating a wrapper around it to provide Use-case driven access to the Model. This is called the Application Service Layer. It provides a simplified interface to your domain model so that your application can remain shielded from changes that don't directly impact it.

Layers

People get obsessed with complicated architectures...to me there are three simple elements to an application UI, Business Logic, Storage. You might decide to break them up into different conceptual layers (e.g. your Mobile UI has to access a hosted service around your business logic) but for the most part it's splitting hairs.

What Is Business Logic?

This was difficult concept for me to grasp at first when I moved from a database-centric mindset to Domain-Driven Design. The business logic lives in your entities. Which are mapped to the database.

The difference between just mapping classes to tables/objects to rows and Domain-Driven Design, is that DDD Entities are rich Objects in the Object-Oriented sense. One of the principles of Object-Oriented programming is encapsulation, that is your data and the logic surrounding that data are linked together in a class.

Take for example your rule that a Client must have at least one Address. In DDD lingo, this would be called an invariant. Basically, the Domain would not allow you to construct a Client without all of its invariants being valid. What would that look like? You'd have a constructor for your Client entity that takes an address and any other information that is mandatory for a valid Client. There are a few good blog posts about the concept (this one gives a good discussion with links going into further details).

Long story short, the business logic goes with the data that you're storing.

Developers

All of it's subjective. More important than how you do storage is your development methodology, how you get information to you developers what to build. Overall architectural design, how do the various pieces of the solution work together. Once you have a clear direction laid out for these things, how you do storage shouldn't matter.

Final Note

One thing that I don't like about Stored procedures is that you have to duplicate your logic. You write the sproc in the database, then you have to write the code that interacts with the sproc and translates the results into your objects. It's tedious work (and error prone) let the O/RM handle that if you can.


问:
RESTful key-value collection
I am creating a HTTP REST API. I have a large collection of key-value pairs, at /base-url.

I need to provide the ability to get and set values for a key.

My first attempt:

```<code>GET /base-url/{key}

PUT /base-url/{key}
</code>```

The problem is that this requires URL recipes, which as I understand go against the hypermedia principles of REST.

What is the usual way of providing a key-value store via a RESTful API?

答:
This is allowed by REST as long as your {key} URLs are discoverable; for example if doing

```<code>GET /base-url/
</code>```

returned a list of links to other valid REST resources, and among those were /base-url/{key}

The main point is that out-of-band knowledge can't be required by a REST-conforming API; but if a provider publishes a specification the client is certainly free to go directly to a URL it already knows about.

I found this article by Roy Fielding useful to clarify these points, in particular

```<code>A REST API must not define fixed resource names or hierarchies (an obvious coupling
of client and server). Servers must have the freedom to control their own namespace.
Instead, allow servers to instruct clients on how to construct appropriate URIs, such
as is done in HTML forms and URI templates, by defining those instructions within
media types and link relations. [Failure here implies that clients are assuming a
resource structure due to out-of band information, such as a domain-specific standard,
which is the data-oriented equivalent to RPC's functional coupling].
</code>```

This essentially means that if you publish a spec and the client/programmer needs that in order to determine the valid URLs, then you've created an API but it's not a REST API. To conform with Roy Fielding's thesis defining REST, you must make those same URLs discoverable by starting at the root.

ContentLicense: CC BY-SA 3.0

Title: RESTful key-value collection

Body:
This is allowed by REST as long as your {key} URLs are discoverable; for example if doing

GET /base-url/

returned a list of links to other valid REST resources, and among those were /base-url/{key}

The main point is that out-of-band knowledge can't be required by a REST-conforming API; but if a provider publishes a specification the client is certainly free to go directly to a URL it already knows about.

I found this article by Roy Fielding useful to clarify these points, in particular

A REST API must not define fixed resource names or hierarchies (an obvious coupling
of client and server). Servers must have the freedom to control their own namespace.
Instead, allow servers to instruct clients on how to construct appropriate URIs, such
as is done in HTML forms and URI templates, by defining those instructions within
media types and link relations. [Failure here implies that clients are assuming a
resource structure due to out-of band information, such as a domain-specific standard,
which is the data-oriented equivalent to RPC's functional coupling].

This essentially means that if you publish a spec and the client/programmer needs that in order to determine the valid URLs, then you've created an API but it's not a REST API. To conform with Roy Fielding's thesis defining REST, you must make those same URLs discoverable by starting at the root.


问:
Why does GCC use AT&T syntax by default?
I think title says it all :)

Is there any particular practical reason (I guess it's mostly historic, but I'm unable to find it on my own) why GCC uses AT&T/GAS syntax?

Note: I know this is just default and you can switch it

Note 2: I personally find "Intel syntax" much more readable, so that's why it surpises me.

答:
GCC uses AT&T syntax by default because it was originally written on a system that either used AT&T System V (now known as UNIX) or had syntax that closely resembled System V.

From Wikipedia on GCC

In an effort to bootstrap the GNU operating system, Richard Stallman asked Andrew S. Tanenbaum, the author of the Amsterdam Compiler Kit (also known as the Free University Compiler Kit) if he could use that software for GNU. When Tanenbaum told him that while the Free University was free, the compiler was not, Stallman decided to write his own. Stallman's initial plan was to rewrite an existing compiler from Lawrence Livermore Laboratory from Pastel to C with some help from Len Tower and others. Stallman wrote a new C front end for the Livermore compiler, but then realized that it required megabytes of stack space, an impossibility on a 68000 Unix system with only 64K, and concluded he would have to write a new compiler from scratch. None of the Pastel compiler code ended up in GCC, though Stallman did use the C front end he had written.

Note the following part:

Stallman wrote a new C front end for the Livermore compiler, but then realized that it required megabytes of stack space, an impossibility on a 68000 Unix system with only 64K...

Given that GCC was first released March 22, 1987* and that System V Release 3 was released in 1986**, it's highly likely that GCC was written on either SVR2 or SVR3.

The Wikipedia quote makes it clear that Stallman was working on the Lawrence Livermore Labs' equipment, which was Unix based and therefore System V.  So we could stop there and just say "that's what he had to work on."  But it's also interesting to look at the available MS-DOS / PC-DOS systems at that point in time.  According to this timeline, the likely candidate for PC-DOS1 would have been version 3.2.

PCs (personal computers) weren't as widely used in academic or research settings at that point in time because their networking facilities were not as good as what Unix based systems could provide.  There was also a historical preference for server / terminal type environments.  Server / terminal systems had been available prior to the existence of PCs and generally provided much greater processing power and other resources than what a PC could affordably provide.

So while Stallman could have developed GCC on a PC, he likely would not have wanted to since his primary work would have been on Unix systems.

And as noted in a comment, there was an underlying architectural difference between the CPUs powering Unix systems and PCs.

Put all those pieces together and it's pretty clear why Stallman chose the AT&T syntax over Intel when developing GCC.

1 Note that it's easiest to say that MS-DOS was called PC-DOS prior to version 3.31. That being said, there's a lot to the history of DOS development that's outside the scope of this question.


问:
Determining the winning condition for Tic-Tac-Toe
I'm writing a tic-tac-toe game in C++ and now I found a function to check if a player has a winning board for a connect four game.

The function looks like this:

```<code>bool haswon(int64_t board)
{
    int64_t y = board & (board >> 7);
    if (y & (y >> 2 * 7)) // check \ diagonal
        return true;
    y = board & (board >> 8);
    if (y & (y >> 2 * 8)) // check horizontal -
        return true;
    y = board & (board >> 9);
    if (y & (y >> 2 * 9)) // check / diagonal
        return true;
    y = board & (board >> 1);
    if (y & (y >> 2))     // check vertical |
        return true;
    return false;
}
</code>```

I would be looking for an explanation of the above function.

Then I could perhaps try to implement the same thing for my tic-tac-toe. I'm fairly OK with the bitwise operators

```<code>#include <iostream>
#include <bitset>

namespace tictactoe {

    constexpr std::size_t N = 3;

    using board = std::bitset<N*N>;

    constexpr char NOUGHT = 'O';
    constexpr char CROSS = 'X';

    bool curr_move_noughts = true;

    board combined() {
        return noughts | crosses;    // combined bit board for both players
    }

}
</code>```

答:
Forget that connect 4 function. Apart from being unnecessarily cryptic, checking for a win in connect 4 is more complex than in tac-tac-toe.

In tic-tac-toe there are eight lines to check for - three rows, three columns and two diagonals. The first thing I'm going to suggest is using a single-dimensional array for the board, so the array indexes are as follows...

```<code>+---+---+---+
| 0 | 1 | 2 |
+---+---+---+
| 3 | 4 | 5 |
+---+---+---+
| 6 | 7 | 8 |
+---+---+---+
</code>```

The reason for using a two-dimensional array would be to make it easier to identify locations and easier to loop over them. In this case, I'm going to argue that because the board is so small, it's actually easier to avoid the two dimensions issue. I'm also going to avoid loops, at least for a first attempt, since the scale of the problem is small enough to allow that. So...

```<code>bool line_is_full (Board* p_board, char p_player, int p1, int p2, int p3)
{
  return (   (p_board [p1] == p_player)
          && (p_board [p2] == p_player)
          && (p_board [p3] == p_player));
}

bool board_has_win (Board* p_board, char p_player)
{
  return (   line_is_full (p_board, p_player, 0, 1, 2)
          || line_is_full (p_board, p_player, 3, 4, 5)
          || line_is_full (p_board, p_player, 6, 7, 8)

          || line_is_full (p_board, p_player, 0, 3, 6)
          || line_is_full (p_board, p_player, 1, 4, 7)
          || line_is_full (p_board, p_player, 2, 5, 8)

          || line_is_full (p_board, p_player, 0, 4, 8)

          || line_is_full (p_board, p_player, 2, 4, 6));
}
</code>```

Only checking for one player winning is valid because the only player you need to check for is the player who has just made a move. I'm also not checking for a draw here - just keep count of how many moves have been made to handle that.

Obvious things that could be improved...

The blank lines in board_has_win are there to emphasize groups of similar cases. You could have a loop over the three rows and a loop over the three columns.

Alternatively, board_has_win is an "unwound" loop over all eight lines. There are several ways this could be expressed using a loop. Possibly the most sensible is to have a data table (giving the three cell numbers for each of the eight lines), so you can directly loop over the eight lines.

line_is_full could obviously be rewritten as a loop over the three cells if only those cells were passed as an array.

Alternatively, for each line (given the way I've specified them), (p2-p1) == (p3-p2) - there's a constant stepping distance between cells. Also (p1+p3)/2 == p2 - the position of the middle cell is the average of the two end cells. That means given any two cells (provided you know which two) you can determine the first and the stepping distance and loop over all three.

Personally I'd ignore points 3 and 4 - having a loop rather than three cases isn't really worth even that small amount of extra complexity. I'd probably focus on point 2 - that table of cell-numbers for each row could have other uses in the program.

Here's a tip I think I first saw back in ye olden days when computer magazines would print listings in BASIC. Each of the lines has three cells. What happens if you assign O the value 1 and X the value 4 (and zero for empty)? Consider the total of the values for the three cells in a line - here's a table...

```<code> 0 .... All three cells empty
 1 .... One O, two empty cells
 2 .... Two Os, one empty cell
 3 .... Three Os - O wins

 4 .... One X, two empty cells
 5 .... One X, one O, one empty cell
 6 .... One X, two Os
 7 .... Impossible

 8 .... Two Xs, one empty cell
 9 .... Two Xs, one O
10 .... Impossible
11 .... Impossible

12 .... Three Xs - X wins
13+ ... Impossible
</code>```

This is a kind of special-case hash table. This is useful not only for spotting a win but also for a very simple AI.

Body:
Forget that connect 4 function. Apart from being unnecessarily cryptic, checking for a win in connect 4 is more complex than in tac-tac-toe.

In tic-tac-toe there are eight lines to check for - three rows, three columns and two diagonals. The first thing I'm going to suggest is using a single-dimensional array for the board, so the array indexes are as follows...

+---+---+---+
| 0 | 1 | 2 |
+---+---+---+
| 3 | 4 | 5 |
+---+---+---+
| 6 | 7 | 8 |
+---+---+---+

The reason for using a two-dimensional array would be to make it easier to identify locations and easier to loop over them. In this case, I'm going to argue that because the board is so small, it's actually easier to avoid the two dimensions issue. I'm also going to avoid loops, at least for a first attempt, since the scale of the problem is small enough to allow that. So...

bool line_is_full (Board* p_board, char p_player, int p1, int p2, int p3)
{
  return (   (p_board [p1] == p_player)
          && (p_board [p2] == p_player)
          && (p_board [p3] == p_player));
}

bool board_has_win (Board* p_board, char p_player)
{
  return (   line_is_full (p_board, p_player, 0, 1, 2)
          || line_is_full (p_board, p_player, 3, 4, 5)
          || line_is_full (p_board, p_player, 6, 7, 8)

          || line_is_full (p_board, p_player, 0, 3, 6)
          || line_is_full (p_board, p_player, 1, 4, 7)
          || line_is_full (p_board, p_player, 2, 5, 8)

          || line_is_full (p_board, p_player, 0, 4, 8)

          || line_is_full (p_board, p_player, 2, 4, 6));
}

Only checking for one player winning is valid because the only player you need to check for is the player who has just made a move. I'm also not checking for a draw here - just keep count of how many moves have been made to handle that.

Obvious things that could be improved...

The blank lines in board_has_win are there to emphasize groups of similar cases. You could have a loop over the three rows and a loop over the three columns.

Alternatively, board_has_win is an "unwound" loop over all eight lines. There are several ways this could be expressed using a loop. Possibly the most sensible is to have a data table (giving the three cell numbers for each of the eight lines), so you can directly loop over the eight lines.

line_is_full could obviously be rewritten as a loop over the three cells if only those cells were passed as an array.

Alternatively, for each line (given the way I've specified them), (p2-p1) == (p3-p2) - there's a constant stepping distance between cells. Also (p1+p3)/2 == p2 - the position of the middle cell is the average of the two end cells. That means given any two cells (provided you know which two) you can determine the first and the stepping distance and loop over all three.

Personally I'd ignore points 3 and 4 - having a loop rather than three cases isn't really worth even that small amount of extra complexity. I'd probably focus on point 2 - that table of cell-numbers for each row could have other uses in the program.

Here's a tip I think I first saw back in ye olden days when computer magazines would print listings in BASIC. Each of the lines has three cells. What happens if you assign O the value 1 and X the value 4 (and zero for empty)? Consider the total of the values for the three cells in a line - here's a table...

 0 .... All three cells empty
 1 .... One O, two empty cells
 2 .... Two Os, one empty cell
 3 .... Three Os - O wins

 4 .... One X, two empty cells
 5 .... One X, one O, one empty cell
 6 .... One X, two Os
 7 .... Impossible

 8 .... Two Xs, one empty cell
 9 .... Two Xs, one O
10 .... Impossible
11 .... Impossible

12 .... Three Xs - X wins
13+ ... Impossible

This is a kind of special-case hash table. This is useful not only for spotting a win but also for a very simple AI.


问:
Find common ancestor

Given X number of leaves (the ringed leaves in the picture) in an unbalanced tree with depth aroun 100-1000 and total number of nodes around 15 000 000. I'm looking for the first common ancestor for those leaves.

What is the most efficient way to  achieve this?

答:
Considering you already have implemented a find method, you can do this:

```<code>struct NodeBin* ancestor(struct NodeBin* n, int i, int j){ // find ancestor of i and j
    struct NodeBin* ni = find(n,i);
    while(ni!=NULL){
        printf("%d\n",ni->data);
        if(find(ni,j)!=NULL) return ni;
        ni=parent(n,ni->data);
    }
    return NULL;
}
</code>```

It basically runs the find method using i's parent as the tree's root, and if it can't find j from there that's not the common ancestor, then it goes one level up to i's grandparent and does that recursively.

Title: Find common ancestor

Body:
Considering you already have implemented a find method, you can do this:

struct NodeBin* ancestor(struct NodeBin* n, int i, int j){ // find ancestor of i and j
    struct NodeBin* ni = find(n,i);
    while(ni!=NULL){
        printf("%d\n",ni->data);
        if(find(ni,j)!=NULL) return ni;
        ni=parent(n,ni->data);
    }
    return NULL;
}

It basically runs the find method using i's parent as the tree's root, and if it can't find j from there that's not the common ancestor, then it goes one level up to i's grandparent and does that recursively.


答:
Using bits to represent a Tic-Tac-Toe board is perfectly fine and is as easy and maintainable as using two dimensional array. Since there are only 8 possibilities for winning condition, you can just check the board against every cases.

```<code>1 0 0       0 1 0      0 0 1     1 1 1    0 0 0
1 0 0       0 1 0      0 0 1     0 0 0    1 1 1
1 0 0       0 1 0      0 0 1     0 0 0    0 0 0

0 0 0       1 0 0      0 0 1
0 0 0       0 1 0      0 1 0
1 1 1       0 0 1      1 0 0
</code>```

To keep the clean-ness of the code, try to abstract the implementation of the board away from the your game logic. It is easier to change the board implementation later if you dislike the bitboard representation.

```<code>class Board
{
    private:
        uint32_t board;

    public:
        Board() { board = 0; }

        /* Check if there is any of our piece
           placed in this (x, y) location */
        bool Check(int x, int y) {
            return (board & (1 << y * 3 + x)) > 0;
        }

        /* Make a move in this (x, y) location */
        void Move(int x, int y) {
            board = board | (1 << y * 3 + x);
        }

        /* Check if we have won */
        bool IsWin()
        {
            return (board & 292) == 292 || (board & 146) == 146 ||
                   (board & 73) == 73 || (board & 448) == 448 ||
                   (board & 56) == 56 || (board & 7) == 7 ||
                   (board & 273) == 273 || (board & 84) == 84;
        }
};
</code>```

Keep two boards for player 1 and player2.

```<code>Board player1;
Board player2;
</code>```

Check if (x, y) location is unoccupied

```<code>if (!player1.Check(x, y) && !player2.Check(x, y)) {
    // unoccupied slot
}
</code>```

Check if player 1 has won

```<code>if (player1.isWin()) {
    // player 1 has won.
}
</code>```

Title: Determining the winning condition for Tic-Tac-Toe

Body:
I'm writing a tic-tac-toe game in C++ and now I found a function to check if a player has a winning board for a connect four game.

The function looks like this:

```<code>bool haswon(int64_t board)
{
    int64_t y = board & (board >> 7);
    if (y & (y >> 2 * 7)) // check \ diagonal
        return true;
    y = board & (board >> 8);
    if (y & (y >> 2 * 8)) // check horizontal -
        return true;
    y = board & (board >> 9);
    if (y & (y >> 2 * 9)) // check / diagonal
        return true;
    y = board & (board >> 1);
    if (y & (y >> 2))     // check vertical |
        return true;
    return false;
}
</code>```

I would be looking for an explanation of the above function.

Then I could perhaps try to implement the same thing for my tic-tac-toe. I'm fairly OK with the bitwise operators

```<code>#include <iostream>
#include <bitset>

namespace tictactoe {

    constexpr std::size_t N = 3;

    using board = std::bitset<N*N>;

    constexpr char NOUGHT = 'O';
    constexpr char CROSS = 'X';

    bool curr_move_noughts = true;

    board combined() {
        return noughts | crosses;    // combined bit board for both players
    }

}
</code>```

Body:
Using bits to represent a Tic-Tac-Toe board is perfectly fine and is as easy and maintainable as using two dimensional array. Since there are only 8 possibilities for winning condition, you can just check the board against every cases.

1 0 0       0 1 0      0 0 1     1 1 1    0 0 0
1 0 0       0 1 0      0 0 1     0 0 0    1 1 1
1 0 0       0 1 0      0 0 1     0 0 0    0 0 0

0 0 0       1 0 0      0 0 1
0 0 0       0 1 0      0 1 0
1 1 1       0 0 1      1 0 0

To keep the clean-ness of the code, try to abstract the implementation of the board away from the your game logic. It is easier to change the board implementation later if you dislike the bitboard representation.

class Board
{
    private:
        uint32_t board;

    public:
        Board() { board = 0; }

        /* Check if there is any of our piece
           placed in this (x, y) location */
        bool Check(int x, int y) {
            return (board & (1 << y * 3 + x)) > 0;
        }

        /* Make a move in this (x, y) location */
        void Move(int x, int y) {
            board = board | (1 << y * 3 + x);
        }

        /* Check if we have won */
        bool IsWin()
        {
            return (board & 292) == 292 || (board & 146) == 146 ||
                   (board & 73) == 73 || (board & 448) == 448 ||
                   (board & 56) == 56 || (board & 7) == 7 ||
                   (board & 273) == 273 || (board & 84) == 84;
        }
};

Keep two boards for player 1 and player2.

Board player1;
Board player2;

Check if (x, y) location is unoccupied

if (!player1.Check(x, y) && !player2.Check(x, y)) {
    // unoccupied slot
}

Check if player 1 has won

if (player1.isWin()) {
    // player 1 has won.
}


问:
An algorithm that spreads similar items across a list
I need an algorithm that distributes same items across a list, so maximizing the distance between occurrences.

E.g.
I have a list of 15 items:

```<code>{a,b,c,c,c,d,e,f,f,f,g,h,h,i,j}
</code>```

The algorithm should reorder these in such a way that all the duplicates are spread as uniformly as possible.

The mentioned list should result in something like this:

```<code>{c,f,a,h,b,c,d,e,c,f,g,c,h,i,j,f}
</code>```

Preferably I'd like pseudo code, and even better would be TSQL (since that is the platform it needs to run on). It needs to process hundreds of these lists in one go.

I also tested a proposed method called 'Weighted shuffle' but this will still allow two of the same items in the list to appear next to each other even when this is not needed.

答:
If you're only worried about spreading the similar rows apart, and not as bothered by making sure they are in regular intervals, you can use something like the following:

It determines a weight for each group of letters, then uses the ROW_NUMBER function to calculate a distribution of sorts. By tweaking the weighting and/or sorting in the final select, you may get the results you need.

```<code>CREATE TABLE #items (letter char(1))
INSERT INTO #items VALUES ('a')
INSERT INTO #items VALUES ('b')
INSERT INTO #items VALUES ('c')
INSERT INTO #items VALUES ('c')
INSERT INTO #items VALUES ('c')
INSERT INTO #items VALUES ('d')
INSERT INTO #items VALUES ('e')
INSERT INTO #items VALUES ('f')
INSERT INTO #items VALUES ('f')
INSERT INTO #items VALUES ('f')
INSERT INTO #items VALUES ('g')
INSERT INTO #items VALUES ('h')
INSERT INTO #items VALUES ('h')
INSERT INTO #items VALUES ('i')
INSERT INTO #items VALUES ('j')
ALTER TABLE #items ADD weight numeric(4,2)

--Add weight for each letter
DECLARE @itemcount numeric(4,2) = (SELECT COUNT(*) FROM #items)
UPDATE #items set weight = @itemcount / (SELECT COUNT(*) FROM #items i WHERE letter = #items.letter)

--Sort items by weight, using row_number to space out letter groups
;WITH cteNumbered AS (SELECT letter, weight, ROW_NUMBER() OVER (PARTITION BY letter ORDER BY letter) as rownum FROM #items)
SELECT letter from cteNumbered ORDER BY rownum * weight, weight desc, letter
</code>```

Body:
If you're only worried about spreading the similar rows apart, and not as bothered by making sure they are in regular intervals, you can use something like the following:

It determines a weight for each group of letters, then uses the ROW_NUMBER function to calculate a distribution of sorts. By tweaking the weighting and/or sorting in the final select, you may get the results you need.

CREATE TABLE #items (letter char(1))
INSERT INTO #items VALUES ('a')
INSERT INTO #items VALUES ('b')
INSERT INTO #items VALUES ('c')
INSERT INTO #items VALUES ('c')
INSERT INTO #items VALUES ('c')
INSERT INTO #items VALUES ('d')
INSERT INTO #items VALUES ('e')
INSERT INTO #items VALUES ('f')
INSERT INTO #items VALUES ('f')
INSERT INTO #items VALUES ('f')
INSERT INTO #items VALUES ('g')
INSERT INTO #items VALUES ('h')
INSERT INTO #items VALUES ('h')
INSERT INTO #items VALUES ('i')
INSERT INTO #items VALUES ('j')
ALTER TABLE #items ADD weight numeric(4,2)

--Add weight for each letter
DECLARE @itemcount numeric(4,2) = (SELECT COUNT(*) FROM #items)
UPDATE #items set weight = @itemcount / (SELECT COUNT(*) FROM #items i WHERE letter = #items.letter)

--Sort items by weight, using row_number to space out letter groups
;WITH cteNumbered AS (SELECT letter, weight, ROW_NUMBER() OVER (PARTITION BY letter ORDER BY letter) as rownum FROM #items)
SELECT letter from cteNumbered ORDER BY rownum * weight, weight desc, letter


答:
Independent from implementing a key-value-store or whatever: you could use HATEOAS to describe your api. This enrichens the plain ressource information with meta-information what to do with your API. So in your example a call to base gives a collection of keys and their values:

```<code>GET /baseurl/
</code>```

gives you a resultset:

```<code>    [
    {
        "links": {
            "self": {
                "href": "http://www.yoursite/base"
            },
            "item": [
                {
                    "href": "http://www.yoursite/base/key1"
                },
                {
                    "href": "http://www.yoursite/base/key2"
                },
                {
                    "href": "http://www.yoursite/base/key3"
                }
            ]
        },
        "content": [
            {
                "key": "key1",
                "value": "value1",
                "links": [
                    {
                        "self": {
                            "href": "http://www.yoursite/base/key1"
                        }
                    }
                ]
            },
            {
                "key": "key2",
                "value": "value2",
                "links": [
                    {
                        "self": {
                            "href": "http://www.yoursite/base/key2"
                        }
                    }
                ]
            },
            {
                "key": "key3",
                "value": "value3",
                "links": [
                    {
                        "self": {
                            "href": "http://www.yoursite/base/key3"
                        }
                    }
                ]
            }
        ]
    }
]
</code>```

A simple GET against your baseurl shows a list of items returned. Each with a link (at least) to the single item (or more if you want to relate several keys to other ressources). From that I - as a consumer - know, that there is a ressource key3 behind the URL http://www.yoursite/base/key3. Analogous I know, that I (eventually) could use the typical HTTP-verbs (HEAD, GET,PUT,POST,DELETE, PATCH). But I can query that ressurce for its capabilities via an OPTIONS-Request. Its answer would contain an Allow-Section, which shows allowed verbs:

```<code>Allow: OPTIONS, GET, HEAD, POST, PUT, DELETE
</code>```

When implemented in this way, your API becomes very intuitive and selfexplaining (independend from the ressources you offer).

Title: RESTful key-value collection

Body:
I am creating a HTTP REST API. I have a large collection of key-value pairs, at /base-url.

I need to provide the ability to get and set values for a key.

My first attempt:

```<code>GET /base-url/{key}

PUT /base-url/{key}
</code>```

The problem is that this requires URL recipes, which as I understand go against the hypermedia principles of REST.

What is the usual way of providing a key-value store via a RESTful API?

Body:
Independent from implementing a key-value-store or whatever: you could use HATEOAS to describe your api. This enrichens the plain ressource information with meta-information what to do with your API. So in your example a call to base gives a collection of keys and their values:

GET /baseurl/

gives you a resultset:

    [
    {
        "links": {
            "self": {
                "href": "http://www.yoursite/base"
            },
            "item": [
                {
                    "href": "http://www.yoursite/base/key1"
                },
                {
                    "href": "http://www.yoursite/base/key2"
                },
                {
                    "href": "http://www.yoursite/base/key3"
                }
            ]
        },
        "content": [
            {
                "key": "key1",
                "value": "value1",
                "links": [
                    {
                        "self": {
                            "href": "http://www.yoursite/base/key1"
                        }
                    }
                ]
            },
            {
                "key": "key2",
                "value": "value2",
                "links": [
                    {
                        "self": {
                            "href": "http://www.yoursite/base/key2"
                        }
                    }
                ]
            },
            {
                "key": "key3",
                "value": "value3",
                "links": [
                    {
                        "self": {
                            "href": "http://www.yoursite/base/key3"
                        }
                    }
                ]
            }
        ]
    }
]

A simple GET against your baseurl shows a list of items returned. Each with a link (at least) to the single item (or more if you want to relate several keys to other ressources). From that I - as a consumer - know, that there is a ressource key3 behind the URL http://www.yoursite/base/key3. Analogous I know, that I (eventually) could use the typical HTTP-verbs (HEAD, GET,PUT,POST,DELETE, PATCH). But I can query that ressurce for its capabilities via an OPTIONS-Request. Its answer would contain an Allow-Section, which shows allowed verbs:

Allow: OPTIONS, GET, HEAD, POST, PUT, DELETE

When implemented in this way, your API becomes very intuitive and selfexplaining (independend from the ressources you offer).


问:
What does 'Nightly Builds' mean?
I have been using open source projects for a while and been developing upon the open source applications and every so often I come across the words 'Nightly Build' and I have always been curious as to what it actually means. Does it literally mean the projects are done purely as side projects (usually at night after everyone has finished their day jobs) and there's no true contributor/dedicated development team or is it more complex than that?</p>

答:
Nightly builds are good thing, they provide immediate feed back to developers if they broke the build. Having a nightly build means that the software is stable and likely to build for new users. Software that is not built regularly is difficult to release.

Quoted from: https://chess.eecs.berkeley.edu/softdevel/nightly.htm

ContentLicense: CC BY-SA 2.5

Title: What does 'Nightly Builds' mean?


问:
How to deal with Windows .NET configuration files
We use the normal app.config file for the configuration of the application. Although it works for now it has some pretty significant drawbacks:

Upgrading an application with a modified app.config is hard. Either it overwrites the existing configuration file or the upgraded app.config isn't installed at all.

An error in app.config often renders the entire configuration invalid.

The files are read-only and cannot be altered from the application itself.

To overcome these issues I am considering some alternative options.

Custom XML document transformation

An alternative would be to revert back to a custom XML file to prevent these drawbacks. I think of a solution that uses XML document transformation.

The installer will install the default configuration file default.xml and is read-only. It shall never be modified, because it is overwritten during an upgrade. It contains all the default settings and should be sufficient to start the application.

Modifications can be done in the custom-xxx.xml files that are processed in alphabetic order. The modifications are done using the XDT syntax as described here.

The resulting file will be written to configuration.xml that is actually been used. The configuration.xml file should never be directly altered, because it will be overwritten when the application is started again.

I think this approach will have some advantages:

The default configuration can be updated during an application upgrade.

Local configuration changes can be applied and will be persisted during upgrades.

If transformation cannot be applied (syntax error) then the file is skipped, but the default configuration can always be read.

There are some disadvantages too:

XDT is not trivial for most users and error-prone.

Modifying the configuration from within the application is difficult, because you should write an XDT file.

Not all settings can be done outside the app.config, because the .NET framework looks for certain settings in this file.

Custom.xml only

The application has default settings specified in code. These settings can be overriden by the application by using a custom.xml file. This has some advantages:

Defaults are specified in code, so will be upgraded automatically when the application is updated.

Local configuration changes can be applied and will be persisted during upgrades.

If the custom.xml contains errors, then this file is skipped and the default settings can still be used.

Relatively easy to create a GUI to modify the settings and only write the non-default settings.

There are some disadvantages too:

There is no default.xml, so not all options are clearly visible in the XML file.

When the default configuration contains a list, then there is no way to remove items from the list in the custom.xml. Configurations should be modelled in such a way that these circumstances can be handled.

Wrap-up

There are some different scenarios to deal with configuration files. I would like to know how you deal with configurations in situations where the configuration files need to be customized and you want to maintain automatic upgrade scenarios.

答:
In our applications, we only use the app.config to point to the related servers (web, db, license).  Any other kind of configuration data is

either stored as a local user config file (assumed it is configuration data only important for look-and-feel of the application of the local machine, thus dispensable)

or stored in the database (if it is more important configuration data, which has to be backuped)

This means

we never have the need for updating / changing the app.config by the installer after first installation, since it never changes its structure

we provide a GUI within the application for all kind of configurations, database or local file, whatever is necessary

whenever configuration data is extended, the GUI provides meaningful default values, and there is always a button "reset to default" for the related data, or a button "copy from other project", if it is project-related configuration data.

Using this strategy, it actually does not matter for the user or for the customers, how the data is stored internally. Try to avoid the need for the users to edit any XML manually, then your whole question becomes pointless, just choose the format you can process most easily in your program.


问:
Unit of Work Concurrency, how is it handled
I am reading some information about the Unit of Work pattern. There is one thing that is not very clear for me: what will happen when you request a couple of records on a thread (1) and another thread (2) removes one of those records an commit the change?

Is the removed record on the first thread given a “removed” state? The problem with this approach is that the program has to check every time he want to use a record when it still exists. He also has to lock the record when he wants to use it.

I cannot think of  any other approach, how is this problem solved in practice?

答:
In general a unit of work corresponds with a database transaction.  So from that perspective:

```<code>BEGIN TRANSACTION

-- do stuff

COMMIT TRANSACTION
</code>```

Databases are very advanced with how they handle this.  Any data you read after the BEGIN TRANSACTION statement is "locked" to any other thread (note that you can override this behavior in your SELECT statement with some explicit locking options, but I am ignoring that here).  All other threads that want to access the same data will block until this transaction gets committed or rolled back.  That's why it's important to make the work done inside the transaction as short as possible.

In practice, in an application using the repository pattern, there are two typical scenarios:

Read-modify-write all within a transaction

Read in a read-only transaction, modify-write in a later read-write transaction

For scenario 1, imagine you had a button called "Delete old records".  The button would (roughly) do this:

```<code>using(var uow = GetUnitOfWork())
{
    var repository = uow.GetRepository<MyRecord>();
    var oldRecords = repository.Entities
        .Where(x => x.Old)
        .ToList();
    foreach(var record in oldRecords)
    {
        repository.Delete(record);
    }
    uow.Commit(); // sometimes this is optional (default behavior could be to commit)
}
</code>```

Since all of the reading/writing is done inside of a unit of work, which is inside of a database transaction, then if two people clicked this button at the same time, there's no concurrency issue because the database will serialize the requests.

Scenario 2 is much more common, and trickier.  Imagine you have an edit screen, like "edit employee".  You typically don't want to keep a transaction open the whole time the user has the edit screen open, so first you get the employee information and render it to the screen.  Then the user makes changes and clicks the "Save" button.  It's reasonable to assume someone else was also editing that employee at the same time, so both started with the same copy of the employee, made 2 different changes, and then they click "Save" (one of them will click first).

If, inside the save routine, you reload the employee data, modify only the data that changed, and then commit it, then as long as the two users changed something different (user 1 changed the first name and user 2 change the last name) then it's possible that both changes will be made.  However, if you write your save routine such that you copy all the data from your edit screen back into your employee entity and save it, then user 2's changes will overwrite user 1's changes (because user 2 still has the original first name in their screen).  Furthermore, if both user 1 and user 2 changed the same field, then user 2's change will always overwrite user 1's change.  This is not the right way to go about it.

In practice, using something like Entity Framework or NHibernate, there are two concepts: a session and a transaction.  When your edit screen is created, you also create a session.  The session keeps track of all data loaded from the database during that session (including what the original values were).  The session is disposed of when the screen is closed (I'm considering a desktop application here, not a web application).  When you click save, then it starts a transaction, but instead of reloading the data from the database, you just change the original employee entity that you loaded from the database, and then commit the transaction.  The framework then does an UPDATE statement like this (assume the employee table only has 3 columns: "id", "first_name", "last_name"):

```<code>BEGIN TRANSACTION

UPDATE Employee
SET first_name = 'new first name'
WHERE id = 123
    AND first_name = 'old first name'
    AND last_name = 'last name'

COMMIT TRANSACTION
</code>```

This is called optimistic concurrency.  What that means is if someone else changed that record between when you loaded the edit screen and when you clicked save, then the update will fail (and the database will indicate this by saying "0 records updated" instead of "1 record updated").  The framework will detect this error and typically throw an exception (NHibernate throws a StaleObjectStateException).  It's up to you to handle this exception.  Honestly I just show a message like "someone else edited this record at the same time, so you'll have to close this screen and try again."

Note that there is an optimization you can do.  You can add a new column to your table named VERSION.  Then you can configure your framework to use that column instead of checking every single column in the table to see if they're changed, so the update would look like this:

```<code>BEGIN TRANSACTION

UPDATE Employee
SET first_name = 'new first name',
    version = 2
WHERE id = 123
    AND version = 1

COMMIT TRANSACTION
</code>```

So, you're relying on the database to make sure changes are atomic (indivisible) but you have to do some extra work to handle the human element, since people need to get a copy of the data, think about it for a while and make a change, and the data might have changed during that time.  It's up to you as a programmer how you want to handle conflicts like that.

Body:
In general a unit of work corresponds with a database transaction.  So from that perspective:

BEGIN TRANSACTION

-- do stuff

COMMIT TRANSACTION

Databases are very advanced with how they handle this.  Any data you read after the BEGIN TRANSACTION statement is "locked" to any other thread (note that you can override this behavior in your SELECT statement with some explicit locking options, but I am ignoring that here).  All other threads that want to access the same data will block until this transaction gets committed or rolled back.  That's why it's important to make the work done inside the transaction as short as possible.

In practice, in an application using the repository pattern, there are two typical scenarios:

Read-modify-write all within a transaction

Read in a read-only transaction, modify-write in a later read-write transaction

For scenario 1, imagine you had a button called "Delete old records".  The button would (roughly) do this:

using(var uow = GetUnitOfWork())
{
    var repository = uow.GetRepository<MyRecord>();
    var oldRecords = repository.Entities
        .Where(x => x.Old)
        .ToList();
    foreach(var record in oldRecords)
    {
        repository.Delete(record);
    }
    uow.Commit(); // sometimes this is optional (default behavior could be to commit)
}

Since all of the reading/writing is done inside of a unit of work, which is inside of a database transaction, then if two people clicked this button at the same time, there's no concurrency issue because the database will serialize the requests.

Scenario 2 is much more common, and trickier.  Imagine you have an edit screen, like "edit employee".  You typically don't want to keep a transaction open the whole time the user has the edit screen open, so first you get the employee information and render it to the screen.  Then the user makes changes and clicks the "Save" button.  It's reasonable to assume someone else was also editing that employee at the same time, so both started with the same copy of the employee, made 2 different changes, and then they click "Save" (one of them will click first).

If, inside the save routine, you reload the employee data, modify only the data that changed, and then commit it, then as long as the two users changed something different (user 1 changed the first name and user 2 change the last name) then it's possible that both changes will be made.  However, if you write your save routine such that you copy all the data from your edit screen back into your employee entity and save it, then user 2's changes will overwrite user 1's changes (because user 2 still has the original first name in their screen).  Furthermore, if both user 1 and user 2 changed the same field, then user 2's change will always overwrite user 1's change.  This is not the right way to go about it.

In practice, using something like Entity Framework or NHibernate, there are two concepts: a session and a transaction.  When your edit screen is created, you also create a session.  The session keeps track of all data loaded from the database during that session (including what the original values were).  The session is disposed of when the screen is closed (I'm considering a desktop application here, not a web application).  When you click save, then it starts a transaction, but instead of reloading the data from the database, you just change the original employee entity that you loaded from the database, and then commit the transaction.  The framework then does an UPDATE statement like this (assume the employee table only has 3 columns: "id", "first_name", "last_name"):

BEGIN TRANSACTION

UPDATE Employee
SET first_name = 'new first name'
WHERE id = 123
    AND first_name = 'old first name'
    AND last_name = 'last name'

COMMIT TRANSACTION

This is called optimistic concurrency.  What that means is if someone else changed that record between when you loaded the edit screen and when you clicked save, then the update will fail (and the database will indicate this by saying "0 records updated" instead of "1 record updated").  The framework will detect this error and typically throw an exception (NHibernate throws a StaleObjectStateException).  It's up to you to handle this exception.  Honestly I just show a message like "someone else edited this record at the same time, so you'll have to close this screen and try again."

Note that there is an optimization you can do.  You can add a new column to your table named VERSION.  Then you can configure your framework to use that column instead of checking every single column in the table to see if they're changed, so the update would look like this:

BEGIN TRANSACTION

UPDATE Employee
SET first_name = 'new first name',
    version = 2
WHERE id = 123
    AND version = 1

COMMIT TRANSACTION

So, you're relying on the database to make sure changes are atomic (indivisible) but you have to do some extra work to handle the human element, since people need to get a copy of the data, think about it for a while and make a change, and the data might have changed during that time.  It's up to you as a programmer how you want to handle conflicts like that.


问:
OSS Non-Commericial License
I'm working on a project I want to keep open source on GitHub, but I have a licensing problem. I have searched for hours, but I haven't found a license which disallows commercial use/sale of the application. This is very important as I plan to sell it.</p>

答:
The GNU GPL is probably the closest thing to what you are looking for.

While it expressly allows commercial use/sale the copyleft provisions are very good at deterring businesses from using it because they would have to open their source too.

Title: OSS Non-Commericial License


答:
You won't find such a license, since the freedom to use the software commercially is an integral part of the Open Source Definition, specifically see clause (6), emphasis mine:

6. No Discrimination Against Fields of Endeavor

The license must not restrict anyone from making use of the program in a specific field of endeavor. For example, it may not restrict the program from being used in a business, or from being used for genetic research.

And the non-normative rationale in the Annotated Open Source Definition:

The major intention of this clause is to prohibit license traps that prevent open source from being used commercially. We want commercial users to join our community, not feel excluded from it.

The Free Software Definition doesn't spell it out as explicitly as the OSD does, but it is implicit in the four freedoms:

The freedom to run the program as you wish, for any purpose (freedom 0).

The freedom to study how the program works, and change it so it does your computing as you wish (freedom 1). Access to the source code is a precondition for this.

The freedom to redistribute copies so you can help your neighbor (freedom 2).

The freedom to distribute copies of your modified versions to others (freedom 3). By doing this you can give the whole community a chance to benefit from your changes. Access to the source code is a precondition for this.

It is however clarified explicitly in the commentary further down the page:

“Free software” does not mean “noncommercial”. A free program must be available for commercial use, commercial development, and commercial distribution. Commercial development of free software is no longer unusual; such free commercial software is very important. You may have paid money to get copies of free software, or you may have obtained copies at no charge. But regardless of how you got your copies, you always have the freedom to copy and change the software, even to sell copies.

The FSF even has an entire page about Selling Free Software.

So, in short, you haven't found such a license, because such a license cannot possibly exist.

Title: OSS Non-Commericial License

Body: I'm working on a project I want to keep open source on GitHub, but I have a licensing problem. I have searched for hours, but I haven't found a license which disallows commercial use/sale of the application. This is very important as I plan to sell it.</p>


问:
Patterns for subclass constructors that vary the parent class constructor slightly
So, my problem is in the context of an MVC-style approach. The code here is PHP, but I'm hoping this is a design issue independent of it.

```<code>abstract class Controller
{
  private $domain;
  private $view;

  function __construct() {
    $this->domain = new Domain;
    $this->view = new View;
  }
}
</code>```

So I want to create a series of classes that inherit from this abstract class, such as BlogPageController, or ErrorPageController. The constructors for these subclasses would look something like this:

```<code>class BlogPageController
{
  function __construct() {
    $this->domain = new BlogPageDomain;
    $this->view = new BlogPageView;
  }
}
</code>```

The issue I would like to address is having to always define the constructor for my concrete subclasses - is there a way I can have the parent class Constructor do this, but on the condition that instead of creating (for example) a generic Domain object:

```<code>$this->domain = new Domain;
</code>```

It will create a matching Domain:

```<code>$this->domain = new <concrete class>Domain;
</code>```

As in the example above?

答:
The abstract Controller class can't create the right <concrete class>Domain classes, because it doesn't know which concrete class it belongs to and which Domain and View classes it should be associated with.

What you can do is pass in the Domain and View classes from the derived class's constructor.

```<code>abstract class Controller
{
  private $domain;
  private $view;

  function __construct($aDomain, $aView) {
    $this->domain = $aDomain;
    $this->view = $aView;
  }
}

class BlogPageController extends Controller
{
  function __construct() {
    parent::__construct(new BlogPageDomain, new BlogPageView);
  }
}
</code>```

Body:
The abstract Controller class can't create the right <concrete class>Domain classes, because it doesn't know which concrete class it belongs to and which Domain and View classes it should be associated with.

What you can do is pass in the Domain and View classes from the derived class's constructor.

abstract class Controller
{
  private $domain;
  private $view;

  function __construct($aDomain, $aView) {
    $this->domain = $aDomain;
    $this->view = $aView;
  }
}

class BlogPageController extends Controller
{
  function __construct() {
    parent::__construct(new BlogPageDomain, new BlogPageView);
  }
}


问:
Is it appropriate to ask for reasons after rejected after the interview?
I thought I did okay in the interviews but apparently the interviewers didn't think so. Is it appropriate to ask for a reason after I have received the rejection email? After all I don't want to annoy the HR person.

I am a student, so not so much job hunting experience so far. Bear with me if this question sounds stupid.

答:
It's important to be timely and ask the right person, as others have said. When you get your response email/letter/phone call, you need to ask immediately for feedback on your performance at interview. If you wait too long, the interviewers will have moved on to other people and forget the details of why you didn't get the job.

There's a variety of answers you might receive:

Inexperienced in the relevant technologies

Not at the experience level they're hiring for (you're too high/low)

Not a good team fit (see What's a "Professional Fit" interview?)

Vague nondescript brush-off answer. This is the awkward one where someone specifically didn't like something you said or did and just doesn't want you, and they're in a position of authority, so their veto counts.

Try not to get hung up on the response; there's no way you can argue the case - they have already made their decision. All you can do is to digest the feedback and do differently next time if it was something you did wrong, or interview with a different type of role if it wasn't something you did.


问:
Why does this evaluation function work in a connect four game in java
I am exploring how a Minimax algorithm can be used in a connect four game.  I was looking through a program and found this evaluation function.

```<code>private static int[][] evaluationTable = {{3, 4, 5, 7, 5, 4, 3},
                                          {4, 6, 8, 10, 8, 6, 4},
                                          {5, 8, 11, 13, 11, 8, 5},
                                          {5, 8, 11, 13, 11, 8, 5},
                                          {4, 6, 8, 10, 8, 6, 4},
                                          {3, 4, 5, 7, 5, 4, 3}};

//here is where the evaluation table is called
public int evaluateContent() {
        int utility = 128;
        int sum = 0;
        for (int i = 0; i < rows; i++)
            for (int j = 0; j <columns; j++)
                if (board[i][j] == 'O')
                    sum += evaluationTable[i][j];
                else if (board[i][j] == 'X')
                    sum -= evaluationTable[i][j];
        return utility + sum;
    }
</code>```

And then a MiniMax algo is used to evaluate the possible solutions.

I am not sure how/why this works.  Would anyone be able to explain?

答:
The numbers in the table indicate the number of four connected positions which include that space for example:

the 3 in the upper left corner is for one each of horizontal, vertical, and diagonal lines of four which can be made with it.

the 4 beside it is for two horizontal (one including starting in the corner, one starting on it, one vertical, and one diagonal)

This gives a measurement of how useful each square is for winning the game, so it helps decide the strategy.

I believe that the evaluateBoard function returns a number <0 if

int utility = 128

is a typo - it should be initialized to 138 (since the sum of all the values in the table is 276 = 2 x 138). This would make the evaluateBoard function return:

< 0 if the player whose marker is 'X' is likely to win (has the most strategic places based on the utility function)

= 0 if the players are equally likely to win

> 0 if the player whose marker is 'O' is likely to win.


答:
Have you thought about breaking up your config file into several files? Look into configsource, which allows you to refer to a separate file for a section in your config.

```<code><pages configSource="pages.config"/>
</code>```

http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource%28v=vs.110%29.aspx

You can use that to put values that change often into a smaller file, making it easier to maintain.

Title: How to deal with Windows .NET configuration files

Body:
We use the normal app.config file for the configuration of the application. Although it works for now it has some pretty significant drawbacks:

Upgrading an application with a modified app.config is hard. Either it overwrites the existing configuration file or the upgraded app.config isn't installed at all.

An error in app.config often renders the entire configuration invalid.

The files are read-only and cannot be altered from the application itself.

To overcome these issues I am considering some alternative options.

Custom XML document transformation

An alternative would be to revert back to a custom XML file to prevent these drawbacks. I think of a solution that uses XML document transformation.

The installer will install the default configuration file default.xml and is read-only. It shall never be modified, because it is overwritten during an upgrade. It contains all the default settings and should be sufficient to start the application.

Modifications can be done in the custom-xxx.xml files that are processed in alphabetic order. The modifications are done using the XDT syntax as described here.

The resulting file will be written to configuration.xml that is actually been used. The configuration.xml file should never be directly altered, because it will be overwritten when the application is started again.

I think this approach will have some advantages:

The default configuration can be updated during an application upgrade.

Local configuration changes can be applied and will be persisted during upgrades.

If transformation cannot be applied (syntax error) then the file is skipped, but the default configuration can always be read.

There are some disadvantages too:

XDT is not trivial for most users and error-prone.

Modifying the configuration from within the application is difficult, because you should write an XDT file.

Not all settings can be done outside the app.config, because the .NET framework looks for certain settings in this file.

Custom.xml only

The application has default settings specified in code. These settings can be overriden by the application by using a custom.xml file. This has some advantages:

Defaults are specified in code, so will be upgraded automatically when the application is updated.

Local configuration changes can be applied and will be persisted during upgrades.

If the custom.xml contains errors, then this file is skipped and the default settings can still be used.

Relatively easy to create a GUI to modify the settings and only write the non-default settings.

There are some disadvantages too:

There is no default.xml, so not all options are clearly visible in the XML file.

When the default configuration contains a list, then there is no way to remove items from the list in the custom.xml. Configurations should be modelled in such a way that these circumstances can be handled.

Wrap-up

There are some different scenarios to deal with configuration files. I would like to know how you deal with configurations in situations where the configuration files need to be customized and you want to maintain automatic upgrade scenarios.

Body:
Have you thought about breaking up your config file into several files? Look into configsource, which allows you to refer to a separate file for a section in your config.

<pages configSource="pages.config"/>

http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource%28v=vs.110%29.aspx

You can use that to put values that change often into a smaller file, making it easier to maintain.


问:
How to prevent others from using non-thread safe variables in a multithreading environment?
I have an application written in C++ that was originally single threaded, but, due to the increasing complexity of this project, I'll need to expand it to at least two or three threads.

There are only a total of four variables that will be used between more than one thread threads, making it useless to make everything thread-safe. The obvious solution is to just create a mutex for each variable and move on with my life.

However, looking back, this seems like a horrible idea! I'm afraid that another programmer may forget that the majority of the methods and variables are not thread-safe and use a variable in another thread.

Since I'm the main programmer for this project, it doesn't seem like this would be an issue, but I honestly feel like this is bad programming and it feels really messy.

What are some ways to keep the variables separate to make it easier to tell which variable is for which thread? I've been thinking about isolating the code for the thread so it cannot access the other global variables (giving a compile error instead of silently creating a bug). I could also create a namespace or class for each thread. Is there a best practice for this?

答:
Wrap all access to the variables in a thread safe function so that access of the variables from anywhere in the code flows through a single method, and make the variable private.

This way any access of the variable from outside the class will be thread safe.

The next step is to move the variables into their own class, only accessible via the safe methods. (Not one class per variable, just all the variable in a separate class.)

There's always a way for another programmer to mess up the code, but in my experience if you write the code so that the easiest thing for them to do is the safe way, that will be what they do.


问:
Python: Object initialised inside a Class?
Is possible and, if so, common practice to initialize an object inside a class in Python?</p>

```<code>self.field = Class()
</code>```

答:
If you want to do it in a Object Oriented way, you could pass a factory into the class, so that you can instantiate your class using a factory method:</p>

```<code>    self.field = myFactory.GetSomeClass()</code>```

Body:
If you want to do it in a Object Oriented way, you could pass a factory into the class, so that you can instantiate your class using a factory method:

    self.field = myFactory.GetSomeClass()


问:
Swift Protocol Naming Conventions
Coming from a mainly c# background, I'm used to using the term "interface" for describing an object with no implementation that defines behaviour. In c#, the convention is to prepend interface names with "I", as in IEnumerable, etc.

Of course, the concept has different names in different languages. In Swift, the same concept is called a "protocol". When I'm developing protocols, I often have very similar names for the protocol and a class that implements it. So far, I've been appending the word "protocol" to these objects in the same way I'd use "I" in c#, as in EnumerableProtocol, etc.

Any thoughts on a naming convention for protocols in swift?

答:
Swift has matured significantly in the years since this answer was written. The design guidelines now state:

Protocols that describe what something is should read as nouns (e.g. Collection).

Protocols that describe a capability should be named using the suffixes able, ible, or ing (e.g. Equatable, ProgressReporting).

Thank you to David James for spotting this!

Original Answer

Using some form of Hungarian Notation can be a good idea – to represent important concepts that cannot be encoded inside the type system. However, the fact that some identifier refers to a protocol is part of the type system in Swift (and C#), and as such any prefix or suffix only adds noise. Clear prefixes or suffixes are a better idea for concepts such as exceptions or events.

In the absence of an official style guide for Swift, we have to come up with our own, or borrow from existing guides or code. For example, the Objective-C style guide for Cocoa contains this section:

Class and Protocol Names

Protocols should be named according to how they group behaviors:

Most protocols group related methods that aren’t associated with any class in particular. This type of protocol should be named so that the protocol won’t be confused with a class. A common convention is to use a gerund (“...ing”) form:

NSLocking – Good.

NSLock – Poor (seems like a name for a class).

Some protocols group a number of unrelated methods (rather than create several separate small protocols). These protocols tend to be associated with a class that is the principal expression of the protocol. In these cases, the convention is to give the protocol the same name as the class.

An example of this sort of protocol is the NSObject protocol. This protocol groups methods that you can use to query any object about its position in the class hierarchy, to make it invoke specific methods, and to increment or decrement its reference count. Because the NSObject class provides the primary expression of these methods, the protocol is named after the class.

However, the advice of the second point is no longer applicable:

Because the namespace of classes and protocols is unified in Swift, the NSObject protocol in Objective-C is remapped to NSObjectProtocol in Swift. (source)

Here, the …Protocol suffix was used in order to disambiguate the protocol from the class.

The Swift Standard Library contains the protocols Equatable, Comparable, and Printable. These do not use the Cocoa “…ing” form, but rather the “…able” suffix to declare that any instance of this type must support a certain operation.

Conclusion

In a few cases where a protocol only has one relevant implementation, a “…Protocol” suffix can make sense so that the class and protocol can have the same name. However, this should be limited to such cases only.

Otherwise, the name should be some noun reflecting what operations this protocol contains. Using an “…ing” or “…able” form of a verb can be a good starting point, and such names are unlikely to conflict with class names.

The name EquatableProtocol is not recommendable. The name Equatable or Equating would be far better, and I do not expect any class to have the name Equatable. In this case, the Protocol suffix is noise.

Title: Swift Protocol Naming Conventions


问:
Asynchronous Programming in Functional Languages
I'm mostly a C/C++ programmer, which means that the majority of my experience is with procedural and object-oriented paradigms.  However, as many C++ programmers are aware, C++ has shifted in emphasis over the years to a functional-esque style, culminating finally in the addition of lambdas and closures in C++0x.

Regardless, while I have considerable experience coding in a functional style using C++, I have very little experience with actual functional languages such as Lisp, Haskell, etc.

I've recently began studying these languages, because the idea of "no side-effects" in purely functional languages has always intrigued me, especially with regards to its applications to concurrency and distributed computing.

However, coming from a C++ background I'm confused as to how this "no side-effects" philsophy works with asynchronous programming.  By asynchronous programming I mean any framework/API/coding style which dispatches user-provided event handlers to handle events which occur asynchronously (outside the flow of the program.)  This includes asynchronous libraries such as Boost.ASIO, or even just plain old C signal handlers or Java GUI event handlers.

The one thing all of these have in common is that the nature of asynchronous programming seems to require the creation of side-effects (state), in order for the main flow of the program to become aware that an asynchronous event handler has been invoked.  Typically, in a framework like Boost.ASIO, an event handler changes the state of an object, so that the effect of the event is propagated beyond the life-time of the event handler function.  Really, what else can an event handler do?  It can't "return" a value to the call point, because there is no call point.  The event handler is not part of the main flow of the program, so the only way it can have any effect on the actual program is to change some state (or else longjmp to another execution point).

So it seems that asynchronous programming is all about asynchronously producing side-effects.  This seems completely at odds with the goals of functional programming.  How are these two paradigms reconciled (in practice) in functional languages?

答:
Having learned encapsulation from Borland C++ after learning C, when Borland C++ lacked templates that enabled generics, the object orientation paradigm made me uneasy.
Somewhat more natural way to compute seemed filtering data through pipes. The outward stream had separate and independent identity from the inward immutable input stream, rather than be thought of as side-effect, i.e. every data source(or filter) was autonomous from others. The keypress( an example event) constrained the asynchronous user input combinations to the available keycodes. Functions operate on input parameter arguments, and the state encapsulated by class is just shortcut to avoiding explicitly passing repetitive arguments between small subset of functions, besides being precautious to bound context preventing abusing those arguments from any arbitrary function.

Adhering rigidly to particular paradigm causes inconvenience to deal with leaky abstractions, for eg. commercial runtimes such as JRE, DirectX, .net target object oriented proponents foremost. To constrain the inconvenience, languages either opt for scholarly sophisticated monads like Haskell does, or flexible multi-paradigm support like F# eventually got. Unless encapsulation is useful from some multiple inheritance use case, multi-paradigm approach might be superior alternative to some, sometimes complex, paradigm-specific programming patterns.


答:
Adding multi-threading is a major new feature of a class. I think you should treat it like a major new feature, and don't try to sneak it in.

Rethink and refactor the class and it relationships. I would look into creating a new class to represent each threaded task and/or slice of functionality.

If needed you can preserve the old class interface as a proxy to the new cluster of classes.

Title: How to prevent others from using non-thread safe variables in a multithreading environment?

Body:
I have an application written in C++ that was originally single threaded, but, due to the increasing complexity of this project, I'll need to expand it to at least two or three threads.

There are only a total of four variables that will be used between more than one thread threads, making it useless to make everything thread-safe. The obvious solution is to just create a mutex for each variable and move on with my life.

However, looking back, this seems like a horrible idea! I'm afraid that another programmer may forget that the majority of the methods and variables are not thread-safe and use a variable in another thread.

Since I'm the main programmer for this project, it doesn't seem like this would be an issue, but I honestly feel like this is bad programming and it feels really messy.

What are some ways to keep the variables separate to make it easier to tell which variable is for which thread? I've been thinking about isolating the code for the thread so it cannot access the other global variables (giving a compile error instead of silently creating a bug). I could also create a namespace or class for each thread. Is there a best practice for this?


问:
JavaScript strict mode compatibility
While reading about strict mode on MDN I really was surprised to read the following near the end of the page, quote:

Browsers don't reliably implement strict mode yet, so don't blindly
  depend on it. Strict mode changes semantics. Relying on those changes
  will cause mistakes and errors in browsers which don't implement
  strict mode. Exercise caution in using strict mode, and back up
  reliance on strict mode with feature tests that check whether relevant
  parts of strict mode are implemented. Finally, make sure to test your
  code in browsers that do and don't support strict mode. If you test
  only in browsers that don't support strict mode, you're very likely to
  have problems in browsers that do, and vice versa.

As far as I understand it, strict mode is a redused set of "nonstict" mode, thus I can't imagine situation where strict code can't run correctly in a nonstrict browser. So, the question is this statement really makes sense? Is the any situation where strict to "nonstrict" switch will make code invalid?

答:
Strict mode isn't just reduced functionality from "non-strict" mode. There's also some altered functionality. Say we'd like to write the following ES6 code:

```<code>function callOnObjectWithArgs(fn, obj, ...args) {
    fn.apply(obj, args);
}
</code>```

But since browsers haven't implemented the rest operator (...) yet, we could do something like this in strict mode:

```<code>function callOnObjectWithArgs(fn, obj) {
    "use strict";
    var splice = Array.prototype.splice;
    splice.call(arguments, 0, 2); // Remove the first 2 elements (fn & obj)
    fn.apply(obj, arguments);
}

callOnObjectWithArgs(console.log, console, 1, 2, 3); // -> 1 2 3
</code>```

However, this code would not work in "non-strict" mode.

```<code>// Using callOnObjectWithArgs without the "strict mode"; invocation
callOnObjectWithArgs(console.log, console, 1, 2, 3) // -> TypeError: undefined is not a function
</code>```

This is because by removing the first two elements from the arguments object, fn and obj will no longer point to the first two parameters passed to the function, but instead would then point to what was arguments[2] and arguments[3] from before the first two elements were removed (1 and 2). This is because in "non-strict" mode, named function parameters always point to the corresponding indices in the arguments object, whereas named parameters in strict mode are not bound to the arguments object in any way.

This is why you should always write code that is compatible with both strict and regular mode.

Title: JavaScript strict mode compatibility

Body:
Strict mode isn't just reduced functionality from "non-strict" mode. There's also some altered functionality. Say we'd like to write the following ES6 code:

function callOnObjectWithArgs(fn, obj, ...args) {
    fn.apply(obj, args);
}

But since browsers haven't implemented the rest operator (...) yet, we could do something like this in strict mode:

function callOnObjectWithArgs(fn, obj) {
    "use strict";
    var splice = Array.prototype.splice;
    splice.call(arguments, 0, 2); // Remove the first 2 elements (fn & obj)
    fn.apply(obj, arguments);
}

callOnObjectWithArgs(console.log, console, 1, 2, 3); // -> 1 2 3

However, this code would not work in "non-strict" mode.

// Using callOnObjectWithArgs without the "strict mode"; invocation
callOnObjectWithArgs(console.log, console, 1, 2, 3) // -> TypeError: undefined is not a function

This is because by removing the first two elements from the arguments object, fn and obj will no longer point to the first two parameters passed to the function, but instead would then point to what was arguments[2] and arguments[3] from before the first two elements were removed (1 and 2). This is because in "non-strict" mode, named function parameters always point to the corresponding indices in the arguments object, whereas named parameters in strict mode are not bound to the arguments object in any way.

This is why you should always write code that is compatible with both strict and regular mode.


问:
Why squash git commits for pull requests?
Why does every serious Github repo I do pull requests for want me to squash my commits into a single commit?

I thought the git log was there so you could inspect all your history and see exactly what changes happened where, but squashing it pulls it out of the history and lumps it all into one commit.  What is the point?

This also seems to go against the "commit early and commit often" mantra.

答: I agree with the sentiments expressed in other answers in this thread about showing a clear and concise history of features added and bugs fixed.  I did however, want to address another aspect which your question eluded to but did not explicitly state. Part of the hangup you may have about some of git's methods of working is that git allows you to rewrite history which seems strange when being introduced to git after using other forms of source control where such actions are impossible.  Furthermore, this also goes against the generally accepted principle of source control that once something is committed/checked-in to source control, you should be able to revert to that state no matter what changes you make following that commit.  As you imply in your question, this is one of those situations.  I think git is a great version control system; however, to understand it you must understand some of the implementation details and design decisions behind it, and as a result it has a steeper learning curve.  Keep in mind git was intended to be a distributed version control system and that will help to explain why the designers allow git history to be rewritten with squash commits being one example of this.</p>


问:
Batching immutable object changes?
With immutable models, what would be the best way to batch several changes?

For example, let's have a Book that is immutable. I need to change both title and year. I could change one by one, but that would just create one additional object that is not going to be used. Is there any better way for this?

I can imagine only something with constructor:

```<code>new Book(oldBook, newTitle, newYear);
</code>```

or to have external tool for cloning books, that we can use.

答:
One useful pattern is to define a public interface which can report all of the properties associated with the class, as well as a package-private interface which extends it with a few additional members.  A package-private version of the class should be mutable, but the public-facing one should be immutable.  The public-facing class should hold a reference of the private interface type, and implement its members in terms of that private interface.  Additionally, all classes in the package must maintain the invariant that no instance of the mutable type may ever be modified after a reference to it has been stored in a field which could be reachable on another thread.

Invoking a method like WithName(String name) on the public face of the class could cause it to call WithName on the encapsulated object, which would in most cases constructing a NameAdder object which holds the new Name value along with a reference to the encapsulated object itself.  All methods other than GetName and WithName would chain to the encapsulated object; while GetName() would return the new Name, and WithName would return a new NameAdder object which holds the new Name and a reference to the object encapsulated in the NameAdder (rather than a reference to the NameAdder itself).

An obvious problem with this approach is that more and more operands get performed upon an object, the chains of method invocations would become longer and longer.  To mitigate that, the internal interface (and perhaps the public one as well) should include a Flatten method.  Calling Flatten on an implementation of the interface should yield a new object which applies all of the changes that have been added to it via methods like WithName.  One way of accomplishing that would be to construct a new object where every field's value was computed by calling Get on all of the objects involved.  That could be expensive and inefficient, however, if it gets invoked upon an object that's very "deep".

An alternative approach would be to have the private interface include an AsFlattenedMutable method which would an instance of the mutable class to which all appropriate changes had been applied, and to which no reference had ever been stored in any class field anywhere.  The mutable class could implement AsFlattenedMutable to return a clone of itself; a class like NameAdder would implement AsFlattenedMutable to invoke AsFlattenedMutable upon the encapsulated object, modify the name stored in that mutable object, and return the object after the mutation.  This would thus allow even a rather deep modification chain to be resolved rather quickly.

The only slight "gotcha" with that approach is if code modifies an object and then stores a reference into a non-final field, the generated code could potentially resequence the operations so that the reference to the object gets stored before all the modifications are complete.  To properly solve that may require having a new object store a reference to the mutable object into a final field, and then copying the reference from that final-field into the non-final one.  By my understanding of the JVM specification, storing a reference to an object into a final field of an object under construction would prevent the deferral of any pending requests beyond the return of the constructor, and reading the value of that field would prevent the non-final field from being assigned until after the execution of the constructor [if code didn't read the reference from the new object, but instead simply used a pre-existing copy, then the call to the constructor--as well as any pending mutations to the object of interest--could be deferred until after the assignment].

Title: Batching immutable object changes?


答:
Depending on the number of fields, you might find it easier to use the Builder pattern to combine these changes than to create a separate constructor for each possible set of changes. It does requiring one object that is not going to be used (returned), but you can use one builder instance for as many books as you need to change.

```<code>public final class Book {
    private final String title;
    private final Integer year;
    private final List<String> authors;

    public static final class Builder {
        private String title = null;
        private Integer year = null;
        private List<String> authors = null;

        public Book build() {
            return new Book(this);
        }

        public Builder from(Book other) {
            withTitle(other.title);
            withYear(other.year);
            withAuthors(other.authors);

            return this;
        }

        public Builder withTitle(String title) {
            this.title = title;

            return this;
        }

        public Builder withYear(Integer year) {
            this.year = year;

            return this;
        }

        public Builder withAuthors(List<String> authors) {
            if (authors.isEmpty())
                this.authors = Collections.emptyList();
            else
                this.authors = new ArrayList<String>(authors);

            return this;
        }
    }

    private Book(Builder builder) {
        this.title = builder.title;
        this.year = builder.year;
        this.authors = builder.authors;
    }

    public String getTitle() {
        return title;
    }

    public Integer getYear() {
        return year;
    }

    public List<String> getAuthors() {
        return Collections.unmodifiableList(authors);
    }
}
</code>```

To make a new object from an old one:

```<code>Book oldBook = new Book.Builder()//
        .withTitle("Hello")//
        .withYear(1900)//
        .withAuthors(Arrays.asList("Alice"))//
        .build();
Book newBook = new Book.Builder()//
        .from(oldBook)//
        .withTitle("World")//
        .withYear(1901)//
        .build();
</code>```

Title: Batching immutable object changes?

Body:
With immutable models, what would be the best way to batch several changes?

For example, let's have a Book that is immutable. I need to change both title and year. I could change one by one, but that would just create one additional object that is not going to be used. Is there any better way for this?

I can imagine only something with constructor:

```<code>new Book(oldBook, newTitle, newYear);
</code>```

or to have external tool for cloning books, that we can use.

Body:
Depending on the number of fields, you might find it easier to use the Builder pattern to combine these changes than to create a separate constructor for each possible set of changes. It does requiring one object that is not going to be used (returned), but you can use one builder instance for as many books as you need to change.

public final class Book {
    private final String title;
    private final Integer year;
    private final List<String> authors;

    public static final class Builder {
        private String title = null;
        private Integer year = null;
        private List<String> authors = null;

        public Book build() {
            return new Book(this);
        }

        public Builder from(Book other) {
            withTitle(other.title);
            withYear(other.year);
            withAuthors(other.authors);

            return this;
        }

        public Builder withTitle(String title) {
            this.title = title;

            return this;
        }

        public Builder withYear(Integer year) {
            this.year = year;

            return this;
        }

        public Builder withAuthors(List<String> authors) {
            if (authors.isEmpty())
                this.authors = Collections.emptyList();
            else
                this.authors = new ArrayList<String>(authors);

            return this;
        }
    }

    private Book(Builder builder) {
        this.title = builder.title;
        this.year = builder.year;
        this.authors = builder.authors;
    }

    public String getTitle() {
        return title;
    }

    public Integer getYear() {
        return year;
    }

    public List<String> getAuthors() {
        return Collections.unmodifiableList(authors);
    }
}

To make a new object from an old one:

Book oldBook = new Book.Builder()//
        .withTitle("Hello")//
        .withYear(1900)//
        .withAuthors(Arrays.asList("Alice"))//
        .build();
Book newBook = new Book.Builder()//
        .from(oldBook)//
        .withTitle("World")//
        .withYear(1901)//
        .build();