问:
Need sorting method for coordinated, flattenned collection
I have a component which outputs an ICollection of the following type:

```<code>public class CoordinatedInjectableValue
{
    public int XOffset { get; set; }

    public int YOffset { get; set; }

    public object Value { get; set; }
}
</code>```

This is used to describe what is basically a dataset, so for a given XOffset value, the "Value" property of all these objects will be of the same type (int, string, etc). The Value property is always a built-in type, not a custom type.

My challenge is that I would like to use this collection to build up a kind of dataset structure which allows sorting on the columns.

As an example, if I had a collection which looked like this:

```<code>new List<CoordinatedInjectableValue>
{
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 20},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 30},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "CCC"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "BBB"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "AAA"}
};
</code>```

I want some method so I can reorder based on the first "column" (ie, where XOffset = 0), so that the collection would then look like this:

```<code>new List<CoordinatedInjectableValue>
{
    // Ordered by value where XOffset = 0
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 20},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 30},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "BBB"}, // Note this has also been re-ordered
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "CCC"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "AAA"}
}
</code>```

And if I ordered by the second column (XOffset = 1) then the following would happen:

```<code>new List<CoordinatedInjectableValue>
{
    // Ordered by value where XOffset = 1
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 30}, // Note this has also been re-ordered
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 20},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "AAA"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "BBB"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "CCC"}
};
</code>```

As you can imagine, I'm having some difficulty doing this, even for single-level sorting. I haven't even tried implementing multi level sorting (eg, sort by this, then that).

I am looking for some kind of logical approach to this. I'd rather not have to change the component which returns this data, as it's supplied by a third party, and would be costly for us to change.

答:
```<code>    public class CIVComparer : IComparer<CoordinatedInjectableValue>
{
    private string SortBy { get; set; }
    private bool SortAscending { get; set; }

    public CIVComparer()
    {
        SortBy = "default";
        SortAscending = true;
    }

    public CIVComparer(string sortBy, bool sortAscending)
    {
        SortBy = sortBy;
        SortAscending = sortAscending;
    }

    #region IComparer<CoordinatedInjectableValue> Members

    int IComparer<CoordinatedInjectableValue>.Compare(CoordinatedInjectableValue x, CoordinatedInjectableValue y)
    {
        CoordinatedInjectableValue cx, cy;
        if (SortAscending)
        {
            cx = x;
            cy = y;
        }
        else
        {
            cx = y;
            cy = x;
        }
        int result = 0;
        var useCulture = new System.Globalization.CultureInfo("en-US");
        string xCaseNum, yCaseNum;

        switch (SortBy)
        {
            case "XOffset":
                result = new Comparer(useCulture).Compare(cx.XOffset, cy.XOffset);
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.Value, cy.Value); }
                if (result == 0) { result = new Comparer(useCulture).Compare(xCaseNum, yCaseNum); }
                break;

            case "Value":
                result = new Comparer(useCulture).Compare(cx.Value, cy.Value);
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.XOffset, cy.XOffset); }
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.YOffset, cy.YOffset); }
                break;

            case "default":
            default:
                result = new Comparer(useCulture).Compare(cx.YOffset, cy.YOffset);
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.XOffset, cy.XOffset); }
                break;
        }
        return result;
    }

    #endregion
}
</code>```

Then, when you want to sort a list:

```<code>    List<CoordinatedInjectableValue> CIVs = MethodWhichReturnsList(argsForMethod);
    CIVComparer civComparer = new CIVComparer(sortBy, sortAscending);
    CIVs.Sort(civComparer);
</code>```

The logic in the Comparer will obviously be different, but, as you can see, it provides a lot of flexibility.

Body:
    public class CIVComparer : IComparer<CoordinatedInjectableValue>
{
    private string SortBy { get; set; }
    private bool SortAscending { get; set; }

    public CIVComparer()
    {
        SortBy = "default";
        SortAscending = true;
    }

    public CIVComparer(string sortBy, bool sortAscending)
    {
        SortBy = sortBy;
        SortAscending = sortAscending;
    }

    #region IComparer<CoordinatedInjectableValue> Members

    int IComparer<CoordinatedInjectableValue>.Compare(CoordinatedInjectableValue x, CoordinatedInjectableValue y)
    {
        CoordinatedInjectableValue cx, cy;
        if (SortAscending)
        {
            cx = x;
            cy = y;
        }
        else
        {
            cx = y;
            cy = x;
        }
        int result = 0;
        var useCulture = new System.Globalization.CultureInfo("en-US");
        string xCaseNum, yCaseNum;

        switch (SortBy)
        {
            case "XOffset":
                result = new Comparer(useCulture).Compare(cx.XOffset, cy.XOffset);
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.Value, cy.Value); }
                if (result == 0) { result = new Comparer(useCulture).Compare(xCaseNum, yCaseNum); }
                break;

            case "Value":
                result = new Comparer(useCulture).Compare(cx.Value, cy.Value);
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.XOffset, cy.XOffset); }
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.YOffset, cy.YOffset); }
                break;

            case "default":
            default:
                result = new Comparer(useCulture).Compare(cx.YOffset, cy.YOffset);
                if (result == 0) { result = new Comparer(useCulture).Compare(cx.XOffset, cy.XOffset); }
                break;
        }
        return result;
    }

    #endregion
}

Then, when you want to sort a list:

    List<CoordinatedInjectableValue> CIVs = MethodWhichReturnsList(argsForMethod);
    CIVComparer civComparer = new CIVComparer(sortBy, sortAscending);
    CIVs.Sort(civComparer);

The logic in the Comparer will obviously be different, but, as you can see, it provides a lot of flexibility.


答:
This is not just a sorting problem. You are also updating the YOffset values based on the sorting. So assume the input data is valid(i.e. no missing offsets, consistent type of Value property). Here is the code:

Source data:

```<code>var givenList = new List<CoordinatedInjectableValue>
{
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 20},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 30},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "CCC"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "BBB"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "AAA"}
};
</code>```

LINQ:

```<code>var sortedByFirstColumn = givenList
.GroupBy(v => v.YOffset)
.OrderBy(grp => grp.First(x => x.XOffset == 0).Value)
.SelectMany((grp, i) =>
    grp.Select(v => new CoordinatedInjectableValue
    {
        XOffset = v.XOffset,
        YOffset = i,
        Value = v.Value
    }))
</code>```

Verify the result:

```<code>sortedByFirstColumn
.OrderBy(v => v.XOffset)
.ThenBy(v => v.YOffset)
.ToList()
.ForEach(v => Console.WriteLine("{0}\t{1}\t{2}", v.XOffset, v.YOffset, v.Value));
</code>```

The output:

```<code>0   0   10
0   1   20
0   2   30
1   0   BBB
1   1   CCC
1   2   AAA
</code>```

Note: I kept sortedByFirstColumn as IEnumerable and unordered, but adjust it the way how your application requires.

ContentLicense: CC BY-SA 3.0

Title: Need sorting method for coordinated, flattenned collection

Body:
I have a component which outputs an ICollection of the following type:

```<code>public class CoordinatedInjectableValue
{
    public int XOffset { get; set; }

    public int YOffset { get; set; }

    public object Value { get; set; }
}
</code>```

This is used to describe what is basically a dataset, so for a given XOffset value, the "Value" property of all these objects will be of the same type (int, string, etc). The Value property is always a built-in type, not a custom type.

My challenge is that I would like to use this collection to build up a kind of dataset structure which allows sorting on the columns.

As an example, if I had a collection which looked like this:

```<code>new List<CoordinatedInjectableValue>
{
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 20},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 30},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "CCC"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "BBB"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "AAA"}
};
</code>```

I want some method so I can reorder based on the first "column" (ie, where XOffset = 0), so that the collection would then look like this:

```<code>new List<CoordinatedInjectableValue>
{
    // Ordered by value where XOffset = 0
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 20},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 30},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "BBB"}, // Note this has also been re-ordered
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "CCC"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "AAA"}
}
</code>```

And if I ordered by the second column (XOffset = 1) then the following would happen:

```<code>new List<CoordinatedInjectableValue>
{
    // Ordered by value where XOffset = 1
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 30}, // Note this has also been re-ordered
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 20},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "AAA"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "BBB"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "CCC"}
};
</code>```

As you can imagine, I'm having some difficulty doing this, even for single-level sorting. I haven't even tried implementing multi level sorting (eg, sort by this, then that).

I am looking for some kind of logical approach to this. I'd rather not have to change the component which returns this data, as it's supplied by a third party, and would be costly for us to change.

Body:
This is not just a sorting problem. You are also updating the YOffset values based on the sorting. So assume the input data is valid(i.e. no missing offsets, consistent type of Value property). Here is the code:

Source data:

var givenList = new List<CoordinatedInjectableValue>
{
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 0, Value = 20},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 1, Value = 10},
    new CoordinatedInjectableValue {XOffset = 0, YOffset = 2, Value = 30},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 0, Value = "CCC"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 1, Value = "BBB"},
    new CoordinatedInjectableValue {XOffset = 1, YOffset = 2, Value = "AAA"}
};

LINQ:

var sortedByFirstColumn = givenList
.GroupBy(v => v.YOffset)
.OrderBy(grp => grp.First(x => x.XOffset == 0).Value)
.SelectMany((grp, i) =>
    grp.Select(v => new CoordinatedInjectableValue
    {
        XOffset = v.XOffset,
        YOffset = i,
        Value = v.Value
    }))

Verify the result:

sortedByFirstColumn
.OrderBy(v => v.XOffset)
.ThenBy(v => v.YOffset)
.ToList()
.ForEach(v => Console.WriteLine("{0}\t{1}\t{2}", v.XOffset, v.YOffset, v.Value));

The output:

0   0   10
0   1   20
0   2   30
1   0   BBB
1   1   CCC
1   2   AAA

Note: I kept sortedByFirstColumn as IEnumerable and unordered, but adjust it the way how your application requires.


问:
Entity Framework Domain Object as Business Object
If I am not concerned with unit testing and switching my data access out at a later time, would using my entity framework objects as my business objects be okay?

I have an existing database for which I generated entities and a datacontext, and have partial classes for holding my methods and any additional (non-database) properties. I have read quite a bit about repository pattern and other seemingly complex ways of setting this up, but I'm not sure all of that is necessary. It is a .NET Web Forms app using Entity Framework 6.1.3 and will not have unit testing.

Are there other reasons why I should avoid such a simplistic approach?

答:
I would not extend POCOs to use them as business objects. It will mix domain logic with data logic and the codes become very difficult to maintain in the future. </p>

<p>But you also mentioned you will not have unit testing. So maybe you are building some one-off, short-lived project that does not need to be maintained and then it may be Okay. Just remember it may create lots of technical debts that you (or other devs) have to deal with later. </p>

Body:
I would not extend POCOs to use them as business objects. It will mix domain logic with data logic and the codes become very difficult to maintain in the future.

But you also mentioned you will not have unit testing. So maybe you are building some one-off, short-lived project that does not need to be maintained and then it may be Okay. Just remember it may create lots of technical debts that you (or other devs) have to deal with later.


问:
Are SMART goals useful for programmers?
Several organisations I know use SMART goals for their programmers. SMART is an acronym for Specific, Measurable, Achievable, Relevant and Time-Bound. They are fairly common in large corporations.

My own prior experience with SMART goals has not been all that positive. Have other programmers found them an effective way to measure performance? What are some examples of good SMART goals for programmers (if they exist).

答:
SMART-type objective-setting can be useful in a programming context but it has to be done intelligently or, as pointed out in other answers, it's likely to be time-wasting (or worse).

To get useful objectives, it helps to agree what the SMART acronym will mean: a quick Google search found varying definitions:

S: seems to have consensus at Specific (although there's some disagreement about what that means)

M: Meaningful and Motivational are
alternatives to the more common
Measurable

A: seems most often to
represent Achievable, but I've also
seen Agreed-upon

R: depending where
you look, you can find Realistic,
Relevant, Results-focused

T seems always to reference Time, although
the emphasis varies

So first, both sides of the objective-setting negotiation should be working from a common understanding of the process.

Next, the overall goals for the organisation, division, group, team (or whatever hierarchy is relevant) need to be explained and understood. At that point it should be possible for the individual (IMO, goals have to be set at the individual level to be worthwhile) to be able to agree on a small number of objectives that should inform that person's activities going forward.

If it ends there, it's still been a waste of everyone's time. Objectives need to be reviewed and adjusted regularly - where achieved, the possible need to set new objectives should be considered, where not achieved, reasons should be identified and corrective action prescribed where necessary.

Everyone concerned should be aware that this kind of exercise is not worthwhile if it's not taken seriously, or perhaps more algorithmically, the value to be extracted is proportional to the effort put in.

It might be instructive to see what people think might be useful/worthwhile SMART objectives. I've put up a question here...

Title: Are SMART goals useful for programmers?

ContentLicense: CC BY-SA 2.5


问:
Algorithm for calculating a bullet path to a target with max. 2 ricochets
Sorry for the poor title but I didn't have a better way to phrase it...

So there's this amazing game by Nintendo (yes!) on Wii called WiiPlay. There're 9 minigames in it, and my favorite one is called Tanks!. It's about destroying COM enemy tanks without getting yourself destroyed. Here's a screenshot of a level:

One way to destroy tanks is by firing bullets. There's this lime green enemy tank which fires high-speed bullets that ricochet (against the walls and blocks) twice. You can see how the player tank can get instantly destroyed if it stays at where it is now, as that lime tank in the center can fire a bullet that follows the green path I drew on the image.

As an amateur programmer myself I have been wondering how can the lime tank determine at which direction it should fire at to smite the player tank.

I thought about it myself but didn't came up with any possible algorithm. I'll explain my conclusions in case they inspire someone. Just for simplicity during my explanation, I assume a wall to be any surface against which a bullet can ricochet. An isolated rectangle of blocks thusly form four walls.

I concluded that the 2 points at which the bullet ricochets always either lie on one side of a parallelogram or become opposite vertices of a parallelogram. The firing enemy tank and the player tank it aims are not necessarily the other 2 vertices but definitely lie on the lines colinear to either of the four sides of the parallelogram. Here is an illustration of the 4 possible ways a parallelogram can be formed:

HOR-VER means the bullet first hits a horizontal wall, then it hits a vertical wall.

And then I'm stuck. I thought about moving around a line that connects the enemy tank and the player tank around the map to see if it forms a parallelogram with any two hits with any wall, but this does not always work because the enemy tank and the player tank are not necessarily coincidental with the vertices of the parallelogram.

Also, I'm not sure of the general flow of the algorithm. Does the algorithm take any of the following 2 structures, or maybe I am wrong with both of these?

Keep figuring out possible paths and always mark one as the best (can be the shortest, the most obscure, the most inescapable, or a combined and weighted assessment based on multiple criteria) and forget about the rest. The one left after all calculation is the best one to take.

First determine all walls first reachable with the bullet (the bullet needs not ricochet against any other wall in order to reach each of these walls), then determine all reachable ranges on each of these walls (it is sometimes impossible to reach a faraway point on a wall without ricochet if another wall stands near you), then again determine all reachable walls with a ricochet, and all ranges reachable on these walls. These 4 processes can be done by a way similar to ray-tracing. During each process, if the player tank is hit by any ray, figure out the bullet path according to that ray.

In my opinion, this algorithm is hard to figure out because:

a bullet can be fired in any direction; and

there are infinitely many points on any wall, as in mathematics, where there are infinitely many points on a line.

But Nintendo people made it anyway, so... anybody with an idea?

答: First off, remember in physics class when you talked about refraction of light? Well your problem can be solved using those principles. The angle of incidence is equal to the angle of reflection. so the enemy tank needs to run through every possible angle for the first bounce so that the second bounce may hit the player. Keep going with the ray tracing idea too. Now, this gets complicated when the player is moving but it should be a good enough idea for you to get started on an algorithm </p>


答:
You can take advantage of the fact that the angle leaving the ricochet must be the same as the angle entering it.  For a given horizontal wall with y-coordinate c and two fixed tanks with coordinates (a,b) and (d,e), there is only one angle which satisfies the equation below.

Just solve for x to get the distance along the wall at which you must aim.  Two walls works the same.  You just have two equations and two unknowns.

Title: Algorithm for calculating a bullet path to a target with max. 2 ricochets

Body:
Sorry for the poor title but I didn't have a better way to phrase it...

So there's this amazing game by Nintendo (yes!) on Wii called WiiPlay. There're 9 minigames in it, and my favorite one is called Tanks!. It's about destroying COM enemy tanks without getting yourself destroyed. Here's a screenshot of a level:

One way to destroy tanks is by firing bullets. There's this lime green enemy tank which fires high-speed bullets that ricochet (against the walls and blocks) twice. You can see how the player tank can get instantly destroyed if it stays at where it is now, as that lime tank in the center can fire a bullet that follows the green path I drew on the image.

As an amateur programmer myself I have been wondering how can the lime tank determine at which direction it should fire at to smite the player tank.

I thought about it myself but didn't came up with any possible algorithm. I'll explain my conclusions in case they inspire someone. Just for simplicity during my explanation, I assume a wall to be any surface against which a bullet can ricochet. An isolated rectangle of blocks thusly form four walls.

I concluded that the 2 points at which the bullet ricochets always either lie on one side of a parallelogram or become opposite vertices of a parallelogram. The firing enemy tank and the player tank it aims are not necessarily the other 2 vertices but definitely lie on the lines colinear to either of the four sides of the parallelogram. Here is an illustration of the 4 possible ways a parallelogram can be formed:

HOR-VER means the bullet first hits a horizontal wall, then it hits a vertical wall.

And then I'm stuck. I thought about moving around a line that connects the enemy tank and the player tank around the map to see if it forms a parallelogram with any two hits with any wall, but this does not always work because the enemy tank and the player tank are not necessarily coincidental with the vertices of the parallelogram.

Also, I'm not sure of the general flow of the algorithm. Does the algorithm take any of the following 2 structures, or maybe I am wrong with both of these?

Keep figuring out possible paths and always mark one as the best (can be the shortest, the most obscure, the most inescapable, or a combined and weighted assessment based on multiple criteria) and forget about the rest. The one left after all calculation is the best one to take.

First determine all walls first reachable with the bullet (the bullet needs not ricochet against any other wall in order to reach each of these walls), then determine all reachable ranges on each of these walls (it is sometimes impossible to reach a faraway point on a wall without ricochet if another wall stands near you), then again determine all reachable walls with a ricochet, and all ranges reachable on these walls. These 4 processes can be done by a way similar to ray-tracing. During each process, if the player tank is hit by any ray, figure out the bullet path according to that ray.

In my opinion, this algorithm is hard to figure out because:

a bullet can be fired in any direction; and

there are infinitely many points on any wall, as in mathematics, where there are infinitely many points on a line.

But Nintendo people made it anyway, so... anybody with an idea?


问:
i++ vs i+=1 in cycles, why evaluate?
Why do most programmers use i++ in cycles? Doesn't it mean evaluate and increment. I find more logical to use just an increment i+=1, because that's all I want.

WriteLn(i++); would evaluate i and then increment, does it somehow remove the evaluation part if i++ is used in cycles?

答: If you're counting keystones saved, don't forget the possible shift; + and = are on the same key in many layouts.</p>

Title: i++ vs i+=1 in cycles, why evaluate?


问:
Is an Optional/Maybe type useful in dynamic languages?
Optional is useful in an obvious way in a statically typed language, but I'm wondering if it's also useful in dynamic languages.  Usually there's no compiler telling you, "hey, you used this Optional<String> as a String", so you still have to discover your mistakes at runtime.  I have a static typing background and from my perspective I can't see the benefit of an Optional type in a dynamic language.

答:
I can talk for Objective-C.

Since dynamic typed languages bind late, checking for an "optional" (a non-value is represented with nil)  is inherent: If you check for the type at runtime, you check for nil implicitly. Of course this is chainable. This is done inherently, too.

For static typed languages this extra concept is a benefit, because they have to take the type decision at compile time – a situation dynamic typed languages never have.


问:
Does requestAnimationFrame() really align with monitor refreshes?
Take this code:

```<code>requestAnimationFrame(function (timestamp) {
  console.log('one', timestamp);
});

requestAnimationFrame(function (timestamp) {
  console.log('two', timestamp);
});

// logs:
// "one", 184.6999999834225
// "two", 184.6999999834225
</code>```

The timestamp is milliseconds since the page loaded. Note these two rAF calls return different IDs which you can cancel individually.

Now let's make the first callback do something very expensive:

```<code>requestAnimationFrame(function (timestamp) {
  console.log('one', timestamp);

  // block for 1 second
  const endAt = Date.now() + 1000;
  while (true) {
    if (Date.now() >= endAt) break;
  }
});

requestAnimationFrame(function (timestamp) {
  console.log('two', timestamp);
});

// LOGS:
//   "one", 189.32800000533462
//   "two", 189.32800000533462  (this appears one second later)
</code>```

I'm confused: the second one runs a whole second later, but gets the same timestamp. Why can't it get a new timestamp, one corresponding with whatever the current monitor refresh frame is now at the time it's being called?

If rAF decides ahead of time that your callback must be run in the same frame as another callback, regardless of how long that other callback might take, then the 'frame' seems like a meaningless concept that doesn't correspond with a single monitor refresh - so what's the point?

I'm sure there's a good reason why it's implemented this way, I just want to understand it.

答:
Those two functions are scheduled to be run at the same time, but will actually never run at the same time in a single-threaded environment. They will run in sequence.

But while they are running the browser rendering is blocked and any effect that they do will happen at the same time when they both finish.

It makes sense for the timestamp to be the same because any visible effects of those functions will happen at the same time - so e.g. if you are animating two cars with the same speed then you would expect them to be always moving in sync, no matter how long it takes to calculate the position of any of them.

See this DEMO on jsbin:

```<code>// noprotect
var p1 = document.getElementById('p1');
var p2 = document.getElementById('p2');

requestAnimationFrame(function (timestamp) {
  console.log('one', timestamp);

  // block for 3 second
  var endAt = Date.now() + 3000;
  while (true) {
    if (Date.now() >= endAt) break;
  }
  p1.innerHTML = timestamp;
});

requestAnimationFrame(function (timestamp) {
  console.log('two', timestamp);

  // block for 3 second
  var endAt = Date.now() + 3000;
  while (true) {
    if (Date.now() >= endAt) break;
  }
  p2.innerHTML = timestamp;
});
</code>```

I changed your example to take longer (3 sec) for the effects to be more visible and to manipulate the DOM. Other changes were made to avoid jsbin warnings.

As you can see both of the DOM manipulations get visible at exactly the same time, so it would be strange if the timestamps were different.

Those timestamps are there to be used to calculate the positions of animated objects or other time dependent values. And if two functions were scheduled at the same time then they will have the same timestamp.

Body:
Those two functions are scheduled to be run at the same time, but will actually never run at the same time in a single-threaded environment. They will run in sequence.

But while they are running the browser rendering is blocked and any effect that they do will happen at the same time when they both finish.

It makes sense for the timestamp to be the same because any visible effects of those functions will happen at the same time - so e.g. if you are animating two cars with the same speed then you would expect them to be always moving in sync, no matter how long it takes to calculate the position of any of them.

See this DEMO on jsbin:

// noprotect
var p1 = document.getElementById('p1');
var p2 = document.getElementById('p2');

requestAnimationFrame(function (timestamp) {
  console.log('one', timestamp);

  // block for 3 second
  var endAt = Date.now() + 3000;
  while (true) {
    if (Date.now() >= endAt) break;
  }
  p1.innerHTML = timestamp;
});

requestAnimationFrame(function (timestamp) {
  console.log('two', timestamp);

  // block for 3 second
  var endAt = Date.now() + 3000;
  while (true) {
    if (Date.now() >= endAt) break;
  }
  p2.innerHTML = timestamp;
});

I changed your example to take longer (3 sec) for the effects to be more visible and to manipulate the DOM. Other changes were made to avoid jsbin warnings.

As you can see both of the DOM manipulations get visible at exactly the same time, so it would be strange if the timestamps were different.

Those timestamps are there to be used to calculate the positions of animated objects or other time dependent values. And if two functions were scheduled at the same time then they will have the same timestamp.


答:
You have neat diagrams showing how to direct rays, so I'll leave the details on how to determine a pair of reflecting surfaces.

Let's call the surface that must be hit first surface A, and the second, B.

Try to hit the (visible) edges of B by shooting at A. In other words, determine the points where one would see reflections of the ends of B if looking at the mirror-finished A. This must be easy to do, you have only one reflection point to handle.

Now you know two rays that hit the (visible) edges of B. Let's call them edge rays Compute their reflections off B; they must go somewhere past your target. You can determine if the target lies between them, that is, to the left of one ray but to the right of the other, or vice versa. This is trivial to do using the general equation of the straight line.

If the target is not between the edge rays, you obviously cannot hit it with any intermediate ray; pick another pair of surfaces.

If the target is between the rays, look for the intermediate hitting ray using binary search. You have two firing angles corresponding to the edge rays, your hitting angle lies between them. Provided that your target's angular diameter, as seen from the firing point, is not excessively small, you will need few iterations until you find a direction of a hitting ray.

Here's a picture:

Here the two edge rays are shown in red and blue. Apparently you can find a ray emitted at a smaller angle than the red one but greater that the red one so that that ray will hit the green target.


问:
Is it necessary to discuss database changes
I am working on a project with a team of 4-5 people. Is it necessary to discuss the database changes with the team before implementing?  I am working on the database api's.

Is it better to discuss this or not? In my team are senior people. So can't I make changes myself and implement the change and explain the changes.

答:
I dont think this is only related to database changes.

If you are not the Senior Architect or Database Programmer in your team, any changes you make to design & implementation of code or SQL or DB tables or any other artifacts, should be reviewed and approved by other team members - either peers or seniors.

Are you hesitant to do this? Is there no formal review process already in place?

Update:

In your case, it depends on what impact the changes have. Are you making a small change like the length of a single VARCHAR2 column or adding new columns to the table which need buy-in from the front-end developers too?
In any case, I'd say discussion is better than not doing so - and regretting later


问:
How should keypoll functions be designed in games?
So I'm making a clone of Super Mario Bros in pygame. As of now I am in the middle of making my keypoll function, to check all the keys that are currently being pressed. I am wondering which would be better:

Have the keypoll function modify marios attributes (ex. horizontal direction), then based on those, have mario decide which action he should be doing (ie. walk, run, jump, etc.) and call the function cooresponding to that action (ex. mario.moveHorz())

OR

Have the keypoll function call the function of the action he should be doing, and then the mario instance would decide what state he is currently in.

Here is some semi-pseudo code for the first one:

```<code>def doAction():
    if mario.horzDir == 'r' or 'l':
        mario.moveHorz()
    elif mario.action == 'jump':
        mario.jump()

 def keyPoll(keys):
    if keys[K_RIGHT]:
        mario.horzDir = 'r'
    elif keys[K_LEFT]:
        mario.horzDir = 'l'
    if keys[K_z]:
        mario.action = 'jump'
</code>```

Here is some more semi-pseudo code for the second one:

```<code>def keyPoll(keys):
    if keys[K_RIGHT]:
        mario.moveHorz('r')
    elif keys[K_LEFT]:
        mario.moveHorz('l')
    if keys[K_z]:
        mario.jump()

def setProperties():
    if mario.x_vel > 0:
        mario.horzDir = 'r'
    elif mario.x_vel < 0:
        mario.horzDir = 'l'
    elif mario.y > ground:
        mario.action  = 'jump'
</code>```

Both essentially accomplish the same thing, I just don't know which one is more correct.

Thanks!

答:
Because key polling usually happens at the very top of the game loop, the specific question you're asking is hard to separate completely from all the other extremely important issues one needs to be aware of when designing a game loop (Gilbert's comment appears to be referring to some of them). To get those out of the way, I'll simply suggest you read this: http://gameprogrammingpatterns.com/game-loop.html Now to answer your specific question.

It is better for your keypoll function to call mario methods than to set mario properties, mainly because all of these commands are going to have at least one or two extra steps beyond setting a field on the object. mario may have an internal state machine that keeps track of whether jumping or changing direction is even allowed in its current state. It may be keeping track of how many times it's been told to move right or left in the past several frames so it can speed up or slow down gradually. It may have yet more state to help it work out when you've done the inputs for various special combo moves. keyPoll() shouldn't have to know about any of that.

By setting a field and then calling a method to do all of this work, you're essentially doing in two steps what you could be doing with one step. That's usually not a good thing. Yes, it's likely that mario will have an update() or render() method to get called later on, but those should be completely separate from the methods for handling input.

Now, whether this is the best option depends on how complex your game is, but for most games, it's better to go even farther, and not have your keyPoll() function directly refer to mario at all. In principle, the only thing keyPoll() needs to do is check the state of the keyboard, and output zero or more objects that represent commands. If you ever want to support key rebinding or multiple control schemes, that logic would go in keyPoll(). Then the main loop gives these commands to whatever entity the player is currently controlling, presumably mario. By decoupling the input handling from the specific game entity, you make it easy to add new abilities to mario or support key rebinding or allow switching between multiple characters or add AI/demo characters and other cool stuff without having to worry about both the internals of keyPoll() and the internals of mario at the same time.


答:
Given a direct line of sight, the problem is obviously trivial. However, we are dealing with reflection. Properly finding out which parts of the scene can be seen is challenging when implementing reflection as part of a ray tracer, since this might miss some openings. A “binary search” between two promising angles is also not viable: due to the reflections, the actually visible space is not continuous, so the heuristic “if it's to the right of A and to the left of B, there must be a target solution between A and B” is not permissible, and will miss “creative” solutions. I would instead recommend implementing reflection by re-running the tracer from a virtual position – the position where our firing tank seems to be when seen in the mirror:

```<code>target |obstacle
   X   |
    \  |  X real position
     \   /
      \ /
   ----------- mirror surface
        \
         \
          X virtual position
</code>```

The advantage is that the mirrored ray is now a straight line originating from the virtual position. I tried to illustrate the technique in the following sketch:

X marks the firing position, (X) the target. The coloured areas are visible.

Direct line of sight: the target is not visible. However, we can hit surfaces (1) and (2).

One reflection. There are two virtual firing positions within the obstacles. The lower position has direct LOS to the target, so we have our first firing solution: the bullet path is the part of the ray between the target and the lower mirror surface, and between the ray–mirror collision point and the real firing position.

Two reflections: The upper virtual position from the first reflection can see part of the lower obstacle through its mirror surface. Since two reflections are allowed, we can mirror this position into the lower obstacle. The positions are marked as (I) the real position, (II) the virtual position from the first reflection, and (III) the virtual position from the second reflection.

From (III), we have direct LOS to the target (X), so we have found another firing solution. The bullet path is along the line X–III until the second mirror collision point, then along the line III–II between the mirror collision points, and finally along the line II–I from the first mirror collision point to the real position I.

Actually, the lower virtual position from the first reflection could also be reflected into the upper obstacle, but this will not lead to any direct solutions.

Once you can figure out which parts of the obstacles are visible (and can therefore be used to reflect the bullet), implementing mirroring via a depth-first search would seem straightforward. To find suitable mirror surfaces, the techniques outlined in Nicky Case's Sight & Light might be used: rather than trying out 360 vectors – which might miss openings, and also is wasteful – we launch rays only to the edges of obstacles.

Body:
Given a direct line of sight, the problem is obviously trivial. However, we are dealing with reflection. Properly finding out which parts of the scene can be seen is challenging when implementing reflection as part of a ray tracer, since this might miss some openings. A “binary search” between two promising angles is also not viable: due to the reflections, the actually visible space is not continuous, so the heuristic “if it's to the right of A and to the left of B, there must be a target solution between A and B” is not permissible, and will miss “creative” solutions. I would instead recommend implementing reflection by re-running the tracer from a virtual position – the position where our firing tank seems to be when seen in the mirror:

target |obstacle
   X   |
    \  |  X real position
     \   /
      \ /
   ----------- mirror surface
        \
         \
          X virtual position

The advantage is that the mirrored ray is now a straight line originating from the virtual position. I tried to illustrate the technique in the following sketch:

X marks the firing position, (X) the target. The coloured areas are visible.

Direct line of sight: the target is not visible. However, we can hit surfaces (1) and (2).

One reflection. There are two virtual firing positions within the obstacles. The lower position has direct LOS to the target, so we have our first firing solution: the bullet path is the part of the ray between the target and the lower mirror surface, and between the ray–mirror collision point and the real firing position.

Two reflections: The upper virtual position from the first reflection can see part of the lower obstacle through its mirror surface. Since two reflections are allowed, we can mirror this position into the lower obstacle. The positions are marked as (I) the real position, (II) the virtual position from the first reflection, and (III) the virtual position from the second reflection.

From (III), we have direct LOS to the target (X), so we have found another firing solution. The bullet path is along the line X–III until the second mirror collision point, then along the line III–II between the mirror collision points, and finally along the line II–I from the first mirror collision point to the real position I.

Actually, the lower virtual position from the first reflection could also be reflected into the upper obstacle, but this will not lead to any direct solutions.

Once you can figure out which parts of the obstacles are visible (and can therefore be used to reflect the bullet), implementing mirroring via a depth-first search would seem straightforward. To find suitable mirror surfaces, the techniques outlined in Nicky Case's Sight & Light might be used: rather than trying out 360 vectors – which might miss openings, and also is wasteful – we launch rays only to the edges of obstacles.


问:
Order of terms in a conditional expression
Consider the following loop (in Swift - but my question is language independent):

```<code>    var index = standardizedTimeSpans.count - 1
    while index >= 0 && timeSpan < standardizedTimeSpans[index] {
        index--
    }
    index++
</code>```

In the above code, the standardizedTimeSpans variable is an array of Doubles and the timeSpan variable is a Double.

The above loop may decrement the value of index down to a maximum of -1. If my conditional expression for the while statement was ordered the other way around (i.e. timeSpan < standardizedTimeSpans[index] && index >= 0), a runtime error would occur with array out of bounds in the event of the index reaching -1.

My question:

Is this code considered "safe"? In other words, is there a risk of a compiler change that doesn't necessarily sequence the evaluation of conditional from left to right? Of course, the alternative is to evaluate the conditions separately and but a break expression in the loop.

答:
I'm not sure about Swift specifically, but in general using the && operator short circuits and ends early if the left side is false. The code after the && will not be run.

Short circuiting is common practice in many languages.


答:
"but my question is language independent"

It is of course language dependent. In any programming language where short circuit behaviour is part of the language definition, the code is "safe". Otherwise it is not.

Fortunately, any serious programming language of the C-based language families I know of has short circuit behaviour "by definition" (and lots of other programming languages, too). I do not know Swift, but since the inventors of that language were professionals, I am pretty sure they care for backwards compatibility. So I would not expect the behaviour to be changed in that language in the future.

Title: Order of terms in a conditional expression

Body:
Consider the following loop (in Swift - but my question is language independent):

```<code>    var index = standardizedTimeSpans.count - 1
    while index >= 0 && timeSpan < standardizedTimeSpans[index] {
        index--
    }
    index++
</code>```

In the above code, the standardizedTimeSpans variable is an array of Doubles and the timeSpan variable is a Double.

The above loop may decrement the value of index down to a maximum of -1. If my conditional expression for the while statement was ordered the other way around (i.e. timeSpan < standardizedTimeSpans[index] && index >= 0), a runtime error would occur with array out of bounds in the event of the index reaching -1.

My question:

Is this code considered "safe"? In other words, is there a risk of a compiler change that doesn't necessarily sequence the evaluation of conditional from left to right? Of course, the alternative is to evaluate the conditions separately and but a break expression in the loop.


答:
Just extending Karl Bielefeldt idea for a 2 walls reflections:

A and B are given (the tanks). You first must list all walls that A can see and a list of all walls B can see. Then you make pairs where the first wall is in the fist list and the second wall is different from the first wall and is in the second list. You need to make this test for all possible pairs of walls (unless you find a way to eliminate candidates). Once you find R and S for a given pair of walls you check

1) if A has direct vision of R

2) if R belongs to the wall1 (the wall is just a segment, no the whole line)

3) if R has direct access to S

4) if S belongs to wall2 (the wall is just a segment, no the whole line)

5) if S has direct access to B.

To find R and S: Since you know wall1 you can determine the line equation tangent to wall1, since R belongs to the line tangent to wall 1, you have a relation between the 2 coordinates of R (ending up with one degree of freedom for R)
Similarly to S (you have a relation between S coordinates since this point belongs to the line tanget to wall2). So now you have 2 degrees of freedom and you must have 2 additional independent equations to determine a solution.
One equation is:

```<code>(AA')/(RA')=(SS')/(RS')
</code>```

the other equation is:

```<code>(BB')/(SB')=(RR')/(SR')
</code>```

notice that in the above equations A,A',B,B' are know or can be calculated directly. R' and S' are function of the coordinates of R and S and the wall equations. I didn't finish the math so I don't know how the equations will look like.

Body:
Just extending Karl Bielefeldt idea for a 2 walls reflections:

A and B are given (the tanks). You first must list all walls that A can see and a list of all walls B can see. Then you make pairs where the first wall is in the fist list and the second wall is different from the first wall and is in the second list. You need to make this test for all possible pairs of walls (unless you find a way to eliminate candidates). Once you find R and S for a given pair of walls you check

1) if A has direct vision of R

2) if R belongs to the wall1 (the wall is just a segment, no the whole line)

3) if R has direct access to S

4) if S belongs to wall2 (the wall is just a segment, no the whole line)

5) if S has direct access to B.

To find R and S: Since you know wall1 you can determine the line equation tangent to wall1, since R belongs to the line tangent to wall 1, you have a relation between the 2 coordinates of R (ending up with one degree of freedom for R)
Similarly to S (you have a relation between S coordinates since this point belongs to the line tanget to wall2). So now you have 2 degrees of freedom and you must have 2 additional independent equations to determine a solution.
One equation is:

(AA')/(RA')=(SS')/(RS')

the other equation is:

(BB')/(SB')=(RR')/(SR')

notice that in the above equations A,A',B,B' are know or can be calculated directly. R' and S' are function of the coordinates of R and S and the wall equations. I didn't finish the math so I don't know how the equations will look like.


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
Ration of hours spent on support issues against development?

What new things will I learn?

How clean is your code-base? How fragmented (branching in repository)?

What's your automated test coverage percentage?

Do you use Lotus notes?

Which source code control system do you use?

Can I use my favourite IDE (Intellij-IDEA for me)?

Do you have continuous integration on the project?

What is your deployment process?

How agile are you?

Both pigs and chickens at the standup?

Who are your customers?

Developer's kit? Dual 19" monitors? Local admin rights?

OwnerDisplayName: WinstonChurchill


答:
my question is language independent

No, it isn't.

You are assuming that

the order of evaluation is well-defined

the order of evaluation is left-to-right

&& is lazy in its right operand

All three of which are language-dependent. For example, in Visual Basic, And is strict in both its operands.


问:
Deploy a website via apt/yum to different environments without rebuilding for each?
I want to setup a continuous integration pipeline for the first time. I have a website that includes a config file that points to MySQL and Redis. I would like to build a package once and then deploy it to test, UAT and live environments.

I don't want to rebuild the package after deploying it to each environment because it could cause inconsistencies between builds but I can't see an alternative because the config file would need to be different depending on which environment it was deployed to (the test server would be using a different database to live or UAT).

Does anyone have any ideas on how this would be possible?

答: You might want to look into tools like chef or puppet, as they are built for this kind of thing (provisioning).  I know chef uses templates and variables in the script to substitute these.  If a framework like this is unwanted you could always use a similar substitution on deploy scheme of your own or alternately expect configuration to be statically located in an externalized directory that is not effected by deploy and baked into an image for that environment or one time setup (scaling drawbacks apply).</p>


问:
How can I show and hide a single field across my web application through a checked value?
Let's say I have a field called "FooName" and I have "FooName" in several places across my web application (ASP.NET MVC4). I have a check box that allows me to turn "FooName" on and off across the application. Currently, I have access to the checked value (I can grab the saved value from the database) but I'm not sure how to show/hide "FooName" text display across the application? </p>

<p>Is there a utility class I can use or make? Should I use a regex to parse all my web pages? What should I do? </p>

答:
You want to have a single class that knows about your FooName current display settings. Your Views should decide to show or not the FooName based on visibility settings provided by your class.

When you build your pages, pass the current true/false visibility
state of your FooName(produced by that class) into viewBag,

Everywhere where you have your FooName rendered have a condition
    that checks the boolean.


问:
What is the time complexity of this program?
An algorithm is given on GeeksForGeeks.com for constructing a Binary Search Tree from its preorder traversal.

They say that the time complexity for the following code is O(n^2). But in my opinion it should be O(nlogn). I'm confident about calculating O() for most algorithms, but here there's a divide and conquer algorithm, which runs as T(n) = T(n/2) + O(n), which I believe should be working in O(nlogn) by the master method?

Can someone please tell how the complexity is O(n^2)?

The idea of the code is :

The first element of preorder traversal is always root. We first construct the root. Then we find the index of first element which is greater than root. Let the index be ‘i’. The values between root and ‘i’ will be part of left subtree, and the values between ‘i+1′ and ‘n-1′ will be part of right subtree. Divide given pre[] at index “i” and recur for left and right sub-trees.

For example in {10, 5, 1, 7, 40, 50}, 10 is the first element, so we make it root. Now we look for the first element greater than 10, we find 40.

```<code>struct node
{
    int data;
    struct node *left;
    struct node *right;
};

// A utility function to create a node
struct node* newNode (int data)
{
    struct node* temp = (struct node *) malloc( sizeof(struct node) );
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}

// A recursive function to construct Full from pre[]. preIndex is used
// to keep track of index in pre[].
struct node* constructTreeUtil (int pre[], int* preIndex,
                            int low, int high, int size)
{
    // Base case
    if (*preIndex >= size || low > high)
        return NULL;

    // The first node in preorder traversal is root. So take the node at
    // preIndex from p re[] and make it root, and increment preIndex
    struct node* root = newNode ( pre[*preIndex] );
    *preIndex = *preIndex + 1;

        // If the current subarry has only one element, no need to recur
    if (low == high)
        return root;

    // Search for the first element greater than root
    int i;
    for ( i = low; i <= high; ++i )
        if ( pre[ i ] > root->data )
            break;

    // Use the index of element found in postorder to divide postorder array in
    // two parts. Left subtree and right subtree
    root->left = constructTreeUtil ( pre, preIndex, *preIndex, i - 1, size );
    root->right = constructTreeUtil ( pre, preIndex, i, high, size );

    return root;
}

// The main function to construct BST from given preorder traversal.
// This function mainly uses constructTreeUtil()
struct node *constructTree (int pre[], int size)
{
int preIndex = 0;
return constructTreeUtil (pre, &preIndex, 0, size - 1, size);
}
</code>```

答: While the stated algorithm is O(n log n) on the average case, it is O(n^2)  in the worst case, i.e. when used to reconstruct a tree in which each node has an empty branch either to its left or right. Such a tree has a depth of n, and therefore the algorithm will recurse n times, each recursion requiring an average of n/2 comparisons to complete.</p>


答:
As pointed out by others before, its definitely better to discuss. This is especially true in case of database changes. Database, being pretty much the lowest layer, means that any changes to it ( both additions but especially modifications) can potentially have the GREATEST impact to the developers on the team.

A formal review process is a MUST (and preferable this has to be done by the data architect / dba  / someone who owns the schema ) but even if that is in place, i would still recommend a discussion with team members about data especially schema changes before hand.

People with a broader technical / domain / application understanding than you might be easily able to point out pitfalls / need / changes to your approach at an earlier stage than a review saving you time and effort (if they are right)

Title: Is it necessary to discuss database changes

Body:
I am working on a project with a team of 4-5 people. Is it necessary to discuss the database changes with the team before implementing?  I am working on the database api's.

Is it better to discuss this or not? In my team are senior people. So can't I make changes myself and implement the change and explain the changes.


问:
Why is Ruby's interpreter so small?
I noticed that the filesize of Ruby's interpreter seems suspiciously small.

I would have expected /bin/dash to be the smallest of all, but is 20x larger than Ruby:

```<code>Interpreter       Bytes
------------  ---------
Node 0.10.32  8,790,152
Python 3.4.0  4,061,272
Bash 4.3.11   1,021,112
gawk 4.0.01     441,512
Dash            121,272
Ruby 1.9.3        6,304
</code>```

I know that, unlike Node/Python, that Ruby binary doesn't launch REPL. Perhaps the interpreter built in a modular way that spreads itself over several files rather than collecting them in one large binary?

(irb binary also suspiciously small:)

```<code>irb 1.9.3           319
</code>```

Also: This is Ubuntu 14.04.1 LTS

答:
This is really hard to answer, because a ton of information is missing:

How did you measure those sizes? Do they include libraries required to run the interpreter? Do they include runtimes?

What Python implementation are you talking about? There are four production-ready implementations of Python in current use (PyPy, IronPython, Jython, CPython), plus Stackless Python, plus a couple of not-production-ready ones (e.g. Pynie).

What Ruby implementation are you talking about? There are six production-ready implementations of Ruby in current use (Rubinius, MagLev, JRuby, MRuby, YARV, plus MRI, which is no longer being developed but is still being used), plus the abandoned MacRuby and IronRuby, plus the in-development Topaz, Cardinal, and many others.

For example, you count this as the entire size of irb:

```<code>#!/usr/bin/env ruby
#
#   irb.rb - interactive ruby
#       $Release Version: 0.9.6 $
#       $Revision$
#       by Keiju ISHITSUKA(keiju@ruby-lang.org)
#

require "irb"

IRB.start(__FILE__)
</code>```

So, you do not include the size of the IRb library, nor the size of the other libraries of the standard library which IRb uses, nor the size of the Ruby core library, nor the size of the Ruby interpreter, nor the size of any libraries the Ruby interpreter uses, nor the size of any runtime services the Ruby interpreter might use, nor the size of any operating system components, kernel systems, hardware drivers, etc. that the interpreter might need to operate. You count only those two lines of code as the entire size of IRb.

Title: Why is Ruby's interpreter so small?

Body:
This is really hard to answer, because a ton of information is missing:

How did you measure those sizes? Do they include libraries required to run the interpreter? Do they include runtimes?

What Python implementation are you talking about? There are four production-ready implementations of Python in current use (PyPy, IronPython, Jython, CPython), plus Stackless Python, plus a couple of not-production-ready ones (e.g. Pynie).

What Ruby implementation are you talking about? There are six production-ready implementations of Ruby in current use (Rubinius, MagLev, JRuby, MRuby, YARV, plus MRI, which is no longer being developed but is still being used), plus the abandoned MacRuby and IronRuby, plus the in-development Topaz, Cardinal, and many others.

For example, you count this as the entire size of irb:

#!/usr/bin/env ruby
#
#   irb.rb - interactive ruby
#       $Release Version: 0.9.6 $
#       $Revision$
#       by Keiju ISHITSUKA(keiju@ruby-lang.org)
#

require "irb"

IRB.start(__FILE__)

So, you do not include the size of the IRb library, nor the size of the other libraries of the standard library which IRb uses, nor the size of the Ruby core library, nor the size of the Ruby interpreter, nor the size of any libraries the Ruby interpreter uses, nor the size of any runtime services the Ruby interpreter might use, nor the size of any operating system components, kernel systems, hardware drivers, etc. that the interpreter might need to operate. You count only those two lines of code as the entire size of IRb.


问:
Maintaining separation of concerns
I'm making my first C# app and I am having a bit of difficulty with separation of concerns. I understand the concept, but I don't know if I'm doing it right. I have this as a quick example to illustrate my question. In an app such as a game, there is a main class that runs the main loop, such as Program or Game. My question is, do I maintain every reference to every instance of a class in this class, and make that the only way in which they interact?

For example, a card game with a player, cards, and a board. Let's say the player wants to put cards on the board, but the Player class only has a List<> of Cards and no idea about the game board. However, the main Game class knows about the players, the cards and the gameboard. Should it be up to the Game class to place the cards on the board, or does it make more sense that, because it is the player's action, it should be within the Player class.

Example:

public class Game{
    private GameBoard gameBoard;
    private Player[] players;

   public Game(){
     gameBoard = new GameBoard(10,10);
     Player player1 = new Player();
     Player player2 = new Player();
     players = {player1, player2};
   }

   // Create method here?
   public void PlayerPlaceCard(int x, int y, int cardIndex){
      gameBoard.grid[1,1] = player1.cards[cardIndex];
   }
}

public class Player {
     public List<Cards> cards = new List<Cards>();

     public Player(){
     }

     // Or place method here?
     public PlaceCard(Card card, int x, int y, GameBoard gameBoard){
     }
}

public class GameBoard{
    public Card[,] grid;

    public GameBoard(int x, int y){
       // Make the game board
    }
}

public class Card{
   public string name;
   public string value;
}
```

To me it makes more sense to have the method in Game, because Game knows about everything. But as I add more code, Game is becoming pretty bloated and I am writing a lot of PlayerDoesThis() functions.

Thanks for any advice

答:
The key here is not just separation of concerns, but also the single responsibility principle. The two are basically different sides of the same coin: when I think SOC I think top-down (I have these concerns, how do I separate them?) while SRP is more bottom-up (I have this object, does it have a single concern? Should it be split? Are its concerns split too much already?).

In your example you have the following entities and their responsibilities:

Game: this is the code that makes the program "go."

GameBoard: maintains the state of the play area.

Card: a single entity on the game board.

Player: performs actions that change the state of the game board.

Once you think about each entity's single responsibility the lines become more clear.

In an app such as a game, there is a main class that runs the main
  loop, such as Program or Game. My question is, do I maintain every
  reference to every instance of a class in this class, and make that
  the only way in which they interact?

There are really two issues here to keep in mind. The first thing to decide is what entities know about other entities? Which entities belong to other entities?

Look at the responsibilities I outlined above. Players perform actions that change the state of the game board. In other words, Players send messages to (call methods on) the game board. Those messages likely involve cards: for example, a player may place a card in its hand on the board, or change the state of an existing card (e.g. turn a card over or move it to a new location).

Clearly, a player must know about the game board which contradicts the assumption you made in your question. Otherwise, the player must send a message to the game, which then relays that message to the game board. Since players perform actions on the game board, players must know about the game board. This increases coupling: instead of the player sending the message directly, now two actors must know how to send that message. The Law of Demeter implies that if an object must act on another object, in this scenario, that other object should be passed in via parameter to reduce coupling.

Next, where do you store what state? The game is the driver here, it must crease all of the objects either directly or via proxy (e.g. a factory or in a constructor that game calls). The logical next question is what objects need which other objects? This is basically what I asked above, but a different way of asking it.

The way I would design it is like this:

Game creates all of the objects required for the game.

Game shuffles the cards and divides them up per whatever game it represents (poker, solitaire, etc).

Game places the cards in their initial locations: maybe some on the game board, others in players' hands.

Game then goes into its main loop representing a turn.

Each turn would look like this:

Game sends a message to (invokes a method on) the current player and provides a reference to the game board.

Player performs whatever internal logic (computer player) or user interaction necessary to determine what play to perform.

Player sends a message to the game board provided to it asking to change the game board state.

The game board decides whether the move is valid or not (it is responsible for maintaining valid game state).

Control returns to the game, which then decides what to do next. Check for win conditions? Draw? Next player? Next turn? Depends on the specific card game being played.

Should it be up to the Game class to place the cards on the board, or
  does it make more sense that, because it is the player's action, it
  should be within the Player class.

Both: Game is responsible for the initial setup, but Player performs actions on the board. GameBoard is responsible for guaranteeing a valid state. For example, in classic Solitaire only the top card on a pile may be face-up.

Back to my original point: you have the right separations of concerns. You identified the proper objects. What tripped you up was figuring out how messages flow through the system and which objects should keep references to other objects. I would design it like this, which is pseudocode:

```<code>class Game {
  main();
}

class GameBoard {
  // Data structures specific to the game being played. There is a
  // lot of hand-waving here to give the general idea without
  // getting bogged down in the implementation.
  Map<Card, Location> cards;

  GameBoard(Map<Card, Location>);

  // Return false if the move is invalid.
  bool flip(Card);
  bool move(Card, Location);
}

class Card {
  // Make Rank and Suit enums.
  Suit suit;
  Rank rank;
  bool faceUp;
}

class Player {
  Set<Card> hand;

  Player(Set<Card>);
  void takeTurn(GameBoard);
}
</code>```

Title: Maintaining separation of concerns

Body:
The key here is not just separation of concerns, but also the single responsibility principle. The two are basically different sides of the same coin: when I think SOC I think top-down (I have these concerns, how do I separate them?) while SRP is more bottom-up (I have this object, does it have a single concern? Should it be split? Are its concerns split too much already?).

In your example you have the following entities and their responsibilities:

Game: this is the code that makes the program "go."

GameBoard: maintains the state of the play area.

Card: a single entity on the game board.

Player: performs actions that change the state of the game board.

Once you think about each entity's single responsibility the lines become more clear.

In an app such as a game, there is a main class that runs the main
  loop, such as Program or Game. My question is, do I maintain every
  reference to every instance of a class in this class, and make that
  the only way in which they interact?

There are really two issues here to keep in mind. The first thing to decide is what entities know about other entities? Which entities belong to other entities?

Look at the responsibilities I outlined above. Players perform actions that change the state of the game board. In other words, Players send messages to (call methods on) the game board. Those messages likely involve cards: for example, a player may place a card in its hand on the board, or change the state of an existing card (e.g. turn a card over or move it to a new location).

Clearly, a player must know about the game board which contradicts the assumption you made in your question. Otherwise, the player must send a message to the game, which then relays that message to the game board. Since players perform actions on the game board, players must know about the game board. This increases coupling: instead of the player sending the message directly, now two actors must know how to send that message. The Law of Demeter implies that if an object must act on another object, in this scenario, that other object should be passed in via parameter to reduce coupling.

Next, where do you store what state? The game is the driver here, it must crease all of the objects either directly or via proxy (e.g. a factory or in a constructor that game calls). The logical next question is what objects need which other objects? This is basically what I asked above, but a different way of asking it.

The way I would design it is like this:

Game creates all of the objects required for the game.

Game shuffles the cards and divides them up per whatever game it represents (poker, solitaire, etc).

Game places the cards in their initial locations: maybe some on the game board, others in players' hands.

Game then goes into its main loop representing a turn.

Each turn would look like this:

Game sends a message to (invokes a method on) the current player and provides a reference to the game board.

Player performs whatever internal logic (computer player) or user interaction necessary to determine what play to perform.

Player sends a message to the game board provided to it asking to change the game board state.

The game board decides whether the move is valid or not (it is responsible for maintaining valid game state).

Control returns to the game, which then decides what to do next. Check for win conditions? Draw? Next player? Next turn? Depends on the specific card game being played.

Should it be up to the Game class to place the cards on the board, or
  does it make more sense that, because it is the player's action, it
  should be within the Player class.

Both: Game is responsible for the initial setup, but Player performs actions on the board. GameBoard is responsible for guaranteeing a valid state. For example, in classic Solitaire only the top card on a pile may be face-up.

Back to my original point: you have the right separations of concerns. You identified the proper objects. What tripped you up was figuring out how messages flow through the system and which objects should keep references to other objects. I would design it like this, which is pseudocode:

class Game {
  main();
}

class GameBoard {
  // Data structures specific to the game being played. There is a
  // lot of hand-waving here to give the general idea without
  // getting bogged down in the implementation.
  Map<Card, Location> cards;

  GameBoard(Map<Card, Location>);

  // Return false if the move is invalid.
  bool flip(Card);
  bool move(Card, Location);
}

class Card {
  // Make Rank and Suit enums.
  Suit suit;
  Rank rank;
  bool faceUp;
}

class Player {
  Set<Card> hand;

  Player(Set<Card>);
  void takeTurn(GameBoard);
}


问:
Quicksort and don't bother?
Especially when writing 'standard' (non-HPC) applications, do you consider what sorting algorithm to pick, or just settle with quicksort (which is what most libraries just call sort)? To some extent it may be profitable in specific situations, but on the other hand proper optimization requires some time to analyse the problem and make benchmarks. </p>

答:
Always call the library routines provided, unless you have very, very good reason not to do so (and you need to document why it is so).

This is because sorting algorithms are hard to get absolutely right.   There was a bug in the Java quicksort with very large datasets, which was identified, fixed and delivered to customers by Sun, so you didn't have to.

Also the default sort in Java 7 has been upgraded to a newer, better sort.  Also for free.

Unless the default sort is provably not good enough for you, stick with it.

Title: Quicksort and don't bother?


问:
What is the difference between multi-label learning and multi-label classification?
The litterature on multi-label learning uses the terms: multi-label learning and multi-label classification. I was wondering what the difference between these terms is, and when to use one over the other??</p>

答:
Both are forms of supervised learning where the classification algorithm should learn from a set of instances/examples.

In multi-class problems each example is restricted to have only one class label.

Multi-label learning is a generalized version in which each instance can belong to multiple classes (e.g. a research paper can belong to both the health and science category).

Binary and multi-class problems can be posed as specific cases of multi-label problem. However, the generality of multi-label problems makes them more difficult than the others.


问:
How to design database to keep list of special members among all members?
I want to design Database which works  as   below explained.

We have some members and they are listed in many categories.

Among members, some have special privileges.

We have Memeber Table

We have Category Table

Member- category relation maintained in separate table

Member- privilege relation maintained in separate table

Now we want to retrieve members for the particular category , this can be achieved by accessing  Member-category table but in my case I also want to know there privilege , to achieve one thing I can do is

Compare The result (query result- member-category) with Member-Privilege Table  and Check whether Member has privilege or not .

THis is seems to be OK in general case but in this case , We want to make sure Member that have privilege must be included in all result , if "Category" linked to privileged Member .

CASE : 1
When I query for members in category with out limit , I get all the members and then I can compare against Privilege table . This is OK
Case 2 : when I query for members in category with LIMIT , I may miss some of the members who have privileges due to limit ( like LIMIT 10 .. etc )
in that case I will not get all privileged members

How to design database so that I always get privileged members from database quires against category

答:
You can't design your database that way, but you can write your queries (or rather, design your application) to handle that. The example with the LIMIT simply cannot be handled on the database because you can't change what LIMIT does fundamentally.

Your example seems weird because a limit bascially means 'give me only X results'. What do you want to do if there are 12 privileged members, 15 'ordinary' members and you LIMIT 10? Return all 12 privileged and no ordinary? Return all priviledged members and 10 ordinary members? This is the kind of decision you have to make in your application and handle everything that way from the application, not the database...

(Failing that, I suppose you could write a stored procedure to handle this and wrap your logic in that. That leaves you with a database-only solution, but still does not prevent anybody from simply querying the data)


问:
Maintainability while adding custom findByX methods to DAOs
I'm in the beginning of a project which I want to have the best testability and maintainability possible. To achieve this, I'm reading a lot about concepts in the DDD area, mainly.

To get you contextualized, suppose the following entities:

User

It's basically a container for Accounts (see below) and configurations;

Account

It's a way for a User to login. Each User may have various accounts, one for each OAuth provider (Facebook, Google, etc);

Session

It's a token that points to a User + expiration date. Each login generates a new Session.

I need to find a User by Account (when I'm logging in) or Session (when I'm already logged in).

However, I'm afraid that I'll be bloating my DAOs with findByX methods - these seem to be the most performant and simple to understand, but they kinda couple the DB structure to some business rule - or am I wrong?

This post says that I should be using a Specification interface, which its implementations should return the right query criteria.

Is there any problem I may face upfront - like bloating my DAOs with find methods, or am I just over concerned with this architecture?

答:
Your findBy methods don't couple you to the database structure, they couple you to business requirements. Personally, I don't mind repositories that have multiple findBy methods, as long as they are clean and neat. For example:

```<code>User findById(string id);
User findByEmail(string email);
User findByUserName(string userName);
</code>```

To me seems like a clean interface. It can get a little big in the long run, but I'm not too concerned about that because the methods are small and easy to read.

On the other hand, compare this:

```<code>IList<User> findByEmailLikeAndNameLike(string email, string name);
IList<User> findByEmailWithStatusAndLastLoginAfter(string email, UserStatus status, DateTime lastLogin);
IList<User> findByEmailAndStatus(string email, UserStatus status);
</code>```

These are very specific methods that are still business requirements but get VERY unwieldy in the long run and duplicate a lot of logic. I'd replace those three methods by a generic findBy that I can pass a specification to.

Body:
Your findBy methods don't couple you to the database structure, they couple you to business requirements. Personally, I don't mind repositories that have multiple findBy methods, as long as they are clean and neat. For example:

User findById(string id);
User findByEmail(string email);
User findByUserName(string userName);

To me seems like a clean interface. It can get a little big in the long run, but I'm not too concerned about that because the methods are small and easy to read.

On the other hand, compare this:

IList<User> findByEmailLikeAndNameLike(string email, string name);
IList<User> findByEmailWithStatusAndLastLoginAfter(string email, UserStatus status, DateTime lastLogin);
IList<User> findByEmailAndStatus(string email, UserStatus status);

These are very specific methods that are still business requirements but get VERY unwieldy in the long run and duplicate a lot of logic. I'd replace those three methods by a generic findBy that I can pass a specification to.


答:
I don't think there will be a good general answer. It really depends on whether the work of other team members will be affected by what you do or not (although I tend to think changes of the database structure will affect other code). If the database design and API is solely your responsibility, then the least you should do is INFORM people of changes that may affect them. If you are not sure about the effects, ASK the team members so you will be able to judge the trade-offs and make the best (re)design decision - the team as a whole will benefit from it.

If there are other people being allowed to make changes to the database or share your responsibility there will be a need to COORDINATE everything. You can call this DISCUSSION, but I don't see anything bad in it, unless your team's way to discuss things is perceived as an unjust judgement/criticism of your work. If this is the case I'd understand why you feel uncomfortable with it. But the way to solve this is not to think about what to discuss and what not, but to change the "how" to discuss and to change the team spirit.


问:
Memory page - virtual or physical and relation to data types allocation?
I'm looking for a understandable definition of memory pages. Please help me clarify the following questions:

Is a "memory page" always related only to a data chunk of virtual memory?

Are physical RAM addresses also split into pages?

How does a definition of a "memory page" as the smallest unit of data for memory management in a virtual memory operating system fit into the fact that it's possible to allocate a chardata type which is usually one byte (compared to 4Kb of usual page size)?

答:
Pages are the chunks of memory that may be swapped between RAM and the hard disk in order to support virtual memory.

Example: Say you have 1 MB pages, 2 MB of physical RAM, and a lot more virtual RAM. You run application A that takes 1 MB. It gets one virtual page of memory, which is mapped to one of the physical pages. Then you run application B that requires 2 MB. Application B's memory will be spread across two virtual pages. When we start executing application B, we either have to move application A's page onto disk so we can have both of B's pages in RAM, or we have to swap between B's two pages constantly as we run it. Hopefully that's enough to get the idea across.

So the direct answers to your questions are:

Yes. A page of physical RAM always corresponds to a page of virtual RAM. Virtual addresses are what your programs actually operate on, so any physical address that did not map to a virtual one would be completely inaccessible to applications (including the OS, I think).

Yes, paging is a mapping of physical memory chunks to virtual memory chunks, so physical addresses are definitely involved.

That phrase is referring only to the OS code that handles the implementation of virtual memory (i.e., the page swapping). It is not referring to the OS code that allocates memory for you.


问:
What does using pointer in Linux kernel imply?
So far I was under the perspective that while working in the kernel code, working with memory implies working with long integers and not pointers because dereferencing pointers shouldn't be done in the kernel code:

A quote on the topic from LDD3:

Although, conceptually, addresses are pointers, memory administration
  is often better accomplished by using an unsigned integer type; the
  kernel treats physical memory like a huge array, and a memory address
  is just an indexinto the array. Furthermore, a pointer is easily
  dereferenced; when dealing directly with memory addresses, you
  almost never want to dereference them in this manner. Using an integer
  type prevents this dereferencing, thus avoiding bugs. Therefore,
  generic memory addresses in the kernel are usually unsigned long ,
  exploiting the fact that pointers and long integers are always the
  same size, at least on all the platforms currently supported by Linux.

However, I see that there are pointers (source)

char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);

And I'm successful at dereferencing them and getting expected results:

```<code>printk(KERN_INFO "%s:%i  %x \n", __FILE__, __LINE__,*hwbuf);
</code>```

Questions:

What memory address is allocated when char *hwbuf s run in
the kernel? When I say "what memory" I mean if the address is an actual physical address in RAM or something else?

Is it sensible that different parts of the kernel act differently on pointer dereferencing given the relationship that code has on MMU initialization? By this I mean early kernel code deals with physical addresses, driver code deals with some form of virtual addresses?

What are the basis for not dereferencing pointers in kernel code?

答:
There's a key difference between managing memory as a resource (when you don't care what's inside and shouldn't even look), and using memory to do something else (when the contents are the whole point).

... memory administration is often better accomplished ...

The quote is talking about managing memory addressing and maps, where you're treating memory as some opaque resource to be managed.

The code you posted isn't managing memory as a resource, it's using some memory to do non-memory-management-related stuff (specifically DMA to an audio device).


问:
ScrumMaster rotation with multiple scrum masters and teams
I'm currently working in a project where we discuss the question whether it is a good idea or not to rotate the scrum masters through all teams.

We have different teams for ONE project. The context where they work in is the same. They only switch teams for a couple of weeks. We hope to benefit from each ScrumMaster as they have new influences on other teams and maybe can resolve problems others couldn't.

In detail we want each scrum master to assist every team for a couple of weeks. I didn't find any literature about that topic, but only about rotating the scrum master role in a team.

Is this is a good/bad idea?

答:
According to Tuckman's Stages of Groupdevelopment you risk that your team drops into the "Storming Phase" again and again. This is not desired to happen too often, because of the lack of performance in this group phase.

You can try the following to address your problem: The moderation of the retrospective does another Scrum Master.


问:
Distributing a proprietary app together with an ASLv2'ed derived work
My proprietary Java app includes a modified version of a 3rd party library distributed under Apache Software License, version 2.0. The 3rd party library doesn't come from the Apache Software Foundation, neither does it include any NOTICE file (mentioned in 4.(d) section of the License).

Do I need to distribute the modified source code? (I assume the answer is no, but just making sure.)

Would a free-form statement like "this product uses 3rd party software licensed under ASL 2.0, license available at http://www.apache.org/licenses/LICENSE-2.0" somewhere in the THIRDPARTYLICENSEREADME.txt file be sufficient?

Do I need to provide any information as per which exact ASLv2'ed software my product uses?

答:
Apache has a pretty good FAQ regarding their license. The relevant points:

No, you do not have to provide the source code.

Not quite. That statement almost covers the "proper attribution" requirement (but see #3), however you also are required to include a copy of the ASLv2 itself.

Bizarrely, I can't find anything on the Apache website to clarify this issue; it looks like the exact criteria for "proper attribution" appear to consist of preserving the NOTICE file and any notices in source files. Personally, I would be very surprised if "proper attribution" of a work did not include specifying what the work is and where it came from.


答:
I've decided the best way to do this will be to delete the config file from the websites config folder.

I will then create a different config file for each environment which will be stored in puppet. Puppet can then add the correct config file into the websites config folder on provision depending on which environment it is running on.

Title: Deploy a website via apt/yum to different environments without rebuilding for each?

Body:
I want to setup a continuous integration pipeline for the first time. I have a website that includes a config file that points to MySQL and Redis. I would like to build a package once and then deploy it to test, UAT and live environments.

I don't want to rebuild the package after deploying it to each environment because it could cause inconsistencies between builds but I can't see an alternative because the config file would need to be different depending on which environment it was deployed to (the test server would be using a different database to live or UAT).

Does anyone have any ideas on how this would be possible?


答:
Is a "memory page" always related only to a data chunk of virtual memory?

In some sense. The kernel has pages internally used for DMA, I/O buffering, block and inode cacheing, etc. These are all physical memory pages, but they're not visible as such to any user process unless they're mmapped.

Are physical RAM addresses also split into pages?

Yes - the two have to be equivalent for paging to work sanely

[paraphrase] is a page really the smallest unit if you can allocate a char

A page is the smallest unit the kernel VM system deals in. User processes request memory from the kernel in whole pages.

Your userspace process will then have an internal mechanism for managing objects allocated inside these pages.

Note that even if you think you allocated one char, you didn't - the allocator will add some overhead to track the allocated block.

Note also that this discussion about sub-page allocators also applies inside the kernel (in the parts that are using, rather than managing, memory).

The reasons the kernel doesn't deal in smaller units are:

they're inefficient for pagefile purposes (anything smaller than a disk block is going to be wasteful in practice), and

each allocation incurs some fixed management overhead - the smaller the block, the more memory you need to reserve for tracking lots of little objects.

Your 1-char allocation example likely has 4-8 bytes of management overhead; if you're allocating lots of these, perhaps only 1/9th of your memory is actually useful (equivalently, your memory use just increased by a factor of 9 for a given amount of data). The same 8-bytes for a 4Kb page represent a pretty low overhead.

Title: Memory page - virtual or physical and relation to data types allocation?

Body:
I'm looking for a understandable definition of memory pages. Please help me clarify the following questions:

Is a "memory page" always related only to a data chunk of virtual memory?

Are physical RAM addresses also split into pages?

How does a definition of a "memory page" as the smallest unit of data for memory management in a virtual memory operating system fit into the fact that it's possible to allocate a chardata type which is usually one byte (compared to 4Kb of usual page size)?


问:
Best way to consume REST service within Servlet on same server?
I'm builiding a web app and I'm implementing a RESTful API to expose the server to all sort of clients.

On the web client I want to have both server rendering and client rendering. The majority of the layout will be server rendering and changes/updates will be through javascript.

In order to serve the HTML from the server I need to consume the REST API, so I was thinking on putting the logic on servlets which will interact with the REST API and then print the result using JSP.

What I would like to know is:

What is the best way to do consume the REST services in the servlets? I mean they are on the same server so should I still implement a REST client on the servlets?

Won't that create too many http requests? Client -> Servlet -> REST API, isn't there a way to do it in a more direct way?

答:
You have 2 options :

Consuming the REST API using AJAX requests. In this case, your web client will return to the web browser a "static" page, that will retrieve all the needed data using AJAX requests to the REST API. Using this approach, you will transport the main processing in the client side (client meaning the web browser of end users). For an easier implementation of AJAX requests and related concepts, such as client-side validation and transformation of data, you can leverage various JS frameworks (such as jQuery, Angular JS etc).

Disadvantages: processing load in client instead of server might degrade application's performance, security issues in client in case of bad design

Consuming the REST API using back-end requests. In this case, you will make the necessary data loading using the REST API from back-end calls. After you have loaded necessary data and dynamically generated the whole page, you will return it to the web browser. In this case, the Javascript used will be minimal and only used for animations (and not data loading). There are various libraries-frameworks that will make your job easier for creating the API calls and consuming the responses. Some of them are JAX-RS client, Unirest, Resty

In order to avoid the architectural pattern Client -> Servlet -> REST API, you could design your application in such a way, that the service is returning various forms of responses (JSON-REST, HTML etc.). In this way, after loading the data, depending on the type of the client, you could choose the format of the response and use the suitable service.


问:
What is an example of a good SMART objective for a programmer?
Following on from this question, I wondered if folk might be able to suggest some samples of what might be considered a "good" objective in a periodic review cycle for a programmer?

Let's define SMART from the most popular definitions in the Wikipedia entry:

Specific

Measurable

Attainable

Relevant

Time-bound

答:
Implementation of X module within

  +-10% of the estimated time (40 hours) within 5% range of 10 defects/KLOC

It is specific -  as long as "Implementation" has an accepted meaning across the team.

Usually it refers to "Coding + Unit Testing"

It is Measurable - you can measure defects, effort and time

Achievable - As long as estimate is based on previous actuals from similar modules / expert judgement, it should be achievable

Relevant - Its specifically talking about a particular module

Time Bound - I think there could be an end - date added to it to make it explicit.

However usually in projects where people multi-task on different things at the same time, that's a lot more difficult to do. But as long as the tasks are prioritized correctly, it shouldn't really be an issue not having an end date in it


答: What I usually see is a simple abstraction where Service classes return the data needed in Object form and Rest controller classes render to JSON or whatever you are marshalling to.  This would allow you to just reuse the Services for your server side needs and not call back into yourself.</p>

Title: Best way to consume REST service within Servlet on same server?

Body:
I'm builiding a web app and I'm implementing a RESTful API to expose the server to all sort of clients.

On the web client I want to have both server rendering and client rendering. The majority of the layout will be server rendering and changes/updates will be through javascript.

In order to serve the HTML from the server I need to consume the REST API, so I was thinking on putting the logic on servlets which will interact with the REST API and then print the result using JSP.

What I would like to know is:

What is the best way to do consume the REST services in the servlets? I mean they are on the same server so should I still implement a REST client on the servlets?

Won't that create too many http requests? Client -> Servlet -> REST API, isn't there a way to do it in a more direct way?


问:
Designing the model layer to be serializable
I am creating simple desktop application in javaFX 8 and I would like to be able to save the state of the model and load it next time the application starts. Therefore I am implementing the Serializable interface with all my custom model classes. First they were pure POJOs.

But in javaFX application when I want to bind the model to UI, I need to have for example StringProperty variables instead of simple String.

I realized that these property variables does not implement the interface for serialization.
I am thinking about

separate the clean POJO-s and than create wrappers with ObesrvableProperty variables for the UI

duplicate the variables in the same class and somehow mark the property variables as transient for serialization

adopt other/manual serialization technique

What is the best/general practice here?

答:
One common approach is to design your application model in a way that is entirely independent of your user interface framework, and then implement an adaptor between the two. This allows your application to treat its UI as a plugin, which can be beneficial (both for testing and for later addition of features that may benefit from a different UI, e.g. mobile). You can also do the same thing for persistence, and any other dependencies you have.

This approach has been given various names (e.g. "clean architecture" by Robert Martin, "hexagonal architecture" by Alistair Cockburn).

The downside is, of course, increased complexity.