问:
Draw a checkerboard in Java
I'm reading through a programming book and am having trouble understanding a few parts of this code. The program draws a checkerboard, and colors the odd squares black.

```<code>import acm.graphics.*;
import acm.program.*;

public class CheckerBoard extends GraphicsProgram   {

public void run()   {
    double squareSize = (double) getHeight() / numRows;
    for(int i = 0; i <= numRows; i++){
        for(int j = 0; j <= numColumns; j++)    {
            double x = j * squareSize;
            double y = i * squareSize;
            GRect square = new GRect(x,y,squareSize,squareSize);
            square.setFilled((i + j) % 2 != 0);
            add(square);
        }
    }
}

private static final int numRows = 8;
private static final int numColumns = 8;
</code>```

I understand most of the code, but I am still a little confused.

My first question is: How exactly does the program go through the for loops? They are nested, so would it create all of the columns (the j for loop) first? Or does it increment both i and j after the block of code finishes?

Secondly, why do I set x = j, and y = i? x is horizontal and j is vertical, shouldn't I set x = i and y = j? Both seem to yield the same results.

Mostly, I would just like to know how the for loop runs each time around. a basic run or two through the program.

Any help would be appreciated, thanks!

答:
The double for-loop is essentially the same as this code:

```<code>int i = 0;

while (i <= numRows) {
    int j = 0;

    while (j <= numColumns) {
        double x = j * squareSize;
        double y = i * squareSize;
        GRect square = new GRect(x,y,squareSize,squareSize);
        square.setFilled((i + j) % 2 != 0);
        add(square);

        j++;
    }

    i++;
}
</code>```

There is one small difference: at the end of the outer while-loop, i will have the value numRows + 1. If you use the for-loop the variable i will be out of scope.

Title: Draw a checkerboard in Java

Body:
The double for-loop is essentially the same as this code:

int i = 0;

while (i <= numRows) {
    int j = 0;

    while (j <= numColumns) {
        double x = j * squareSize;
        double y = i * squareSize;
        GRect square = new GRect(x,y,squareSize,squareSize);
        square.setFilled((i + j) % 2 != 0);
        add(square);

        j++;
    }

    i++;
}

There is one small difference: at the end of the outer while-loop, i will have the value numRows + 1. If you use the for-loop the variable i will be out of scope.


答:
Each time through the inner loop, a single board square is drawn (by adding it to the board). The following three lines of code draw the square:

```<code>GRect square = new GRect(x,y,squareSize,squareSize);
square.setFilled((i + j) % 2 != 0);
add(square);
</code>```

(x,y) in the first line specify the upper left coordinate of the square to be drawn.

The second line determines the square color. As the inner and outer loops iterate, the value of i+j alternates between even and odd.

The squares are added in column order. After one full cycle of the inner loop, a new row of eight squares will be added.

The outer loop iterates once for each row, cycling through the inner loop to add the row.

ContentLicense: CC BY-SA 3.0

Title: Draw a checkerboard in Java

Body:
I'm reading through a programming book and am having trouble understanding a few parts of this code. The program draws a checkerboard, and colors the odd squares black.

```<code>import acm.graphics.*;
import acm.program.*;

public class CheckerBoard extends GraphicsProgram   {

public void run()   {
    double squareSize = (double) getHeight() / numRows;
    for(int i = 0; i <= numRows; i++){
        for(int j = 0; j <= numColumns; j++)    {
            double x = j * squareSize;
            double y = i * squareSize;
            GRect square = new GRect(x,y,squareSize,squareSize);
            square.setFilled((i + j) % 2 != 0);
            add(square);
        }
    }
}

private static final int numRows = 8;
private static final int numColumns = 8;
</code>```

I understand most of the code, but I am still a little confused.

My first question is: How exactly does the program go through the for loops? They are nested, so would it create all of the columns (the j for loop) first? Or does it increment both i and j after the block of code finishes?

Secondly, why do I set x = j, and y = i? x is horizontal and j is vertical, shouldn't I set x = i and y = j? Both seem to yield the same results.

Mostly, I would just like to know how the for loop runs each time around. a basic run or two through the program.

Any help would be appreciated, thanks!

Body:
Each time through the inner loop, a single board square is drawn (by adding it to the board). The following three lines of code draw the square:

GRect square = new GRect(x,y,squareSize,squareSize);
square.setFilled((i + j) % 2 != 0);
add(square);

(x,y) in the first line specify the upper left coordinate of the square to be drawn.

The second line determines the square color. As the inner and outer loops iterate, the value of i+j alternates between even and odd.

The squares are added in column order. After one full cycle of the inner loop, a new row of eight squares will be added.

The outer loop iterates once for each row, cycling through the inner loop to add the row.


问:
Executables and Python
I've started learning my first language recently, Python, and I became interested in how it differed from the myriad of other programming languages.

I've been able to find most of it out with some searching:

There is interpreted, compiled and assembly language. Then there is numerical machine code (which as I understand is just binary?) that is read by hardware directly. So Python is an interpreted language because it isn't explicitly compiled to machine code (although from what I understand this is a false distinction since most code is both compiled and interpreted, if only behind the scenes).

I still have one question I couldn't figure out how to search an answer for. I assume Python code requires the Python platform to be read because it contains the interpreter. But how do you get those "standalone" .exe programs which you can run on most computers? Are those files just using a platform which every computer has by default, or are these files that are already compiled completely to machine code? (Like with C++?)

The main reason I'm wondering this is that I was wanting to send someone my simple Python programs without having them install the platform. I've searched online and found some 'compilers?' that will do this, but they don't seem to work very well and are very difficult to work with.

答:
MichaelT's comment is spot-on. Things like py2exe do the following:

bundle python runtime for a particular platform with your python code and all its dependencies

create a self-extracting executable that unpacks all of the above things and kicks off your script

You get a ready-to-run package for a single platform. You sacrifice portability.

Title: Executables and Python


答:
My first question is: How exactly does the program go through the for loops? They are nested, so would it create all of the columns (the j for loop) first? Or does it increment both i and j after the block of code finishes?

Neither, really. Nested loops like this do not increment at the same time: the inner loop will run until j violates the condition (j > numColumns), then the i loop (the outer loop) will increment and the whole inner loop will run again. Also, as @JayElston said, only one square is drawn at a time. What this means is that on each run through the inner loop the program draws one row of squares, one in each column. The outer loop repeatedly draws these rows to create the whole checkerboard. So the idea is that the inner loop does not draw whole columns, but rather the part of each column that is in the row currently being worked on.

Secondly, why do I set x = j, and y = i? x is horizontal and j is vertical, shouldn't I set x = i and y = j? Both seem to yield the same results.

As far as the x=j and y=i, what you've written isn't quite accurate. x is actually set to j times the width of a square, and y is set to i times the width of a square. So if we're on the fourth column, we are four squares horizontally from the starting point, and thus four times the width of a square in the x-direction from the edge. The fact that both yield the same results is a coincidence; it only happens because the checkerboard is square. Change numRows to 15 and run the program, then flip-flop them and run it again and you should see the difference. The first time, the number of rows will be 15 (or 16 if you've written the program with <= in the for loops), as expected from the variable name. But when x=i*squareSize, the number of columns will be 15. Note that x and y are positions at which to draw the squares, not the numbers of the rows and columns. That may make it make more sense.

Mostly, I would just like to know how the for loop runs each time around. a basic run or two through the program.

Something that might help would be to include the line System.out.println("i:"+i+"; j:"+j+"; x:"+x+"; x:"+y); in the inner loop right after GRect square.... (as I've demonstrated in my code below) In Java, System.out.println will show things on the console. Putting in that line will make the program spit out a line each time it draws a square, giving the values of i, j, x, and y.

Finally, here's an expanded version of the program with lots of comments. It also tells you about its progress, which hopefully will help you see what's happening. Note that I wouldn't normally use multiline comments (/*...*/) anywhere near this much.

```<code>import acm.graphics.GLabel;
import acm.graphics.GRect;
import acm.program.GraphicsProgram;

public class CheckerBoard extends GraphicsProgram {

  public void run() {
    double squareSize = (double) getHeight() / numRows;

    /*
     * Make a variable to carry the number of the square
     * that's being made. So, the first square will be
     * number 0, the second will be number 1, etc.
     */
    int num = 0;

    /*
     * Run the contents once for each number between 0 and
     * numRows Note the < and not <=. Because we're starting
     * from 0, we need to use <. For example, suppose we
     * wrote int i=0; i<=1; i++. We would get our loop run
     * once with i=0 and once with i=1 before i would not be
     * <= 1. Since our numbers in this case are supposed to
     * be the number of rows, we don't want to loop after we
     * do the one before our numRows or numColumns
     */
    for (int i = 0; i < numRows; i++) {
      /*
       * Run the contents of this loop once for each number
       * between 0 and numColumns, including 0, not
       * including numColumns.
       */
      for (int j = 0; j < numColumns; j++) {
        /*
         * Calculate the position for the next square. If
         * we're in column 4, then the next square should be
         * at 4*(the width of each square).
         */
        double x = j * squareSize;
        double y = i * squareSize;

        /*
         * Create a square that's to be put at our x and y
         * positions calculated just above. Make its width
         * squareSize and its height squareSize.
         */
        GRect square = new GRect(x, y, squareSize, squareSize);

        /*
         * Make some text that will be put down. Use the
         * current value of num for its text
         * (Integer.toString just makes that integer into
         * text), and put it at the x-position we're working
         * with plus 1/4 of a squareSize and the y-position
         * we're working with plus 3/4 of a square. This
         * fakes centering the text in the squares.
         */
        GLabel label = new GLabel(Integer.toString(num), x + squareSize * .25,
            y + squareSize * .75);

        /*
         * Tell the user what our i, j, x, y, and num values
         * are.
         */
        System.out.println("i:" + i + "; j:" + j + "; X:" + x + "; Y:" + y
            + "; num: " + num);

        square.setFilled((i + j) % 2 != 0);
        add(square);

        /*
         * Stick that label on the page, just like with the
         * square.
         */
        add(label);

        /*
         * Increment the number variable (add one to it) so
         * the next square is num+1 (if this is square 0,
         * then the next one should be square 1)
         */
        num++;
      }
    }
  }

  // Change this to make the checkerboard non-square.
  private static final int numRows = 8;
  private static final int numColumns = 8;
}
</code>```

And here's what I get on my console when I run it:

```<code>i:0; j:0; X:0.0; Y:0.0; num: 0
i:0; j:1; X:25.0; Y:0.0; num: 1
i:0; j:2; X:50.0; Y:0.0; num: 2
i:0; j:3; X:75.0; Y:0.0; num: 3
i:0; j:4; X:100.0; Y:0.0; num: 4
i:0; j:5; X:125.0; Y:0.0; num: 5
i:0; j:6; X:150.0; Y:0.0; num: 6
i:0; j:7; X:175.0; Y:0.0; num: 7
i:1; j:0; X:0.0; Y:25.0; num: 8
i:1; j:1; X:25.0; Y:25.0; num: 9
i:1; j:2; X:50.0; Y:25.0; num: 10
i:1; j:3; X:75.0; Y:25.0; num: 11
i:1; j:4; X:100.0; Y:25.0; num: 12
i:1; j:5; X:125.0; Y:25.0; num: 13
i:1; j:6; X:150.0; Y:25.0; num: 14
i:1; j:7; X:175.0; Y:25.0; num: 15
i:2; j:0; X:0.0; Y:50.0; num: 16
i:2; j:1; X:25.0; Y:50.0; num: 17
i:2; j:2; X:50.0; Y:50.0; num: 18
i:2; j:3; X:75.0; Y:50.0; num: 19
i:2; j:4; X:100.0; Y:50.0; num: 20
i:2; j:5; X:125.0; Y:50.0; num: 21
i:2; j:6; X:150.0; Y:50.0; num: 22
i:2; j:7; X:175.0; Y:50.0; num: 23
i:3; j:0; X:0.0; Y:75.0; num: 24
i:3; j:1; X:25.0; Y:75.0; num: 25
i:3; j:2; X:50.0; Y:75.0; num: 26
i:3; j:3; X:75.0; Y:75.0; num: 27
i:3; j:4; X:100.0; Y:75.0; num: 28
i:3; j:5; X:125.0; Y:75.0; num: 29
i:3; j:6; X:150.0; Y:75.0; num: 30
i:3; j:7; X:175.0; Y:75.0; num: 31
i:4; j:0; X:0.0; Y:100.0; num: 32
i:4; j:1; X:25.0; Y:100.0; num: 33
i:4; j:2; X:50.0; Y:100.0; num: 34
i:4; j:3; X:75.0; Y:100.0; num: 35
i:4; j:4; X:100.0; Y:100.0; num: 36
i:4; j:5; X:125.0; Y:100.0; num: 37
i:4; j:6; X:150.0; Y:100.0; num: 38
i:4; j:7; X:175.0; Y:100.0; num: 39
i:5; j:0; X:0.0; Y:125.0; num: 40
i:5; j:1; X:25.0; Y:125.0; num: 41
i:5; j:2; X:50.0; Y:125.0; num: 42
i:5; j:3; X:75.0; Y:125.0; num: 43
i:5; j:4; X:100.0; Y:125.0; num: 44
i:5; j:5; X:125.0; Y:125.0; num: 45
i:5; j:6; X:150.0; Y:125.0; num: 46
i:5; j:7; X:175.0; Y:125.0; num: 47
i:6; j:0; X:0.0; Y:150.0; num: 48
i:6; j:1; X:25.0; Y:150.0; num: 49
i:6; j:2; X:50.0; Y:150.0; num: 50
i:6; j:3; X:75.0; Y:150.0; num: 51
i:6; j:4; X:100.0; Y:150.0; num: 52
i:6; j:5; X:125.0; Y:150.0; num: 53
i:6; j:6; X:150.0; Y:150.0; num: 54
i:6; j:7; X:175.0; Y:150.0; num: 55
i:7; j:0; X:0.0; Y:175.0; num: 56
i:7; j:1; X:25.0; Y:175.0; num: 57
i:7; j:2; X:50.0; Y:175.0; num: 58
i:7; j:3; X:75.0; Y:175.0; num: 59
i:7; j:4; X:100.0; Y:175.0; num: 60
i:7; j:5; X:125.0; Y:175.0; num: 61
i:7; j:6; X:150.0; Y:175.0; num: 62
i:7; j:7; X:175.0; Y:175.0; num: 63
</code>```

Title: Draw a checkerboard in Java

Body:
My first question is: How exactly does the program go through the for loops? They are nested, so would it create all of the columns (the j for loop) first? Or does it increment both i and j after the block of code finishes?

Neither, really. Nested loops like this do not increment at the same time: the inner loop will run until j violates the condition (j > numColumns), then the i loop (the outer loop) will increment and the whole inner loop will run again. Also, as @JayElston said, only one square is drawn at a time. What this means is that on each run through the inner loop the program draws one row of squares, one in each column. The outer loop repeatedly draws these rows to create the whole checkerboard. So the idea is that the inner loop does not draw whole columns, but rather the part of each column that is in the row currently being worked on.

Secondly, why do I set x = j, and y = i? x is horizontal and j is vertical, shouldn't I set x = i and y = j? Both seem to yield the same results.

As far as the x=j and y=i, what you've written isn't quite accurate. x is actually set to j times the width of a square, and y is set to i times the width of a square. So if we're on the fourth column, we are four squares horizontally from the starting point, and thus four times the width of a square in the x-direction from the edge. The fact that both yield the same results is a coincidence; it only happens because the checkerboard is square. Change numRows to 15 and run the program, then flip-flop them and run it again and you should see the difference. The first time, the number of rows will be 15 (or 16 if you've written the program with <= in the for loops), as expected from the variable name. But when x=i*squareSize, the number of columns will be 15. Note that x and y are positions at which to draw the squares, not the numbers of the rows and columns. That may make it make more sense.

Mostly, I would just like to know how the for loop runs each time around. a basic run or two through the program.

Something that might help would be to include the line System.out.println("i:"+i+"; j:"+j+"; x:"+x+"; x:"+y); in the inner loop right after GRect square.... (as I've demonstrated in my code below) In Java, System.out.println will show things on the console. Putting in that line will make the program spit out a line each time it draws a square, giving the values of i, j, x, and y.

Finally, here's an expanded version of the program with lots of comments. It also tells you about its progress, which hopefully will help you see what's happening. Note that I wouldn't normally use multiline comments (/*...*/) anywhere near this much.

import acm.graphics.GLabel;
import acm.graphics.GRect;
import acm.program.GraphicsProgram;

public class CheckerBoard extends GraphicsProgram {

  public void run() {
    double squareSize = (double) getHeight() / numRows;

    /*
     * Make a variable to carry the number of the square
     * that's being made. So, the first square will be
     * number 0, the second will be number 1, etc.
     */
    int num = 0;

    /*
     * Run the contents once for each number between 0 and
     * numRows Note the < and not <=. Because we're starting
     * from 0, we need to use <. For example, suppose we
     * wrote int i=0; i<=1; i++. We would get our loop run
     * once with i=0 and once with i=1 before i would not be
     * <= 1. Since our numbers in this case are supposed to
     * be the number of rows, we don't want to loop after we
     * do the one before our numRows or numColumns
     */
    for (int i = 0; i < numRows; i++) {
      /*
       * Run the contents of this loop once for each number
       * between 0 and numColumns, including 0, not
       * including numColumns.
       */
      for (int j = 0; j < numColumns; j++) {
        /*
         * Calculate the position for the next square. If
         * we're in column 4, then the next square should be
         * at 4*(the width of each square).
         */
        double x = j * squareSize;
        double y = i * squareSize;

        /*
         * Create a square that's to be put at our x and y
         * positions calculated just above. Make its width
         * squareSize and its height squareSize.
         */
        GRect square = new GRect(x, y, squareSize, squareSize);

        /*
         * Make some text that will be put down. Use the
         * current value of num for its text
         * (Integer.toString just makes that integer into
         * text), and put it at the x-position we're working
         * with plus 1/4 of a squareSize and the y-position
         * we're working with plus 3/4 of a square. This
         * fakes centering the text in the squares.
         */
        GLabel label = new GLabel(Integer.toString(num), x + squareSize * .25,
            y + squareSize * .75);

        /*
         * Tell the user what our i, j, x, y, and num values
         * are.
         */
        System.out.println("i:" + i + "; j:" + j + "; X:" + x + "; Y:" + y
            + "; num: " + num);

        square.setFilled((i + j) % 2 != 0);
        add(square);

        /*
         * Stick that label on the page, just like with the
         * square.
         */
        add(label);

        /*
         * Increment the number variable (add one to it) so
         * the next square is num+1 (if this is square 0,
         * then the next one should be square 1)
         */
        num++;
      }
    }
  }

  // Change this to make the checkerboard non-square.
  private static final int numRows = 8;
  private static final int numColumns = 8;
}

And here's what I get on my console when I run it:

i:0; j:0; X:0.0; Y:0.0; num: 0
i:0; j:1; X:25.0; Y:0.0; num: 1
i:0; j:2; X:50.0; Y:0.0; num: 2
i:0; j:3; X:75.0; Y:0.0; num: 3
i:0; j:4; X:100.0; Y:0.0; num: 4
i:0; j:5; X:125.0; Y:0.0; num: 5
i:0; j:6; X:150.0; Y:0.0; num: 6
i:0; j:7; X:175.0; Y:0.0; num: 7
i:1; j:0; X:0.0; Y:25.0; num: 8
i:1; j:1; X:25.0; Y:25.0; num: 9
i:1; j:2; X:50.0; Y:25.0; num: 10
i:1; j:3; X:75.0; Y:25.0; num: 11
i:1; j:4; X:100.0; Y:25.0; num: 12
i:1; j:5; X:125.0; Y:25.0; num: 13
i:1; j:6; X:150.0; Y:25.0; num: 14
i:1; j:7; X:175.0; Y:25.0; num: 15
i:2; j:0; X:0.0; Y:50.0; num: 16
i:2; j:1; X:25.0; Y:50.0; num: 17
i:2; j:2; X:50.0; Y:50.0; num: 18
i:2; j:3; X:75.0; Y:50.0; num: 19
i:2; j:4; X:100.0; Y:50.0; num: 20
i:2; j:5; X:125.0; Y:50.0; num: 21
i:2; j:6; X:150.0; Y:50.0; num: 22
i:2; j:7; X:175.0; Y:50.0; num: 23
i:3; j:0; X:0.0; Y:75.0; num: 24
i:3; j:1; X:25.0; Y:75.0; num: 25
i:3; j:2; X:50.0; Y:75.0; num: 26
i:3; j:3; X:75.0; Y:75.0; num: 27
i:3; j:4; X:100.0; Y:75.0; num: 28
i:3; j:5; X:125.0; Y:75.0; num: 29
i:3; j:6; X:150.0; Y:75.0; num: 30
i:3; j:7; X:175.0; Y:75.0; num: 31
i:4; j:0; X:0.0; Y:100.0; num: 32
i:4; j:1; X:25.0; Y:100.0; num: 33
i:4; j:2; X:50.0; Y:100.0; num: 34
i:4; j:3; X:75.0; Y:100.0; num: 35
i:4; j:4; X:100.0; Y:100.0; num: 36
i:4; j:5; X:125.0; Y:100.0; num: 37
i:4; j:6; X:150.0; Y:100.0; num: 38
i:4; j:7; X:175.0; Y:100.0; num: 39
i:5; j:0; X:0.0; Y:125.0; num: 40
i:5; j:1; X:25.0; Y:125.0; num: 41
i:5; j:2; X:50.0; Y:125.0; num: 42
i:5; j:3; X:75.0; Y:125.0; num: 43
i:5; j:4; X:100.0; Y:125.0; num: 44
i:5; j:5; X:125.0; Y:125.0; num: 45
i:5; j:6; X:150.0; Y:125.0; num: 46
i:5; j:7; X:175.0; Y:125.0; num: 47
i:6; j:0; X:0.0; Y:150.0; num: 48
i:6; j:1; X:25.0; Y:150.0; num: 49
i:6; j:2; X:50.0; Y:150.0; num: 50
i:6; j:3; X:75.0; Y:150.0; num: 51
i:6; j:4; X:100.0; Y:150.0; num: 52
i:6; j:5; X:125.0; Y:150.0; num: 53
i:6; j:6; X:150.0; Y:150.0; num: 54
i:6; j:7; X:175.0; Y:150.0; num: 55
i:7; j:0; X:0.0; Y:175.0; num: 56
i:7; j:1; X:25.0; Y:175.0; num: 57
i:7; j:2; X:50.0; Y:175.0; num: 58
i:7; j:3; X:75.0; Y:175.0; num: 59
i:7; j:4; X:100.0; Y:175.0; num: 60
i:7; j:5; X:125.0; Y:175.0; num: 61
i:7; j:6; X:150.0; Y:175.0; num: 62
i:7; j:7; X:175.0; Y:175.0; num: 63


问:
Can I fork Linux source code, change it around to suit my desires, and claim it as my own kernel without doing any of the originating work?
Is it acceptable form to take Linux kernel source from any version, change it, claim it is mine, and then distribute it for monetary gain? In such a case open-source software is entitled to a sort of "grab, change, sell" mechanism in which anyone can just tinker with something to look different from the original source, make it work their way, and sell it as if they made it entirely themselves. Isn't that illegal?</p>

答:
The Linux kernel is licensed under the Free Software Foundation's GPL (General Public License) version 2. It is a copyleft license; basically, this means you are free to make copies of the original or modified kernel and sell them at any price, but the license requires you to give the same rights to the recipients: They may copy your modified version and pass it on, without paying you.

You are also required to give them the source code of your modifications upon request, not just a binary. Under the GPL, you must also retain the copyright notices by the original authors, which prevents you from claiming you wrote everything yourself.

There are permissive licenses as well. Most of them have some form of attribution requirement; but apart from that, you are free to make proprietary forks of software under permissive licenses.

OwnerDisplayName: fork man

OwnerDisplayName: chirlu


答:
I advice you first read this Wikipedia article about free software licenses. It should give you a good overview about how free licenses work. The Linux kernel is licenses under GPLv2.

Another good page about this, is the licenses page at opensource.org. There is an FAQ, which pretty much should sort your questions, as it is written in almost the same kind of nomenclature.

Title: Can I fork Linux source code, change it around to suit my desires, and claim it as my own kernel without doing any of the originating work?

Body: Is it acceptable form to take Linux kernel source from any version, change it, claim it is mine, and then distribute it for monetary gain? In such a case open-source software is entitled to a sort of "grab, change, sell" mechanism in which anyone can just tinker with something to look different from the original source, make it work their way, and sell it as if they made it entirely themselves. Isn't that illegal?</p>

OwnerDisplayName: polemon


答:
The interpreters themselves are compiled and dependent on the platform they run on due to different OS and architecture concerns (for example different C libraries and file handling). So there is no way to get around the platform dependency entirely in the installation.  However as you say there are ways to package it into a package so that it will be easier for distributing to the user who need not install the interpreter and other dependencies.

PyInstaller seems to be able to do what you want with not too much fuss and can build packages for the most common platforms and is easy to run.  The main thing I found with Windows is that you need to also install PyWin32 (making sure to get the correct bitness depending on the version of Python you have installed).

Title: Executables and Python

Body:
I've started learning my first language recently, Python, and I became interested in how it differed from the myriad of other programming languages.

I've been able to find most of it out with some searching:

There is interpreted, compiled and assembly language. Then there is numerical machine code (which as I understand is just binary?) that is read by hardware directly. So Python is an interpreted language because it isn't explicitly compiled to machine code (although from what I understand this is a false distinction since most code is both compiled and interpreted, if only behind the scenes).

I still have one question I couldn't figure out how to search an answer for. I assume Python code requires the Python platform to be read because it contains the interpreter. But how do you get those "standalone" .exe programs which you can run on most computers? Are those files just using a platform which every computer has by default, or are these files that are already compiled completely to machine code? (Like with C++?)

The main reason I'm wondering this is that I was wanting to send someone my simple Python programs without having them install the platform. I've searched online and found some 'compilers?' that will do this, but they don't seem to work very well and are very difficult to work with.


问:
When writing an interpreter, how should the type inference algorithm change the parsed AST? Should it?
When writing an interpreter, how should the type inference algorithm change the parsed AST? Should it? Or parsing and inference are done necessarily simultaneously?

I have implemented a strongly typed functional language interpreter, in which each function can be declared only one time (i.e., with no signature variants).
As soon as the non-typed implementation parser was concluded and working, I have written the type inference algorithm, feeded by the parser's resulting AST.

Hindley-Damas-Milner is working like a charm, but the program use it and if the type checking passes, it just forgets about the matter and pass the AST to the interpreter. To the moment, the "target language" (i.e., the one in which the interpreter is written) have satisfied the interpreter type needs, but I am wondering if this approach is usual: to discard all the type inference fruits after an "ok" result.

Also, would writing a compiler instead of an interpreter make any difference is this sense?

答:
No, it is definitely not the usual to throw away good analysis results. For a stark difference you may want to check out the Scala compiler. It is based on execution phases and you can add plugins which will be executed after certain phases. It is particularly interesting to place your plugin after the typing phase, because that gives you all of the inferred types in a very handy way.

The AST, however, is not so much changed as it is annotated. The basic structure of your statements, expressions, function definitions, etc. that are held in your AST do remain unchanged of course. What you really do during type inference is to annotate the tree nodes with their respective types.

For example, before typing inference ran you would have an AST with a function node for the function f, that is located somewhere within the AST and has some child nodes, which resemble arguments and statements/expressions. During type inference you determine the types of these child nodes, i.e. of the statements/expressions, and from them you determine the type of the function f. Now you could be satisfied detecting, that f is returning an int and it is only ever used in places, where int is used, but there is no reason to lose this information.

As for interpreter vs compiler, there are huge benefits from having types annotated to your AST, which go far beyond that. Consider for example IDEs.. plugin authors are very thankful for having a type-annotated AST available. It is so much more efficient to simply know that f returns an int, when you want to implement code completion, instead of having to run type inference yet again.

You may want to extend your language at one point. If the extension is anywhere past the type inference, you typically need to rely on its results. For example, consider adding type-safe macros, or some kind of semantic checks.

In summary: Type information in a strongly typed lanugage is so important, that it resembles blasphemy if you perform type inference only to throw away its results. You rob yourself and others of information that is both, extremely powerful when available, and rather costly to generate.

ContentLicense: CC BY-SA 4.0


问:
Is this an open source license?
I have been messing with code in The Unix Archive and have found that most of the code references a (non existent) license, however, this is in the root of the mirrors and apparently covers all of the code (typed from a PDF, so excuse the typos): (source pdf is here

The following copyright notice applies to the source code files for which the license is granted.

Copyright(c) Caldera International Inc. 2001-20012. All rights
reserved Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

Redistributions of source code and documentation
must retain the above copyright notice, this list of conditions, and
the following disclaimer.

Redistributions in binary form must
reproduce the above copyright notice, this list of conditions and the
following disclaimer in teh docuemtnation and/or other materials
provided iwth the distribution.

All advertising materials mentioning
features or use of this software must display the following
acknowledgement: This product includes software developed or owned by
Caldera International, inc.

Neither the name of Caldera International,
Inc. nor the names of other contributors may be used to endorse or
promote products derived form this software without specific prior
written permission.

USE OF THE SOFTWARE PROVIDED FOR UNDER THIS
LICENSE BY CALDERA INTERNATIONAL, INC. AND CONTRIBUTORS ''AS IN'' AND
NAY EXPRESS OR IMPLIED WARANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALDERA INTERNATIONAL, INC.
BE LIABLE OFR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLRARAY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Is this an open source license? It kind of seems to be very BSD-ish, with the exclusion of the clause "all advertising materials mentioning features or use of this software must display the following acknowledgement: this product includes software developed or owned by Caldera International, Inc"

Does that clause prevent this from being an open source license?

答:
In essence this is the BSD license, and is indeed an open source license.

The advertising materials bit is really just a restatement of the clause preceding it.

Title: Is this an open source license?


答:
It seems to be the original, 4-clause BSD License.

Yes, it is free software (it's DSFG compatible and FSF-approved, but not OSI approved).

It is, however, slightly problematic, because that advertising clause can lead to lots and lots of small print on any advertisement (and keeping track of all those requirements is a pain).

Also, contrary to the other BSD license variations, the FSF considers this license to be incompatible with the GPL!

Title: Is this an open source license?

Body:
I have been messing with code in The Unix Archive and have found that most of the code references a (non existent) license, however, this is in the root of the mirrors and apparently covers all of the code (typed from a PDF, so excuse the typos): (source pdf is here

The following copyright notice applies to the source code files for which the license is granted.

Copyright(c) Caldera International Inc. 2001-20012. All rights
reserved Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

Redistributions of source code and documentation
must retain the above copyright notice, this list of conditions, and
the following disclaimer.

Redistributions in binary form must
reproduce the above copyright notice, this list of conditions and the
following disclaimer in teh docuemtnation and/or other materials
provided iwth the distribution.

All advertising materials mentioning
features or use of this software must display the following
acknowledgement: This product includes software developed or owned by
Caldera International, inc.

Neither the name of Caldera International,
Inc. nor the names of other contributors may be used to endorse or
promote products derived form this software without specific prior
written permission.

USE OF THE SOFTWARE PROVIDED FOR UNDER THIS
LICENSE BY CALDERA INTERNATIONAL, INC. AND CONTRIBUTORS ''AS IN'' AND
NAY EXPRESS OR IMPLIED WARANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALDERA INTERNATIONAL, INC.
BE LIABLE OFR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLRARAY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Is this an open source license? It kind of seems to be very BSD-ish, with the exclusion of the clause "all advertising materials mentioning features or use of this software must display the following acknowledgement: this product includes software developed or owned by Caldera International, Inc"

Does that clause prevent this from being an open source license?


问:
Will real world applications ever need a 128-bit flat address space?
This is a bit "one megabyte should be enough for anyone", but...

A 64-bit flat address space allows up to 4.3ish billion times more space than a 32-bit address space. That's 17,179,869,184 GiB.

Obviously, the transition from 8 bits to 16 bits was pretty quick (I'm viewing things in a teen-during-the-80s way, ignoring all those mainframes and minis because they couldn't run a port of Elite). The transition from 16 bits to 32 bits took a bit longer, and 32 bits actually lasted quite a while.

Now we have 64 bits, would it be stupid to say "17,179,869,184 GiB should be enough for anyone"?

This is a programmers question because I really have the programming viewpoint in mind. Even if a computer some day has a seemingly infinite amount of working memory, that doesn't mean that applications will need to see a seemingly infinite flat address space.

Basically, can we programmers breath a sigh of relief and say "well, whatever integers or floats may do, at least I don't have to worry about my pointers growing any more?".

答: yes apps dont fill up every byte of virtual space. address space layout randomization would get the biggest benefit. </p>


问:
How can CoffeeScript be written in CoffeeScript?
How is it possible that written a programming language like CoffeeScript in  itself like CoffeeScript? Firstly CoffeeScript doesn't exist that read CoffeeScript scripts and interpret them?</p>

答:
Think of a subset of language to build another language. Don't watch it as building A with A but instead building A with B where B is a small language.

Think of it in this way:
You build a simple interpreter with JavaScript and name it CoffeeScript, later on as your project goes bigger and bigger you start writing parts of your code with your new functions/construcs or in short - your own language like CoffeeScript.


问:
How can I quickly weed out "copy & paste" coders?
I need a way to filter out resumes of folks who just copy-and-paste code then hope it works, and check it in if it does.  All this happens without having an understanding (or care) to understand the rest of the code in the system.

Sure I know that copying and pasting code is part of learning a new object, control, etc... but how can one tell if that accounts for 70% (or more) of their development career?

I've come across some senior level guys perhaps whose skills are so outdated or irrelevant for the project, that all they do is google, copy-then-paste some code without thinking about the solution as a whole.  As a result we have a mismash of JSON, AJAX, callbacks, ASMX, WCF and postbacks in the same project.  It is clear there is no consistency or logic behind where each technology is being used.

In the worst case, this type of developer creates security issues and vectors for attack.

Question

How would you recommend I filter out people who have a poor programming background?  Can I do it at the resume level?  If not, how do I do this during the interview.

答:
I ask three interview questions

Write a linked list capable of storing some numeric type in java without importing anything from the collections framework

Write code showing how you can add/remove nodes from that list

Write code showing how you can get the max/min from that list

I've seen people complete this in 5 minutes and seen people struggle for 30 minutes before giving up.

ContentLicense: CC BY-SA 2.5


问:
How to overcome programming by coincidence?
In the book The Pragmatic Programmer, the writers mention the "programming by coincidence" concept. It explains what it is, why it is caused, what are the dangers you may encounter and it compares with a landmine field in a war.

Do you ever watch old black-and-white war movies? The weary soldier advances cautiously out of the brush. There's a clearing ahead: are there any land mines, or is it safe to cross? There aren't any indications that it's a minefield—no signs, barbed wire, or craters. The soldier pokes the ground ahead of him with his bayonet and winces, expecting an explosion. There isn't one. So he proceeds painstakingly through the field for a while, prodding and poking as he goes. Eventually, convinced that the field is safe, he straightens up and marches proudly forward, only to be blown to pieces.

The soldier's initial probes for mines revealed nothing, but this was merely lucky. He was led to a false conclusion—with disastrous results.

As developers, we also work in minefields. There are hundreds of traps just waiting to catch us each day. Remembering the soldier's tale, we should be wary of drawing false conclusions. We should avoid programming by coincidence—relying on luck and accidental successes—in favor of programming deliberately.

But I am not really satisfied on the way they describe the "how to overcome it" issue. Yeah, you have to think ahead before writing the code, but how to practice that? The only thing I can think is by adding features to existing Open source projects, where you must have knowledge on both the "what I am doing now" and the "How the other pieces of code are working", and it is not that applicable when you are writing your own projects.

答:
You don't have to think ahead, merely be very clear on what was done, and be very clear on what you are doing right now.

Subroutines should say what they do, do what they say, and not have hidden dependencies.  Then someone calling them can more easily reason about what they will do.

Avoid global state.  (Variables, singletons, etc.)  The more state that you have to have in your head to understand what things do, the harder it is to understand what is supposed to happen and find the edge cases.

Write unit tests.  Unit tests are great for capturing the actual behavior of code that you just wrote, rather than the ideal behavior that you are hoping to find.

Shorten your edit/compile/test cycle.  When you add a large chunk of code and test poorly, then the odds are that it will behave differently than you think.  Then you "fix" it with some random change, and you got the right answer for the moment, but have no idea how it actually happened.  You're now programming by coincidence.  But when you add 5 lines and then test, the odds that you got the right answer because it works like you think it works are much better.  I can say from experience that 5 chunks of 10 lines each, individually tested, is a very different beast than 50 lines of code tested all at once.

Refactor ruthlessly.  Many times I've spotted a refactor that will make my code somewhat simpler but take a bunch of work that I didn't want to do.  After I began deliberately tackling those refactors as a priority, I have found that it usually pays off for itself inside of a month.  But note the key, the refactors that I focus on are ones that make day to day life simpler, and not ones that meet some arbitrary aesthetic of better or more general.  Those refactors I've learned to be much more cautious with.

None of these things require advance planning.  But they all make it easier to understand your existing code, and therefore make it easy to implement your next little chunk in a deliberate way.


答:
The most scary comment I ever encountered in a program was

Do not touch this. It works. We don't know how or why, but it works.1

and it is scary just because it acknowledges that the piece of code was the result of programming by coincidence.

To avoid programming by coincidence, you should be able to explain (to a coworker, yourself or a rubber duck) exactly what the code does and why it works. The bullets for programming deliberately are mostly aid in moving towards that goal of being able to explain the code.

1For context, this comment appeared in the code that handles context switches in a primitive OS. The code had already been in production for several years when I encountered it.

Title: How to overcome programming by coincidence?

Body:
In the book The Pragmatic Programmer, the writers mention the "programming by coincidence" concept. It explains what it is, why it is caused, what are the dangers you may encounter and it compares with a landmine field in a war.

Do you ever watch old black-and-white war movies? The weary soldier advances cautiously out of the brush. There's a clearing ahead: are there any land mines, or is it safe to cross? There aren't any indications that it's a minefield—no signs, barbed wire, or craters. The soldier pokes the ground ahead of him with his bayonet and winces, expecting an explosion. There isn't one. So he proceeds painstakingly through the field for a while, prodding and poking as he goes. Eventually, convinced that the field is safe, he straightens up and marches proudly forward, only to be blown to pieces.

The soldier's initial probes for mines revealed nothing, but this was merely lucky. He was led to a false conclusion—with disastrous results.

As developers, we also work in minefields. There are hundreds of traps just waiting to catch us each day. Remembering the soldier's tale, we should be wary of drawing false conclusions. We should avoid programming by coincidence—relying on luck and accidental successes—in favor of programming deliberately.

But I am not really satisfied on the way they describe the "how to overcome it" issue. Yeah, you have to think ahead before writing the code, but how to practice that? The only thing I can think is by adding features to existing Open source projects, where you must have knowledge on both the "what I am doing now" and the "How the other pieces of code are working", and it is not that applicable when you are writing your own projects.


问:
Namespaces, why are they necessary for prefixes?
So I've been reading about namespace on w3schools and I understand they are to uniquely identify an element. But what is the point of having namespaces if you have to have prefixes along side them. Are you always required to have prefixes with namespaces? If not are you always required to have namespaces with prefixes? If so why?

For example:

```<code><root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="http://www.w3schools.com/furniture">

 <h:table>
   <h:tr>
   <h:td>Apples</h:td>
   <h:td>Bananas</h:td>
 </h:tr>
</code>```

```<code><f:name>African Coffee Table</f:name>
    <f:width>80</f:width>
    <f:length>120</f:length>
  </f:table>
</root>
</code>```

Doesn't f and h uniquely identify the different element types?

Thanks for your help. I'm really at a loss at understanding why namespaces exists.

答:
In your example, h is a shortcut for the fully qualified namespace http://www.w3.org/TR/html4. Now, imagine your document is processed by an XSLT stylesheet that you didn't write. In this stylesheet, the same http://www.w3.org/TR/html4 namespace is associated with anoter prefix, html.
Without the namespace declaration, you wouldn't know that html and h refer to the same namespace.


答:
An XML namespace is supposed to have a reasonable chance of being universally unique. A prefix, especially a single-letter one, is almost certain not to be. A namespace declaration creates a mapping from an otherwise meaningless prefix to a stable identifier that software can rely on to identify the schemas of XML elements.

You're right: within a single document, an author can make sure that different prefixes are used for different groups of elements. But without tying those prefixes to unique namespaces, how do you accomplish any of the following:

Sending that XML file to an organisation that uses different prefixes for the same groups of elements, and expecting it to be interpreted correctly by (hypothetical) software that only uses prefixes?

Any automated processing of XML documents at all? Even something as fundamental as schema validation: how does your HTML parser know to associate the prefix h with the collection of HTML elements, and therefore knows how to render h:table?

There is no central database of prefixes where h is forever and all time associated with HTML elements - that's the purpose of the namespace declaration mapping the prefix to the namespace within the scope of the document.

Update - clarification of terminology

Namespace URI, also just called namespace: A stable name uniquely identifying a collection of XML elements and attributes.

This is just an identifier, chosen to be unique.

Although it is often a URL, whatever document might be available at this URL is irrelevant and is not consulted during XML processing. Browsing to the URL does not have to produce any valid content, although sometimes the company which produced the XML schema, and chose its namespace URI to have a domain which they control, chooses to publish some information about the schema at that address.

Note that this means you cannot expect to download a schema given a namespace URI. You will need to get hold of schemas using some other mechanism, probably documented by whoever produced the schema.

Prefix: a document-local representation of a namespace URI within an XML document. Any arbitrary prefix can be mapped to a namespace using xmlns. If you really wanted to, you could have both xmlns:f="http://www.w3schools.com/furniture" and xmlns:argos="http://www.w3schools.com/furniture", and then use the prefixes interchangeably: <f:table> or <argos:table>. The parser doesn't care whether the prefix is f or argos - it only cares that both of these table elements belong to the namespace http://www.w3schools.com/furniture. Further, the URL http://www.w3schools.com/furniture does not have to be a valid document. When used as an XML namespace URI, its only function is to be a unique identifier. If the parser had available a schema whose targetNamespace was http://www.w3schools.com/furniture, it could validate the table elements and their contents using that schema.

Title: Namespaces, why are they necessary for prefixes?

Body:
So I've been reading about namespace on w3schools and I understand they are to uniquely identify an element. But what is the point of having namespaces if you have to have prefixes along side them. Are you always required to have prefixes with namespaces? If not are you always required to have namespaces with prefixes? If so why?

For example:

```<code><root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="http://www.w3schools.com/furniture">

 <h:table>
   <h:tr>
   <h:td>Apples</h:td>
   <h:td>Bananas</h:td>
 </h:tr>
</code>```

```<code><f:name>African Coffee Table</f:name>
    <f:width>80</f:width>
    <f:length>120</f:length>
  </f:table>
</root>
</code>```

Doesn't f and h uniquely identify the different element types?

Thanks for your help. I'm really at a loss at understanding why namespaces exists.


答:
The point of namespaces in XML is not just to make it clear for the human reader that <h:table> and <f:table> are different things, but also to tell a (validating) XML parser how they should be parsed (for example, which attributes and sub-elements are valid).

The prefixes are only needed if there can be confusion about which namespace the element comes from. For example, this is also valid, because all elements come from the same namespace:

```<code><root xmlns="http://www.w3schools.com/furniture">
  <table>
    <name>African Coffee Table</name>
    <width>80</width>
    <length>120</length>
  </table>
</root>
</code>```

The prefixes are mostly a shorthand to indicate a particular namespace, but they don't have any meaning of their own. It is the namespace URI that tells the XML parser how to interpret the XML elements that are part of the namespace.

Body:
The point of namespaces in XML is not just to make it clear for the human reader that <h:table> and <f:table> are different things, but also to tell a (validating) XML parser how they should be parsed (for example, which attributes and sub-elements are valid).

The prefixes are only needed if there can be confusion about which namespace the element comes from. For example, this is also valid, because all elements come from the same namespace:

<root xmlns="http://www.w3schools.com/furniture">
  <table>
    <name>African Coffee Table</name>
    <width>80</width>
    <length>120</length>
  </table>
</root>

The prefixes are mostly a shorthand to indicate a particular namespace, but they don't have any meaning of their own. It is the namespace URI that tells the XML parser how to interpret the XML elements that are part of the namespace.


答:
First you design a language A on paper and white board.

Then you write an implementation of a language A (compiler, vm, interpreter, runtime depending on a scope of language) in language B.

Once you have stable environment for language A, you can start writing version of environment for language A in language A.

I would say, that unless language is slow or not turing complete, it's tools should always be implemented in it. That makes it's much easier for developers to work with it.

Title: How can CoffeeScript be written in CoffeeScript?

Body: How is it possible that written a programming language like CoffeeScript in  itself like CoffeeScript? Firstly CoffeeScript doesn't exist that read CoffeeScript scripts and interpret them?</p>


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
Software Licensing Basics

The difference between a "viral" copyleft license (GPL) when compared to closed-source-friendly Apache, and non-viral MS-PL/MS-RL.

When you should use LGPL, and when not to.

License compatibility.  For example, you may link a modern Apache license'd library to a GPLv3 code, but not GPL 1 or 2.

If you own the source code in it's entirety, you may publish it under as many (or few) licenses as you wish.

Note to S.O. community:

Please feel free to edit this answer as you see fit... mainly for information not suited for the comments section below.


问:
How to detect achievements in gaming?
I mistakenly posted this to stackoverflow and now posting here based on a suggestion in on that site ...

This is a very high level conceptual question. Say in a software application I have 4 different actions, for example: Upload, Share, Comment, and like

And I want to give achievement badges to users like:

Rookie - Upload your first 5 files

Upload Junkie - Upload 20 files in 1 day

Night Crawler - Upload a file after midnight

Share-a-holic - Share 10 different files

Likes-everything - Like 20 different files

you get the idea. What is he best way to check and see if a user has achieved a particular achievement without having to compile the logic for achievement into my code? And .. - Retain the ability to Add new achievements post compile (xml or db) - Achievements must track specific actions, number of times, and additional criteria (like time of day) - Detection should be near real-time so the user notified almost instantly when an achievement is completed

My biggest questions is, how do I detect these achievements being achieved? Do I:

1) Check after every action to see if ... (Most real time) 2) Have another program check the DB at all times against a set of rules? (Easiest)

Is there another paradigm that I'm missing? I feel there definitely is because in many games (like jetpack for iOS for example), I'm notified of the achievement I have unlocked in the instant in which I unlock it which I found pretty impressive.

Thank you

答:
A neat way to handle this might be a specification pattern. You'd have an achievement manager, which would periodically query your users for those that match any of a set of specifications. Your achievement class would therefore include a name, logo, point score etc as normal, and also a specification describing a user who has gained that achievement. For example, in C#, the "Share-a-holic" achievement might look like this:

```<code>AchievementType ShareAHolic = new AchievementType
{
    Name = "Share-a-holic",
    Description = "Shared 10 files",
    Score = 25,
    Specification = (user => user.SharedFiles.Distinct().Count() > 10)
};

AchievementManager.AddAchievementType(ShareAHolic);
</code>```

and then at the appropriate point, your achievement manager can do something like this:

```<code>foreach (AchievementType achievement in AchievementTypes)
{
    var users = DB.Users.Where(achievement.Specification && !(user.Achievements.Contains(achievement)));
    foreach (User u in shareaholics)
    {
        AchievementManager.Award(u, achievement);
    }
}
</code>```

Your achievement manager's .Award() method can also be called directly at the appropriate point if an achievement can be detected immediately. You might also want to add a method to run these checks on a specific user, so that you can trigger a check after important events to allow users to get achievements immediately.

Title: How to detect achievements in gaming?

Body:
A neat way to handle this might be a specification pattern. You'd have an achievement manager, which would periodically query your users for those that match any of a set of specifications. Your achievement class would therefore include a name, logo, point score etc as normal, and also a specification describing a user who has gained that achievement. For example, in C#, the "Share-a-holic" achievement might look like this:

AchievementType ShareAHolic = new AchievementType
{
    Name = "Share-a-holic",
    Description = "Shared 10 files",
    Score = 25,
    Specification = (user => user.SharedFiles.Distinct().Count() > 10)
};

AchievementManager.AddAchievementType(ShareAHolic);

and then at the appropriate point, your achievement manager can do something like this:

foreach (AchievementType achievement in AchievementTypes)
{
    var users = DB.Users.Where(achievement.Specification && !(user.Achievements.Contains(achievement)));
    foreach (User u in shareaholics)
    {
        AchievementManager.Award(u, achievement);
    }
}

Your achievement manager's .Award() method can also be called directly at the appropriate point if an achievement can be detected immediately. You might also want to add a method to run these checks on a specific user, so that you can trigger a check after important events to allow users to get achievements immediately.


答:
It is far too easy to code, test and fix "on the racing line". You have some functionality that given X & Y, produces Z. But what if X is corrupt and Y is unavailable? What if you're unable to output Z? Constantly have in mind what can go wrong and make a note of it for the test cycle.

Keep your routines short and descriptive - the best code requires few (if any) comments.

Meaningful method, class and variable names go a long way to aiding readability.

If you come across a code smell then STOP. That smell is unlikely to go away and a little effort now could save you a huge amount of grief later on.

Include testing within your development process. I'd advocate the use of BDD rather than TDD as it forces you to describe what you're aiming to achieve rather than blindly relying on a raft of tests which could give you a false sense of security.

Resist the urge to add extra cool features (unless it is your own pet project). Any extra code needs to be designed, written, tested and maintained. If it isn't required by the client/business - you risk this becoming a huge drain on your resources.


答: A for loop is perhaps the most commonly used form of iteration. This loop performs initialization before the first iteration. Then it performs conditional testing and, at the end of each iteration, some form of “stepping.”</p>

Title: Draw a checkerboard in Java


问:
How can NodeJS be "non-blocking"?
I'm learning NodeJS and just wanted to clarify something. In several introductory tutorials and books so far, very early on they've described Node's "non-blocking" architecture - or rather that it's possible (and recommended, the entire point) to code in a non-blocking manner.

So for example, this example was given in a book I'm reading of an asynchronous way to get data from a database.

```<code>http.createServer(function (req, res) {
  database.getInformation(function (data) {
      res.writeHead(200);
      res.end(data);
  });
});
</code>```

What happens (as I understand it) is Node makes the call to the database, then continues processing whatever may be next on the call stack. When the database request is complete, the data variable in the anonymous callback function will be populated and that function added to the call stack (and subsequently executed when Node gets to it).

My question is, what exactly is processing the database request? Surely Node has to block whilst it does that? What is taking care of the database request? Or if Node is waiting on an asynchronous HTTP GET request to an external resource, what is taking care of that request that allows Node to continue processing the call stack and be "non-blocking"?

答:
When Node.js is described as "non-blocking", that specifically means that its IO is non-blocking. Node uses libuv to handle its IO in a platform-agnostic way. On Windows, it uses IO completion ports, on Unix, it uses epoll/kqueue/select/etc. So, it makes a non-blocking IO request (which may have a background thread monitoring, but this is never exposed to JavaScript) and upon a result, it queues it within the event loop which calls the JavaScript callback on the main (read: only) JavaScript thread.

For databases, it depends on how the library is written. If it uses HTTP to communicate (as some NoSQL databases do), then it could be easily written in pure JavaScript using the standard node http library. If it does it another way, well, that's up to the library. It could be written in C/C++ and use background threads as long as that abstraction is never exposed to the JavaScript.

As for your question of what is "processing" the database request, ideally all that should be done is sending a simple message to a library (e.g. a SQL statement or some other query or a request to connect), and at that point your JavaScript keeps on chugging. When the library is ready to send a message back, it sends a message back to node's event queue which runs the callback, allowing that snippet of code to run.

Title: How can NodeJS be "non-blocking"?


问:
Is this a Single Responsibility Principle violation?
I'm designing an OO graph library and at the moment I'm trying to figure out the design for a GraphEdge class. I've added setters and getters for it's nodes, direction and weight. This seemes perfectly reasonable.

Then I've started working on the Graph class and I've come to the need of knowing if the particular edge is adjacent to the particular node.

And now I doubt if I should add a isAdjacentTo(Node) method to the GraphEdge class or I should create a GraphUtil class(*) and add static edgeIsAdjacentToNode(Edge,Node) method to it.

On the one hand, I can not see any additional reasons for changing GraphEdge if I stick to the first option. On the other hand, this seems to me like kind of second responsibility added to the class.

Also if I stick to the first option this will probably violate the Open-Close Principle. The GraphEdge is not closed for changes, since later I will need to add linksNodes(Node,Node) method to it and maybe some others later.

The questions are:

Does adding isAdjacentTo(Node) method to the GraphEdge class violates the SRP?

Why?

(*) I stick to pure OO style with no free functions

答:
I believe you've wandered into the field of over-engineering, chasing abstract principles instead of focusing on get things done in the simplest and most pleasant way.

Your (*) is a clear giveaway. OO can provide great help in managing complexity, but only as long as it's used as a tool to that goal. If instead you want to "write pure OO" instead of "solving my problem", it becomes a burden.

SRP is a similar thing -- it's well worth thinking. And especially good use to drive "extract" or "split" type of refactorings when your current code is overburdened with too many tasks.   After addressing DRY usually we still have a plenty of options on packaging, and it is a matter of balance. Too big class is bad, but having it single has benefits. If the same task is done by 5 classes it may be way harder to follow. Especially if none of them have a chance to work alone, they are coupled with cross-calls in all directions.   Such split might look good on dumb statistics but is bad for practice anyway.

So much for the theory, what about your case? You picked a border problem; indeed the function may not fit either Node or Edge. Though even that is hard to tell without the content, knowing what those actually do. Can I walk the graph having just a Node or an Edge? If I can, then adjacent may fit to that same group of functions.

Actually as soon as you have implementation of the function, it should be a great help to see where it fits better -- what data it had to fetch. Say, if it starts with getting the node and edge collections from Graph, why on earth is it not just member of Graph and play on the home ground?

A free function might also be fair game. A *Utils fake class that is really just a trash bin is probably the worst way, that hardly wins anything but adds to complexity.  But a language or an ill-conceived policy may force that.


问:
Are Ruby on Rails / Grails the fastest frameworks for getting sites up quickly?
I'm considering using Grails for a new website, but am open to other/new programming languages and frameworks.  I have done development using J2EE/JSF2, ASP.NET, and PHP.  Is Grails or Ruby on Rails pretty much the best way to get functionality up and running quickly?

Some initial thoughts:

DJango looks similar to RoR/Grails and I'd consider it

GWT is an interesting concept but it doesn't seem like turnaround time is quite as fast

Thanks,
-Jon

答:
As with all questions of this sort, the answer is "it depends". Factors to consider include how comfortable you are with the language/framework and what features the project requires. Having said that, I've built sites using a number of frameworks, each with its own strengths and weaknesses:

Grails

If I need to get a site up quickly for anything professional, Grails would probably be my first choice. GORM is far and away the simplest and most intuitive ORM that I've tried, the MVC paradigm is very well executed, there is 0 configuration to start coding (no worrying about URLs, DB patches, anything), very rapid iteration (just refresh the page), seamless Java integration (a good thing in the business world), and some wonderful plugins (e.g. Searchable is a thing of beauty). Biggest downside is that hosting can be tough to find (and expensive).

Ruby on Rails

My experience with RoR is very similar to that of Grails: MVC well executed. On the positive side, it has a bigger community, so the online resources (documentation, FAQ, code samples, etc) are very plentiful, there are TONS of plugins, Ruby is a bit more flexible/expressive/"funky",
and it's much easier to find hosting (esp. for personal projects); on the negative side, the dependency management/setup sucks (I've used RubyGems on Windows, Ubuntu, Fedora and OSX and ran into non-trivial problems on each one), there is slightly more configuration/overhead than Grails (in particular, dealing with routes.rb and tons of db migration files), and apparently, RoR has some serious scalability issues.

PHP (including the CakePHP framework)

If I need to quickly hack something out or build a site for personal uses, then I'd probably go with PHP. PHP is far and away the easiest language to learn and deploy: download any of the convenient LAMP packages out there, click a couple times, and begin hacking away. The community is bigger than that of RoR, so documentation is plentiful and there are countless plugins (easily "installed" by just dropping in the php file and refreshing the page). The language is simple to learn, but some things in PHP are just downright strange and it takes a lot of discipline to avoid ugly code. The CakePHP framework enforces a nice MVC paradigm to help keep things orderly, and for the most part is on par with RoR, although I personally found it slightly more unintuitive.

Java (servlets, JSPs, JSTL, struts, Velocity)

I've built many sites using the Java servlet technologies, and I can honestly say that there is no good reason to pick them for any new site nowadays. They have a steep learning curve, tons of configuration to fight with (XML hell), slow iteration due to the need to redeploy stuff all the time (unless you use JRebel), verbose code, and no "freebies" in terms of functionality. I've played around with the Play! Framework and Spring Roo a little bit and both are doing some very cool stuff with more or less "pure" Java code and are worth looking into further.


问:
Help identify the pattern for reacting on updates
There's an entity that gets updated from external sources. Update events are at random intervals. And the entity has to be processed once updated. Multiple updates may be multiplexed. In other words there's a need for the most current state of entity to be processed.

There's a point of no-return during processing where the current state (and the state is consistent i.e. no partial update is made) of entity is saved somewhere else and processing goes on independently of any arriving updates.

Every consequent set of updates has to trigger processing i.e. system should not forget about updates. And for each entity there should be no more than one running processing (before the point of no-return) i.e. the entity state should not be processed more than once.

So what I'm looking for is a pattern to cancel current processing before the point of no return or abandon processing results if an update arrives. The main challenge is to minimize race conditions and maintain integrity.

The entity sits mainly in database with some files on disk. And the system is in .NET with web-services and message queues.

What comes to my mind is a database queue-like table. An arriving update inserts row in that table and the processing is launched. The processing gathers necessary data before the point of no-return and once it reaches this barrier it looks into the queue table and checks whether there're more recent updates for the entity. If there are new updates the processing simply shuts down and its data is discarded. Otherwise the processing data is persisted and it goes beyond the point of no-return.

Though it looks like a solution to me it is not quite elegant and I believe this scenario may be supported by some sort of middleware.

If I would use message queues for this then there's a need to access the queue API in the point of no-return to check for the existence of new messages. And this approach also lacks elegance.

Is there a name for this pattern and an existing solution?

答:
I was able to implement the pattern largely following Jimmy Hoffa's advice and ideas.

The pattern works for us for several months already and it works as follows.

Every time the Entity is updated we insert new row to the EntityRevision table. This table has autoincrement (identity) RevisionId field which we pass along to the Pre-Processing.

During Pre-Processing we extract the state of Entity associated with the RevisionId being processed and work with it. The point here is that we avoid using any queries that return current Entity state because it’s constantly changing as Entity is updated. In contrast the state associated with the Revision never changes and it’s safe to use it during concurrent updates.

The Entity’s RevisionId is sent to offline processing Queue after Pre-Processing. We use the following rules.
Say arrived RevisionId is equal to X

a) If there’s no other Revision for the same Entity in the Queue, we add X to the Queue

b) If there’s already RevisionId which is Y for the same Entity in the Queue:

if Y > X, we discard X. In other words we don’t need earlier Revision X to be processed offline.

if X > Y, we remove Y from Queue and X to Queue. Since Y is earlier than X, we replace it with X.

We make operations on the Queue to perform in serial order so that at most one process/thread alters the queue at any time. For now we use Mutex in the Queue operations.

The Offline Processing polls the Queue on a periodical schedule and does what it needs to do with Revisions in the Queue. Again we use here only state of Entity associated with its Revision.

While we guarantee that there’s the current Revision in the Queue pre-processed so far, we are still not protected from the same Entity being updated or update being pre-processed during or right after the ongoing Offline Processing. In such case an update will have to wait in the Queue for the next Offline Processing launch. But that’s ok, we can’t prohibit updates :) In fact those updates are the essence of the system.


问:
Should I be worried about overengineering programming assignments given during interview process?
I recently had a phone interview with a company. After that phone interview, I was told to complete a short programming assignment (a small program; shouldn't take more than three hours). I'm only directly instructed to complete the assignment and turn in the code. I was given complete freedom to use any language I wished and was not told exactly how to turn in the code.

Immediately I planned on throwing it on Github, writing a test suite for it, using Travis-CI (free continuous integration for public Github repositories) to run the test suites, and using CMake to build the Linux makefiles for Travis-CI. That way, not only can I demonstrate that I understand how to use Git, CMake, Travis-CI, and how to write tests, but I can also simply link to the Travis-CI page so they can see the output of the tests. I figured that'd make it a tiny bit more convenient for the interviewer.

Since I know those technologies well, it would add essentially no time to the assignment.

However, I'm a bit worried that doing all this for a relatively simple task would look bad. Although it wouldn't add much more time at all for me, I don't want them thinking I spend too much time on things that should be simple.

答:
As an interviewer I would be happy to see the knowledge of the process of developing software demonstrated by this approach; as opposed to just the writing of the code.

In particular, having a test suite for even very simple problems would be a good sign (even FizzBuzz level).  I've seen candidates submit solutions that didn't even solve the problem and a simple set of tests would have shown them this.  Also, having the commit history allows me to get an idea of the thought process that the candidate has used to get to the solution.

On the other hand, I have known people to be rejected by some companies at an early stage of the process for over-engineering.  However, in most cases, this has been due to over-engineering of the solution not necessarily the processes used.


答:
Having as an interviewee someone who understood things like version control, CI, unit testing and the like would be a step up on what I usually see.

Although, for me, the most important thing is that the problem is solved, and solved well, knowing that the candidate understood ways to improve the quality of their deliverable would definitely get my attention.

What I generally see is people who not only didn't understand the problem, but who also didn't understand how to go about solving the problem - and they'd get ignored no matter how many extra tools they used in the process.

Title: Should I be worried about overengineering programming assignments given during interview process?

Body:
I recently had a phone interview with a company. After that phone interview, I was told to complete a short programming assignment (a small program; shouldn't take more than three hours). I'm only directly instructed to complete the assignment and turn in the code. I was given complete freedom to use any language I wished and was not told exactly how to turn in the code.

Immediately I planned on throwing it on Github, writing a test suite for it, using Travis-CI (free continuous integration for public Github repositories) to run the test suites, and using CMake to build the Linux makefiles for Travis-CI. That way, not only can I demonstrate that I understand how to use Git, CMake, Travis-CI, and how to write tests, but I can also simply link to the Travis-CI page so they can see the output of the tests. I figured that'd make it a tiny bit more convenient for the interviewer.

Since I know those technologies well, it would add essentially no time to the assignment.

However, I'm a bit worried that doing all this for a relatively simple task would look bad. Although it wouldn't add much more time at all for me, I don't want them thinking I spend too much time on things that should be simple.


问:
Help me to understand following points about the strategy pattern, how it relates to open/closed principle
I am learning design patterns. I read this article. Point no. 3 is not clear to me. The writer said that strategy lets you change the guts of an object. But this is a violation of the open-close principle. Am I wrong? If I am wrong, then help me to understand what writer wanted to describe.

Strategy is like Template Method except in its granularity.

State is like Strategy except in its intent.

Strategy lets you change the guts of an object. Decorator lets you change the skin.

State, Strategy, Bridge (and to some degree Adapter) have similar solution structures.

They all share elements of the ‘handle/body’ idiom. They differ in intent - that is,   they solve different problems.

Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
Strategy objects often make good Flyweights.

答:
Strategy lets you change the guts of an object. But it is the violation of open-close principle. Am I wrong??

No, the opposite is the case, it is a standard example for the OCP. In the shown example, you change or extend the behaviour of TransportationToAirport (open for extensions) without modifying this class (closed for modifications). Just derive a new Strategy object (like Train) and use it in conjunction with your unmodified TransportationToAirport object.


问:
Reducing repetitive DI code
I have a method which constructs dependencies using Unity. Currently, all of the calls do pretty much the same thing: Registers 2 repository object and 2 'App Part' objects. My issue is, there's a lot of them and the method has become massive. I've generalised the calls but here's an example:

```<code>container.RegisterType<IRepositoryOneDataAccess, RepositoryOneDataAccess>();
container.RegisterType<IRepositoryTwoDataAccess, RepositoryTwoDataAccess>();
container.RegisterType<IAppPart, FirstAppPart>("FirstAppPart.TestName");
container.RegisterType<IAppPart, SecondAppPart>("SecondAppPart.TestName");
</code>```

I though that this could be split out to reduce the code in the method which registers the types with the container.

Firstly I moved the bottom 2 calls to another method since they both register to the same interface, I came up with this method:

```<code>private void RegisterParts<TPartOne, TPartTwo>(string firstAppPartName, string secondAppPartName) where TPartOne : IAppPart where TPartTwo : IAppPart
{
    container.RegisterType<IAppPart, TPartOne>(firstAppPartName);
    container.RegisterType<IAppPart, TPartTwo>(secondAppPartName);
}
</code>```

This seems to work but I'm not sure this is the best way to do it. I would also like to move the other calls out into another method preferably the same as this one I've created but I'm not sure how to do it or even if it's possible.

Is there a better way of refactoring this?

答:
This can be done using reflection over the assemblies if you use some conventions. Other DI libraries like StructureMap which I use has this feature. A quick search for Unity found this library Unityconfiguration although I haven't used it.

I also see that Unity 3.0 supports registration by convention. So the easiest option may be to upgrade.

Title: Reducing repetitive DI code


问:
In OnionArchitecture can UI talks directly to datastore or not?
I'm fan of onion architecture but looking for some relaxing solutions in some areas.

First of all I was thinking about communicating directly from UI (from controller in mvc) to data on the read side. As everyone can see UI should not be referenced to any assembly  except Core.

When I want to display list of countries on page to select one, that I really need to do this through my Core?

I see two solutions:

UI has reference to NHibernate and talks directly

add a very thin abstraction layer where I define IFinder<> (only to read data) which will be implemented in infrastructure

Thoughts?

答:
The purpose of an onion architecture is that one layer doesn't need to be concerned with how the other layers operate internally.

The fact that the model uses Hibernate to get the list of countries is something the UI layer doesn't need to know. You could, for example later decide to hardcode the list of countries, cache it in memory or try out some exotic NoSQL solution which isn't supported by Hibernate. This is a decision which should only concern the model, not the UI. So the UI should obtain all information about the model through encapsulating method calls, no matter how thin they are initially.


问:
Generic and type safe I/O model in any language
I am looking for an I/O model, in any programming language, that is generic and type safe.

By genericity, I mean there should not be separate functions for performing the same operations on different devices (read_file, read_socket, read_terminal). Instead, a single read operation works on all read-able devices, a single write operation works on all write-able devices, and so on.

By type safety, I mean operations that do not make sense should not even be expressible in first place. Using the read operation on a non-read-able device ought to cause a type error at compile time, similarly for using the write operation on a non-write-able device, and so on.

Is there any generic and type safe I/O model?

答: You could implement something like this using c++ templates. Boost has a lot of examples of limiting behavior at compile time (eg the graph library). The main hurdle to overcome is the syntax of templates.</p>


问:
What is the origin/meaning of the name 'NHibernate'?
Been poking around the web because I was curious as to why they called it that but haven't found anything yet. Anyone know?

(I checked the FAQ and it wasn't clear if questions on history/origins were OK to put here or not, but I figured it wouldn't be good on StackOverflow, feel free to start closing it if it is out of scope and I will delete.)

答:
It's the .NET port of Hibernate. At least it started out as such.

It's a somewhat popular naming pattern for .NET ports of existing projects to just stick an "N" in front or a "#" in the back. E.g. NUnit, a port of JUnit (itself a port of SUnit). Noda Time, a port of Joda Time.


问:
What stops HTML5 and JS apps to perform as good as native apps?
From what I understand,

HTML is a mark-up language, so is the content of XAML, XIB and
whatever Android uses and other native UI development frameworks.

JavaScript is a programming language used along with it to handle
client side scripting which will include things like event handling,
client side validations and anything else C#,Java,Objective-C or C++
do in various such frameworks.

There are MVC/MVVM patterns available in form frameworks like Sencha's, Angular etc.

We have localStorage in form of both sqlite and key-value store as other frameworks have and you have API specification for almost everything that it missing.

Whenever a native UI frameworks has to render UI , it has to parse a similar the markup and render the UI.

Question break-down

What stops from doing the same in HTML and JS itself ?

Instead of having a web-control or browser as a layer in between why can't HTML(along with CSS) and JS be made to perform the same way ?

Even if there is a layer,so does .net runtime and JVM are in other cases where C++,C are not being used.

So Lets take the case of Android, like Dalvik, why Can't Chromium be another option(along with dalvik and NDK) where HTML does what android markup does and JavaScript is used to do what Java does ?

So the Question is,

Even if current implementations aren't as good, but theoretically is it possible to get HTML5 based applications to work as other native apps specially on mobile ?

答:
One reason why Javascript is slow is its total lack of type safety. Any variable can be of any type at any time. Also, most operations are valid with many different types, but have different semantics. A simple term

```<code>a += b;
</code>```

isn't that trivial for the interpreter, because a and b could be numbers or strings.  When both are numbers, it's an arithmetic addition. When both are string, this is a string concatenation. When one is a string and one is a number, the number must be formatted before performing a string concatenation. These are completely different operations which require to interprete the arguments differently.

Depending on the types of a and b, the type of a can now be integer, double or String, regardless of what type it was before.

Because variables in JS can change their type at any time, the interpreter hardly gets around evaluating the types whenever this instruction is called to avoid doing the wrong operation. This requires additional CPU cycles.

Other features which make optimization much harder are sparse arrays or garbage collection and event handlers which can fire at any time.

Take a look at asm.js - It's a subset of Javascript which allows much better optimization by getting rid of some JS features, notably dynamic typing.

Body:
One reason why Javascript is slow is its total lack of type safety. Any variable can be of any type at any time. Also, most operations are valid with many different types, but have different semantics. A simple term

a += b;

isn't that trivial for the interpreter, because a and b could be numbers or strings.  When both are numbers, it's an arithmetic addition. When both are string, this is a string concatenation. When one is a string and one is a number, the number must be formatted before performing a string concatenation. These are completely different operations which require to interprete the arguments differently.

Depending on the types of a and b, the type of a can now be integer, double or String, regardless of what type it was before.

Because variables in JS can change their type at any time, the interpreter hardly gets around evaluating the types whenever this instruction is called to avoid doing the wrong operation. This requires additional CPU cycles.

Other features which make optimization much harder are sparse arrays or garbage collection and event handlers which can fire at any time.

Take a look at asm.js - It's a subset of Javascript which allows much better optimization by getting rid of some JS features, notably dynamic typing.


答:
The poster boy for HTML5 apps, LinkedIn went native early 2013.
In the interview in VentureBeat they explain why.

I think this is the part most relevant to your question:

Prasad said performance issues weren’t causing crashes or making the
  app run slowly. What he did say shows that HTML5 for the mobile web
  still has a bright future — but only if developers are willing to
  build the tools to support it.

...

There are a few things that are critically missing. One is tooling
  support — having a debugger that actually works, performance tools
  that tell you where the memory is running out. If you look at Android
  and iOS, there are two very large corporations that are focused on
  building tools to give a lot of detailed information when things go
  wrong in production. On the mobile web side, getting those desktop
  tools to work for mobile devices is really difficult. The second big
  chunk we are struggling with is operability, runtime diagnostics
  information. Even now, when we build HTML5, we build it as a
  client-side app. It’s more of a client-server architecture. … The
  operability of that, giving us information when we’re distributed to a
  large volume of users, there aren’t as many great tools to support
  that, as well.

[Prasad also noted that dev and ops tools for solving
  issues quickly "don't exist."]

Because those two things don’t exist,
  people are falling back to native. It’s not that HTML5 isn’t ready;
  it’s that the ecosystem doesn’t support it. … There are tools, but
  they’re at the beginning. People are just figuring out the basics.

Title: What stops HTML5 and JS apps to perform as good as native apps?

Body:
From what I understand,

HTML is a mark-up language, so is the content of XAML, XIB and
whatever Android uses and other native UI development frameworks.

JavaScript is a programming language used along with it to handle
client side scripting which will include things like event handling,
client side validations and anything else C#,Java,Objective-C or C++
do in various such frameworks.

There are MVC/MVVM patterns available in form frameworks like Sencha's, Angular etc.

We have localStorage in form of both sqlite and key-value store as other frameworks have and you have API specification for almost everything that it missing.

Whenever a native UI frameworks has to render UI , it has to parse a similar the markup and render the UI.

Question break-down

What stops from doing the same in HTML and JS itself ?

Instead of having a web-control or browser as a layer in between why can't HTML(along with CSS) and JS be made to perform the same way ?

Even if there is a layer,so does .net runtime and JVM are in other cases where C++,C are not being used.

So Lets take the case of Android, like Dalvik, why Can't Chromium be another option(along with dalvik and NDK) where HTML does what android markup does and JavaScript is used to do what Java does ?

So the Question is,

Even if current implementations aren't as good, but theoretically is it possible to get HTML5 based applications to work as other native apps specially on mobile ?


答:
Keep in mind there's a time limit on it. The interviewer knows this, so this means (if I were the interviewer) he will see you not only solved the problem within the alotted time, but did it so quickly you had time left over for gold plating, which is a good sign of your problem solving abilities as well as your appreciation of rigor and diligence.

Over-engineering is a bad word when you're creating AbstractFactoryManagerAdaptors that get plugged in to hand out BuzzManager and FizzManager just to solve FizzBuzz.

What you are doing is over-diligence, which isn't even a thing (though under-diligence definitely is).

That said, if you end up over time or with some half-hacked solution because you used your time on the extras which you claim "add no time at all", this will look as though you have very poor understanding of how large appearingly small tasks can be. This can be a dangerous attribute in an engineer and all-too-common among juniors. Prioritize appropriately and do the extra-credit stuff only after completing the required solution.


答:
I recently had a phone interview with a company. After that phone interview, I was told to complete a short programming assignment (a small program; shouldn't take more than three hours).

I'd proceed with caution. Evaluate the relevancy of the challenge to the job, and be sure future reimbursement from the employer will make 3 hours of your time worthwhile.

I question the value in these types of tests, and would rather judge someone on their past accomplishments. A predefined short task can not tell the employer anything about what you can do. Only what you can not do, and that can quickly be determined with a few questions over the phone.

Testing does have it's place. Ask yourself the following questions about the test, and respond accordingly.

Is the test fair given your current career level?

Does the test have a clearly defined correct answer?

Does the interviewer have an interest in your potential as a person or are they showing more interest in the test results (i.e. hiring agencies are terrible for this).

Does the test represent the kind of work you would enjoy doing or is it an ambiguous skills verification (i.e. test if you know Java syntax).

I'm only directly instructed to complete the assignment and turn in the code.

You've just answered your own question.

Immediately I planned on throwing it on Github, writing a test suite for it, using Travis-CI (free continuous integration for public Github repositories) to run the test suites, and using CMake to build the Linux makefiles for Travis-CI.

No, that's not what they asked you to do.

That way, not only can I demonstrate that I understand how to use Git, CMake, Travis-CI, and how to write tests, but I can also simply link to the Travis-CI page so they can see the output of the tests. I figured that'd make it a tiny bit more convenient for the interviewer.

I'd be careful demonstrating skills too early or too late in the interview process. If you feel you didn't do well in the interview, and are now trying to compensate then it's not going to work. On the other hand, doing too much when not asked too demonstrates over eagerness. This could result in the employer countering with a lower wage offer then you were expecting.

However, I'm a bit worried that doing all this for a relatively simple task would look bad.

Yes it looks bad. Solving their challenge with one line of code will be far more impressive than a full flushed out project.

From my experience this is not how you win the job interview, but it's one way to lose the job. The code test is a quality control issue. Every company that uses code tests when hiring people is doing so, because previously they weren't using code tests. They had a bad experience of someone slipping thru the cracks of the interview process that should not have.

They will take your source code and pass it around the office. People will comment on it, and what you do not want them to say is "He made this mistake? but was spending time using Git, CMake and Travis-CI. What an idiot for missing this mistake."

That's it. You've lost.

They want to know you can code, because they can't teach you that. Git, CMake and Travis-CI can easily be taught.


答:
For new programmers, the most important part of overcoming this is to really understand what they're doing.

In many areas, when you don't know how to do something, you just go by trial and error. Try something; if it works, great, if not, try something else.

In programming, especially when using a language that has the concept of undefined behavior (like C or C++), this approach simply doesn't work, because success is no longer a boolean decision. You can have things that "kind of" work, that sometimes work, that work for some inputs but not others.

I have on occasion tutored new programmers, and the tendency to try typing random stuff to see if it works is common. They would type a line, and then turn to me and ask, "Would it work this way?" while it was clear that they had absolutely no clue whether it might.

The takeaway is that as a new programmer you really have to be able to explain what your code does. You have to learn to read code, not just write it.

(Of course that applies to seasoned programmers as well, but my experience here has been mostly with new complete beginners.)


答: If you directly call NHibernate from the UI layer you are not implementing the Onion architecture, and your code will be highly coupled. For a small project this may not matter, but if you're creating something more lasting or an enterprise solution you will want to create an interface as in your second example to ensure that you have full flexibility to change the concrete implementation later on. You will also most likely want to look into using an IoC container to inject your dependencies, though again consider whether your project really needs the Onion approach as all this will add a fairly significant coding overhead.</p>

Title: In OnionArchitecture can UI talks directly to datastore or not?

Body:
I'm fan of onion architecture but looking for some relaxing solutions in some areas.

First of all I was thinking about communicating directly from UI (from controller in mvc) to data on the read side. As everyone can see UI should not be referenced to any assembly  except Core.

When I want to display list of countries on page to select one, that I really need to do this through my Core?

I see two solutions:

UI has reference to NHibernate and talks directly

add a very thin abstraction layer where I define IFinder<> (only to read data) which will be implemented in infrastructure

Thoughts?


答:
Gavin King created Hibernate for Java back in 2001 as an alternative to EJBs.  His project was later taken over/sponsored by JBoss, which is now part of Red Hat.

There was another alternative at the time called TopLink for Java, originally by Object People, then bought by BEA, and now owned by Oracle.  Hibernate borrowed TopLink's concept of object/relational mapping (ORM) to simplify the translation of Java objects to relational database records and vice versa.

Anyhow, the idea is that often you need your data to go into stasis for an indefinite period of time--that is, until somebody needs it again.  This is not the sort of thing you want to leave in volatile memory--you want it to be persistent.

This is what hibernation is all about.  When a bear goes into hibernation in the winter, his bodily systems slow down to the point where they consume almost no energy--thus he doesn't have to do typical bear things like hunting.  Hibernation is going into a sort of stasis until activity is required again.

So, when Gavin was looking for a name for his project, he came up with "Hibernate" as a fairly descriptive name.  Hibernate was then ported to platforms other than Java, most notably to .NET.  In order to avoid confusion with the original Hibernate (which is a Java tool) they called it nHibernate, with the "N" standing for .NET.

Title: What is the origin/meaning of the name 'NHibernate'?

Body:
Been poking around the web because I was curious as to why they called it that but haven't found anything yet. Anyone know?

(I checked the FAQ and it wasn't clear if questions on history/origins were OK to put here or not, but I figured it wouldn't be good on StackOverflow, feel free to start closing it if it is out of scope and I will delete.)