问:
How to keep unit tests independent?
I've read it at many places that unit tests should be independent. In my case I have a class that does data transformation. These steps must be done sequentially, otherwise they don't make sense. For example,

```<code>load_data
parse_float
label
normalize
add_bias
save_data
</code>```

For example, I cannot normalize the data before I label it, because then values have changed and I don't have access to the original values of my data anymore. Or I cannot save the data before I actually loaded it.

So my test class looks something like this

```<code>class TestTransform(Testcase):
  def setUp(self):
    self.trans = Transform()

  def test_main():
    self.load()
    self.parse_float()
    self.label()

  def load(self):
    self.trans.load()
    assert ....

  def parse_float(self):
    self.trans.parse_float()
    assert ....
</code>```

In this case, my unit tests clearly depend on each other, but I can't see how else I could do it. As an alternative, I could write something like this

```<code>  def test_normalize(self):
    # setup
    self.trans.load()
    self.trans.parse_float()
    self.trans.label()
    # test begins here
    self.trans.normalize()
    assert ....
</code>```

But in this case, I run a lot of code multiple times, which is inefficient and makes my tests run a lot longer.

So does the best practice of keeping unittests independent apply in this case or not?

答:
You're not doing unit tests, but integration tests.

A unit test is ensuring that a single component of a system works as expected.

An integration test combines several components and verifies that, together, they still work normally.

True, you cannot normalize the data before you label it. But when you test data normalization, you should test it one a labeled data. Or data which was specifically not labeled, on purpose, to ensure that normalization successfully fails when the data is not labeled (or gracefully handles this situation).

In order to do that, you may use mocking. Mocking is the technique where you replace one part of a system by something which only provides fictive results. In your normalization tests, you may have a mock which provides labeled data, another mock which provides data which is labeled, but incorrectly, and another mock which doesn't label anything.

Those three mocks will serve you to unit test your normalization independently of the actual labeling process, without even carrying if it is already implemented or not, nor if it is working as expected.

This way, you can unit test the part which saves data and then develop it, then start to unit test labeling and implement it, and finally unit test normalization and write the corresponding code.

Once done, you will then use your actual integration tests to see if the whole system is working.

Example

I don't really understand the process from your question (is it domain-specific?), so I invent some easy to understand illustration. Let's imagine an app which loads weather data (temperature, precipitation risk, etc.), from several web services, compares it using specific rules, makes predicates from statistical data and stores the result in a database.

I can't compare data without loading it, and I can't make predicates from statistical data with no data whatsoever. But I want to implement statistical analysis first, because I'm unsure how to do it nor what my customer expects as a result, so I do this part first to increase the chance to finish the project on time.

For this, I can create a bunch of mocks based on the specification. Those mocks will provide me with the data I specify in the unit tests themselves. A real-world, untested app would look like this:

```<code>data = [];
foreach (provider in weatherProviders)
{
    data.push(provider.getTransformedData());
}

todayOverall = compareWeatherData(data); // We want to implement this first.
pastDaysOverall = loadHistoricalData();
weather = predictWeather(todayOverall, pastDaysOverall);
</code>```

An app which uses mocks will look like that:

```<code>data = [];
foreach (provider in weatherProviders)
{
    data.push(provider.getTransformedData());
}

var dataAccess = new SQLiteDatabaseAccess();
todayOverall = compareWeatherData(new BasicCompare(), data);
pastDaysOverall = loadHistoricalData(new HistoricalLoader(dataAccess));
weather = predictWeather(new WeatherOracle(dataAccess), todayOverall, pastDaysOverall);
</code>```

As you see, compareWeatherData takes an additional argument, which does the actual work, loadHistoricalData needs an object which actually loads the data from a data source, and which, itself, requires a data provider to be specified, etc. This have several benefits compared to the previous piece of code:

If tomorrow, the customer tells me that my app has to support both SQLite and MySQL, I don't care: I'll do two providers instead of one, and specify the first or the second one depending on the application configuration. In the same way, if the weather oracle of the first version is really bad, I can simply work on a better oracle, then easily switch them.

When unit testing the different parts, I can replace any of them by a mock. For example, I can feed WeatherOracle with FictionalDataMock: DataAccess instead of SQLiteDatabaseAccess: DataAccess, and in FictionalDataMock, specify the values manually.

When it finally comes to unit testing the todayOverall = compareWeatherData(new BasicCompare(), data); line, I have enough power to do it without even thinking about any other parts of the system:

```<code>/**
 * Ensures that the comparison handles correctly the case where one of the data providers
 * was on crack and supplied us with a temperature below Absolute Zero (-459.67°F).
 */
public test minimumTemperatureFailure()
{
    dataSet1 = new TransformedDataMock(sky.snow, fromFahrenheit(23));
    dataSet2 = new TransformedDataMock(sky.heavySnow, fromFahrenheit(-480)); // Too cold!

    data = [ dataSet1, dataSet2 ];

    actual = new BasicCompare().compare(data);

    // The temperature below Absolute Zero should be ignored.
    assert.areEqual(dataSet1.temperature, actual.averageTemperature);

    // Since the second data provider was doing drugs, other data from it shouldn't be
    // trusted neither.
    assert.areEqual(dataSet1.sky, actual.mostRealisticSky);
}
</code>```

Title: How to keep unit tests independent?

Body:
You're not doing unit tests, but integration tests.

A unit test is ensuring that a single component of a system works as expected.

An integration test combines several components and verifies that, together, they still work normally.

True, you cannot normalize the data before you label it. But when you test data normalization, you should test it one a labeled data. Or data which was specifically not labeled, on purpose, to ensure that normalization successfully fails when the data is not labeled (or gracefully handles this situation).

In order to do that, you may use mocking. Mocking is the technique where you replace one part of a system by something which only provides fictive results. In your normalization tests, you may have a mock which provides labeled data, another mock which provides data which is labeled, but incorrectly, and another mock which doesn't label anything.

Those three mocks will serve you to unit test your normalization independently of the actual labeling process, without even carrying if it is already implemented or not, nor if it is working as expected.

This way, you can unit test the part which saves data and then develop it, then start to unit test labeling and implement it, and finally unit test normalization and write the corresponding code.

Once done, you will then use your actual integration tests to see if the whole system is working.

Example

I don't really understand the process from your question (is it domain-specific?), so I invent some easy to understand illustration. Let's imagine an app which loads weather data (temperature, precipitation risk, etc.), from several web services, compares it using specific rules, makes predicates from statistical data and stores the result in a database.

I can't compare data without loading it, and I can't make predicates from statistical data with no data whatsoever. But I want to implement statistical analysis first, because I'm unsure how to do it nor what my customer expects as a result, so I do this part first to increase the chance to finish the project on time.

For this, I can create a bunch of mocks based on the specification. Those mocks will provide me with the data I specify in the unit tests themselves. A real-world, untested app would look like this:

data = [];
foreach (provider in weatherProviders)
{
    data.push(provider.getTransformedData());
}

todayOverall = compareWeatherData(data); // We want to implement this first.
pastDaysOverall = loadHistoricalData();
weather = predictWeather(todayOverall, pastDaysOverall);

An app which uses mocks will look like that:

data = [];
foreach (provider in weatherProviders)
{
    data.push(provider.getTransformedData());
}

var dataAccess = new SQLiteDatabaseAccess();
todayOverall = compareWeatherData(new BasicCompare(), data);
pastDaysOverall = loadHistoricalData(new HistoricalLoader(dataAccess));
weather = predictWeather(new WeatherOracle(dataAccess), todayOverall, pastDaysOverall);

As you see, compareWeatherData takes an additional argument, which does the actual work, loadHistoricalData needs an object which actually loads the data from a data source, and which, itself, requires a data provider to be specified, etc. This have several benefits compared to the previous piece of code:

If tomorrow, the customer tells me that my app has to support both SQLite and MySQL, I don't care: I'll do two providers instead of one, and specify the first or the second one depending on the application configuration. In the same way, if the weather oracle of the first version is really bad, I can simply work on a better oracle, then easily switch them.

When unit testing the different parts, I can replace any of them by a mock. For example, I can feed WeatherOracle with FictionalDataMock: DataAccess instead of SQLiteDatabaseAccess: DataAccess, and in FictionalDataMock, specify the values manually.

When it finally comes to unit testing the todayOverall = compareWeatherData(new BasicCompare(), data); line, I have enough power to do it without even thinking about any other parts of the system:

/**
 * Ensures that the comparison handles correctly the case where one of the data providers
 * was on crack and supplied us with a temperature below Absolute Zero (-459.67°F).
 */
public test minimumTemperatureFailure()
{
    dataSet1 = new TransformedDataMock(sky.snow, fromFahrenheit(23));
    dataSet2 = new TransformedDataMock(sky.heavySnow, fromFahrenheit(-480)); // Too cold!

    data = [ dataSet1, dataSet2 ];

    actual = new BasicCompare().compare(data);

    // The temperature below Absolute Zero should be ignored.
    assert.areEqual(dataSet1.temperature, actual.averageTemperature);

    // Since the second data provider was doing drugs, other data from it shouldn't be
    // trusted neither.
    assert.areEqual(dataSet1.sky, actual.mostRealisticSky);
}


问:
What are the main advantages and disadvantages of LL and LR parsing?
When building a parser to a programming language what I earn and what I lost choosing one or the other?</p>

答:
I'll contrast LL and LR parsing for a number of criteria:

Complexity

LL wins here, hands down. You can easily hand-write an LL parser. In fact, this is commonly done: the Microsoft C# compiler is a hand-written recursive descent parser (source here, look for a comment made by Patrick Kristiansen - the blog post is very interesting as well).

LR parsing uses a rather counter-intuitive method to parse a text. It works, but it took me some time to wrap my head around how it works exactly. Writing such a parser by hand is therefore hard: you'd be more or less implementing an LR parser-generator.

Generality

LR wins here: all LL languages are LR languages, but there are more LR languages than LL languages (a language is an LL language if it can be parsed with an LL parser, and a language is an LR language if it can be parsed with an LR parser).

LL has quite a few nuisances that will bother you when implementing just about any programming language. See here for an overview.

There are unambiguous languages that are not LR languages, but those are pretty rare. You almost never encounter such languages. However, LALR does have a few issues.

LALR is more or less a hack for LR parsers to make the tables smaller. The tables for an LR parser can typically grow enormous. LALR parsers give up the ability to parse all LR languages in exchange for smaller tables. Most LR parsers actually use LALR (not secretively though, you can usually find exactly what it implements).

LALR can complain about shift-reduce and reduce-reduce conflicts. This is caused by the table hack: it 'folds' similar entries together, which works because most entries are empty, but when they are not empty it generates a conflict. These kinds of errors are not natural, hard to understand and the fixes are usually fairly weird.

Compiler errors and error recovery

LL wins here. In an LL parse, it's usually pretty easy to emit useful compiler errors, in particular in hand-written parsers. You know what you're expecting next, so if it doesn't turn up, you usually know what went wrong and what the most sensible error would be.

Also, in LL parsing, error recovery is a lot easier. If an input doesn't parse correctly, you can try to skip ahead a bit and figure out if the rest of the input does parse correctly. If for instance some programming statement is malformed, you can skip ahead and parse the next statement, so you can catch more than one error.

Using an LR parser this is a lot more difficult. You can try to augment your grammar so that it accepts erroneous input and prints errors in the areas where things went wrong, but this is usually pretty hard to do. The chance you end up with a non-LR (or non-LALR) grammar also goes up.

Speed

Speed is not really an issue with the manner in which you parse your input (LL or LR), but rather the quality of the resulting code and the use of tables (you can use tables for both LL and LR). LL and LR are therefore comparable in this respect.

Links

Here is a link to a site also contrasting LL and LR. Look for the section near the bottom.

Here you can find a conversation regarding the differences. It's not a bad idea to critically look at the opinions voiced there though, there is a bit of a holy war going on there.

For more info, here and here are two of my own posts about parsers, though they are not strictly about the contrast between LL and LR.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Best way to create draw with limitation
I'm writing a program to automatically make the draw for a competition. There are four objects: Debate Judge School Team Each Debate has two teams and a judge. Each team participates in three debates.

With this, there are the following rules: 1) A team cannot face someone from their same school 2) A team cannot face another team from the same other school (As in if they play a team from a school once, they cannot play again against someone from that school) 3) A judge cannot come from the same school as a team they are judging.

So how would I create a draw? A draw looks like a table (I just need the data, but when you write it it looks like this) with a column for judges and then three other columns for each round of debates (the three debates each team participates in).

Right now I'm basically choosing a random team, finding an opposing team that hasn't played the school of the first team before and doesn't come from the same school and then finding a judge from neither of those schools. Then I do the same thing until I have all the debates. The problem is the program sometimes gets into ruts where there is no other team/judge that fits.  A human would then shift things around and try to find a way to move other judges around to figure it out, but how can I do that with a program. If I run the program again it figures it out just because it's random which teams it chooses for what. Basically, I'm wondering what the best solution is to the problem?

答:
As it's Saturday, and my thinker is currently broken, I'll take the lazy way out. Count iterations without a match found. If they get above an arbitrary number, dump your result set and start over.

It's a kludge fix, but it will address the never-ending rut issue.

ContentLicense: CC BY-SA 3.0

Title: Best way to create draw with limitation


问:
Repetitive Drawing in Javascript & Canvas
Creating an HTML5 page using canvas and javascript to draw a set number of musical staves on the page, spaced a pre-determined amount in between.

What I have is re-drawn on top of the canvas 10 times, and what I really need is something that's spaced out apart every time the loop is drawn.

I tried to create  a JSFiddle, but it doesn't draw anything (which I'm sure is user-error), so here's the js file:

```<code>window.onload = function(){

var canvas = document.getElementById('sheetmusic');
    c = canvas.getContext('2d');

c.fillStyle = 'white';
c.fillRect(0,0, canvas.width, canvas.height);

//  Draw staves
for (var i=0; i<10; i++){
    c.strokeStyle = 'black';
    c.beginPath();
    c.moveTo(0,10);
    c.lineTo(canvas.width,10);
    c.stroke();
    c.moveTo(0,20);
    c.lineTo(canvas.width,20);
    c.stroke();
    c.moveTo(0,30);
    c.lineTo(canvas.width,30);
    c.stroke();
    c.moveTo(0,40);
    c.lineTo(canvas.width,40);
    c.stroke();
    c.moveTo(0,50);
    c.lineTo(canvas.width,50);
    c.stroke();
    // staff whitespace
    c.fillStyle = 'white';
    c.fillRect(0,52, canvas.width, 50);
    }
};
</code>```

I'm just not certain how to append i from my loop into the height attribute of my stroke.

答:
Figured out what I was going for.  Wanted to use loops to make the code as concise as possible, but ran into a few problems until I achieved this.

```<code>window.onload = draw;

function draw() {
    var canvas = document.getElementById('sheetmusic');
    var c = canvas.getContext('2d');
    var whitespace = 0;
    var ycoordinate = 10;

    //draw the staves 'x' number of times requested
    for (var x = 1; x <= 10; x++) {

        // draw the staff
        for (var i = 1; i <= 5; i++){
            c.strokeStyle = 'black';
            c.moveTo(0,ycoordinate);
            c.lineTo(canvas.width,ycoordinate);
            c.stroke();
            ycoordinate = ycoordinate + 10;
        }

        //draw white space beneath each staff
        c.fillStyle = 'white';
        c.fillRect(0,whitespace + 52,canvas.width,52);
        whitespace = whitespace + 100;
        ycoordinate = ycoordinate + 30;

    }
}
</code>```

Now I can set x to repeat as many times as I want, in order to draw music staves in javascript, with the correct amount of adjustable whitespace in between them.

Had to go back and look up some more information on loops, as suggested by tgkprog.  Thanks!

Demo'able JS Fiddle at http://jsfiddle.net/ShawnCodes/K8j7u/1/

Body:
Figured out what I was going for.  Wanted to use loops to make the code as concise as possible, but ran into a few problems until I achieved this.

window.onload = draw;

function draw() {
    var canvas = document.getElementById('sheetmusic');
    var c = canvas.getContext('2d');
    var whitespace = 0;
    var ycoordinate = 10;

    //draw the staves 'x' number of times requested
    for (var x = 1; x <= 10; x++) {

        // draw the staff
        for (var i = 1; i <= 5; i++){
            c.strokeStyle = 'black';
            c.moveTo(0,ycoordinate);
            c.lineTo(canvas.width,ycoordinate);
            c.stroke();
            ycoordinate = ycoordinate + 10;
        }

        //draw white space beneath each staff
        c.fillStyle = 'white';
        c.fillRect(0,whitespace + 52,canvas.width,52);
        whitespace = whitespace + 100;
        ycoordinate = ycoordinate + 30;

    }
}

Now I can set x to repeat as many times as I want, in order to draw music staves in javascript, with the correct amount of adjustable whitespace in between them.

Had to go back and look up some more information on loops, as suggested by tgkprog.  Thanks!

Demo'able JS Fiddle at http://jsfiddle.net/ShawnCodes/K8j7u/1/


答:
I think you're close.  The trick is to start with the first team ('first' can be defined any way you want, including random) and make a list of all the available other teams, in some order.  Pair up the first team with the first of the available other teams.  Now look make a list of the available judges (again in some order), and pick the first available judge.

Repeat the above for the next set.  At some point you won't have any second team to pick, or you'll be out of judges.  At that point you need to "backtrack" - unwind one of your previous decisions and move on to the next.

For example, when you select team A, your choices are (B and C).  You select B and move on.  Later you discover that B was an unfortunate choice, so you revisit that choice and select C instead.

The idea is called Depth First Search.  It's a lot easier than the Wikipedia page makes it out to be.

I'd handle your challenge by assigning each team a random number then use that number for sorting them whenever I'm looking for the "next available" team or judge.  That way you'd get your random pairings and a way to backtrack and unwind.  (The goal is to correctly select the correct teams and judges in such an order that you get all the pairings you need, subject to the contest rules constraints).

The only time you use Random() is when you're setting up the data.  The algorithm shouldn't use it.

Title: Best way to create draw with limitation

Body:
I'm writing a program to automatically make the draw for a competition. There are four objects: Debate Judge School Team Each Debate has two teams and a judge. Each team participates in three debates.

With this, there are the following rules: 1) A team cannot face someone from their same school 2) A team cannot face another team from the same other school (As in if they play a team from a school once, they cannot play again against someone from that school) 3) A judge cannot come from the same school as a team they are judging.

So how would I create a draw? A draw looks like a table (I just need the data, but when you write it it looks like this) with a column for judges and then three other columns for each round of debates (the three debates each team participates in).

Right now I'm basically choosing a random team, finding an opposing team that hasn't played the school of the first team before and doesn't come from the same school and then finding a judge from neither of those schools. Then I do the same thing until I have all the debates. The problem is the program sometimes gets into ruts where there is no other team/judge that fits.  A human would then shift things around and try to find a way to move other judges around to figure it out, but how can I do that with a program. If I run the program again it figures it out just because it's random which teams it chooses for what. Basically, I'm wondering what the best solution is to the problem?


答:
Sounds like a good candidate for using the knapsack problem algorithm.  You may want one of the multi-variant extensions (also listed in that Wikipedia reference), but ultimately it's the same algorithm.  You could have a look at one of my recent answers for a very similar problem domain.

The bad news is that this is an NP-hard problem.  Loose translation: you'll never find a perfect algorithm to solve the issue.  However, if you're willing to use some "cheats" then you can generate an algorithm that will reliably complete.  The cheats aren't that big of a deal in this case; you just need to constrain the starting parameters in order to allow the algorithm to converge upon a solution.  And it's not like you need true randomness for setting up the draw, you just need to make sure the participants are able to compete against as wide of a range of other participants as reasonably possible.

Title: Best way to create draw with limitation


问:
Find how the data has been processed
Well this has been a question I have puzzled about for a long time:

Suppose I have a dictionary of input:output like:

This

```<code>{2: 6,
 5: 15,
 20: 60,
 26: 78,
 ...
 982: 2946,
 997: 2991}
</code>```

where output = input*3.

or This

```<code>{0: 5,
 3: 8,
 17: 22,
 19: 24,
 ...
 991: 996,
 996: 1001}
</code>```

where output = input+5

or something else.

In short where there is a definite relation between input and output.

How can a program find the relation between the input and output, such that, given another input, the output can be calculated??

Is it possible to do the same with more complex calculations like output = 5*((input*5)+3)

答:
It seems like the problem is to find the "simplest" function that fits the data.  For example, given 1->2, 2->4, 3->8, 4->16 you could fit a cubic polynomial, but the simplest answer is f(x) = 2^x.  This problem can be solved by simply trying all possible functions starting with the simplest: f(x) = 0 and moving to more complex functions.  At worst you will find a polynomial function of degree n-1.  However, such a brute force search could take a while, and the correct answer is not clear.  Suppose you have:

f(1) = 2, f(2) = 6, f(3) = 11.  Is a quadratic polynomial more or less complex than 2^x + x ?

Title: Find how the data has been processed


问:
How do I tell a user that bps means bits per second or bytes per second?
I'm writing an application that deals with the network and the hard drive. For the network portion, the application measures in bits per second, while the disk portion measures in bytes per second. This becomes an issue as they both are abbreviated b/s or bps everywhere I've seen. How could I inform the user that one means bits per second, while the other means bytes per second?

If I were writing a specification, I could just add a footnote, but as this is an application, I can't do that.

So, my question is How do I tell a user that one means bits per second while the other means bytes per second and how would I style the lettering (i.e. megabinarybytes is MiB, but what is megabinarybits)?

答: The abbreviations for bits and bytes are differentiated by their case:  lower case (b) means bits and upper case (B) means bytes.


答:
If you are writing the entire application yourself, why not just normalize all the messages to use the same unit?

The engineer in me would also ask if that is useful information at all to be presenting to the user? If they don't know what it means, then what are they going to use it for?

Title: How do I tell a user that bps means bits per second or bytes per second?

Body:
I'm writing an application that deals with the network and the hard drive. For the network portion, the application measures in bits per second, while the disk portion measures in bytes per second. This becomes an issue as they both are abbreviated b/s or bps everywhere I've seen. How could I inform the user that one means bits per second, while the other means bytes per second?

If I were writing a specification, I could just add a footnote, but as this is an application, I can't do that.

So, my question is How do I tell a user that one means bits per second while the other means bytes per second and how would I style the lettering (i.e. megabinarybytes is MiB, but what is megabinarybits)?


答:
How do I tell a user that one means bits per second while the other
  means bytes per second and how would I style the lettering

Seems like this is one of those things that you get to decide as the designer of the program. There are lots of options, including but not limited to:

spell it out: Eliminate the ambiguity by simply writing "bytes/sec" or "bits/sec".

tooltips: User hovers the cursor over any of the places in the program where an abbreviation for a measurement is used, and a tooltip appears displaying the unit name spelled out.

help: Describe the units of measure in online help.

choose one: Pick one unit and use it everywhere.

user chooses: Why can't the user click on any measurement in the program and get a choice of what units to use?


问:
How does one make a cluster capable program?
In cluster computing, there seems to be two options: task redirection and task splitting. Task redirection seems easy enough, you just have the master dispatch the small calls to other nodes in the cluster for processing (eg webserver clusters (I think)). Task splitting however seems wildly more complex. Since I don't think you can have two threads of the same program run on different machines, meaning you have to split up the work.

How though does one split up the work? I can see some stuff like rendering or video encoding just because you can tell each node to work on a different part of the video, but when you want to do things like calculate the 5 trillionth digit of pie, how would you split that up? Or even in science where you need to simulate weather or other resource intensive tasks?

In short, how do you split up tasks that aren't really designed for splitting up?

答:
Computer scientists had been dreaming of the moment in which parallel processing could be made a reality, and then it came as a surprise to find out that it's really not so advantageous or even possible to apply parallel processing to many problems.  Apart from the fact that some problems must be solved in a linear fashion, there's also the fact that there are diminishing returns, which is to say, the amount of work put into simply dividing up the work and distributing it and then making sense of work done by the cluster afterwards begins to actually become more trouble than its worth.

Unfortunately this threshold depends mostly on the problem and therefore makes it difficult to know when using clusters would actually make calculations faster which leads into some very complicated algorithms.

Back to your original question, it really depends on what you want to accomplish as to whether or not you can do it.  Though it should be said that if we programmers knew a way to build a program to analyze a problem, we'd all be out of a job.


问:
What are the drawbacks of immutable types?
I see myself using more and more immutable types when the instances of the class are not expected to be changed. It requires more work (see example below), but makes it easier to use the types in a multithreaded environment.

At the same time, I rarely see immutable types in other applications, even when mutability wouldn't benefit anyone.

Question: Why immutable types are so rarely used in other applications?

Is this because it's longer to write code for an immutable type,

Or am I missing something and there are some important drawbacks when using immutable types?

Example from real life

Let's say you get Weather from a RESTful API like that:

public Weather FindWeather(string city)
{
    // TODO: Load the JSON response from the RESTful API and translate it into an instance
    // of the Weather class.
}
```

<p>What we would generally see is (new lines and comments removed to shorten the code):</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class Weather
{
    public City CorrespondingCity { get; set; }
    public SkyState Sky { get; set; } // Example: SkyState.Clouds, SkyState.HeavySnow, etc.
    public int PrecipitationRisk { get; set; }
    public int Temperature { get; set; }
}
</code>```

On the other hand, I would write it this way, given that getting a Weather from the API, then modifying it would be weird: changing Temperature or Sky wouldn't change the weather in real world, and changing CorrespondingCity doesn't make sense neither.

public sealed class Weather
{
    private readonly City correspondingCity;
    private readonly SkyState sky;
    private readonly int precipitationRisk;
    private readonly int temperature;

    public Weather(City correspondingCity, SkyState sky, int precipitationRisk,
        int temperature)
    {
        this.correspondingCity = correspondingCity;
        this.sky = sky;
        this.precipitationRisk = precipitationRisk;
        this.temperature = temperature;
    }

    public City CorrespondingCity { get { return this.correspondingCity; } }
    public SkyState Sky { get { return this.sky; } }
    public int PrecipitationRisk { get { return this.precipitationRisk; } }
    public int Temperature { get { return this.temperature; } }
}
```

答:
I program in C# and Objective-C. I really like immutable typing, but in real life I've been always forced to limit its usage, mainly for data types, for the following reasons:

Implementation effort comparing to mutable types. With an immutable type, you would need to have a constructor requiring arguments for all properties. Your example is a good one. Try imagining that you have 10 classes, each having 5-10 properties. To make things easier, you might need to have a builder class to construct or create modified immutable instances in a manner similar to StringBuilder or UriBuilder in C#, or WeatherBuilder in your case. This is the main reason for me as many classes I design are  not worth such an effort.

Consumer usability. An immutable type is more difficult to use in comparison to mutable type. Instantiation requires initialising all values. Immutability also means that we cannot pass the instance to a method to modify its value without using a builder, and if we need to have a builder then the drawback is in my (1).

Compatibility with the language's framework. Many of the data frameworks require mutable types and default constructors to operate. For example, you cannot do nested LINQ-to-SQL query with immutable types, and you cannot bind properties to be edited in editors  such as Windows Forms' TextBox.

In short, immutability is good for objects that behave like values, or only have a few properties. Before making anything immutable, you must consider the effort needed and the usability of the class itself after making it immutable.


答:
Why immutable types are so rarely used in other applications?

Ignorance? Inexperience?

Immutable objects are widely regarded as superior today, but it's a relatively recent development. Engineers who haven't kept up to date, or are simply stuck in 'what they know' won't use them. And it does take a bit of design changes to use them effectively. If the apps are old, or the engineers weak in design skills then using them might be awkward or otherwise troublesome.

Title: What are the drawbacks of immutable types?

Body:
I see myself using more and more immutable types when the instances of the class are not expected to be changed. It requires more work (see example below), but makes it easier to use the types in a multithreaded environment.

At the same time, I rarely see immutable types in other applications, even when mutability wouldn't benefit anyone.

Question: Why immutable types are so rarely used in other applications?

Is this because it's longer to write code for an immutable type,

Or am I missing something and there are some important drawbacks when using immutable types?

Example from real life

Let's say you get Weather from a RESTful API like that:

public Weather FindWeather(string city)
{
    // TODO: Load the JSON response from the RESTful API and translate it into an instance
    // of the Weather class.
}
```

<p>What we would generally see is (new lines and comments removed to shorten the code):</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class Weather
{
    public City CorrespondingCity { get; set; }
    public SkyState Sky { get; set; } // Example: SkyState.Clouds, SkyState.HeavySnow, etc.
    public int PrecipitationRisk { get; set; }
    public int Temperature { get; set; }
}
</code>```

On the other hand, I would write it this way, given that getting a Weather from the API, then modifying it would be weird: changing Temperature or Sky wouldn't change the weather in real world, and changing CorrespondingCity doesn't make sense neither.

public sealed class Weather
{
    private readonly City correspondingCity;
    private readonly SkyState sky;
    private readonly int precipitationRisk;
    private readonly int temperature;

    public Weather(City correspondingCity, SkyState sky, int precipitationRisk,
        int temperature)
    {
        this.correspondingCity = correspondingCity;
        this.sky = sky;
        this.precipitationRisk = precipitationRisk;
        this.temperature = temperature;
    }

    public City CorrespondingCity { get { return this.correspondingCity; } }
    public SkyState Sky { get { return this.sky; } }
    public int PrecipitationRisk { get { return this.precipitationRisk; } }
    public int Temperature { get { return this.temperature; } }
}
```


问:
What's the best documentation you produce and why?
I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination.

So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests.

The bigger question is why is that the best documentation you produce?

答: Does Javadoc count? I think my API documentation is reasonably well made and maintained. Why? Because it's as integrated with the coding process as it can be, and its structure and notation is well enough standardized. No need to waste brain cells on thinking how to actually realize the documentation, or link it with the code, or version it, because all this just happens by itself.</p>


问:
Architecting Python application consisting of many small scripts
I am building an application which, at the moment, consists of many small Python scripts.

Each Python script processes items from one Amazon SQS queue. Emails come into an initial queue and are processed by a script, and typically the script will do a small unit of processing (for example, parse email and store some database fields), then an item will be placed on the next queue for further processing, until eventually the email has finished going through the various scripts and queues.

What I like about this approach is that it is very loosely coupled.

However, I'm not sure how I should implement live.  Should I make each script a daemon which is constantly polling its inbound queue for things to do? Or should there be some overarching orchestration program or process? Or maybe I should not have lots of small Python scripts but one large application?

Specific questions:
How should I run each of these scripts - as a daemon with some sort or restart monitor to restart them in case they stop for any reason? If yes, should I have some program which orchestrates this?

Or is the idea of many small script not a good one, would it make more sense to have a larger python program which contains all the functionality and does all the queue polling and execution of functionality for each queue?
What is the current preferred approach to daemonising Python scripts?

Broadly I would welcome any comments or opinions on any aspect of this.

thanks

答:
I think this all depends much on your own goals and constraints. Does it run fast enough this way? Is it flexible enough for your use cases? Is it too brittle/Does it fail often? Does it seem well organized and easy to update/maintain/enhance?

If it works, do it. If it fails to meet your requirements, change it. You may need to test it "live" to decide whether it is acceptable.

A single program consisting of a framework for integrating the various scripts as modules would probably be ideal. But is the work required for a Cathedral worth the gain? Could you settle for a Bazaar?


答: If this application needs to stay running for a long time then build in resilience but kill it at random times (the monitor too - but less frequently), and have a monitor restart it. That way you are constantly exercising the monitor and restart capability of the system so when some true system failure shafts your system it will be more likely to recover smoothly.</p>

Title: Architecting Python application consisting of many small scripts

Body:
I am building an application which, at the moment, consists of many small Python scripts.

Each Python script processes items from one Amazon SQS queue. Emails come into an initial queue and are processed by a script, and typically the script will do a small unit of processing (for example, parse email and store some database fields), then an item will be placed on the next queue for further processing, until eventually the email has finished going through the various scripts and queues.

What I like about this approach is that it is very loosely coupled.

However, I'm not sure how I should implement live.  Should I make each script a daemon which is constantly polling its inbound queue for things to do? Or should there be some overarching orchestration program or process? Or maybe I should not have lots of small Python scripts but one large application?

Specific questions:
How should I run each of these scripts - as a daemon with some sort or restart monitor to restart them in case they stop for any reason? If yes, should I have some program which orchestrates this?

Or is the idea of many small script not a good one, would it make more sense to have a larger python program which contains all the functionality and does all the queue polling and execution of functionality for each queue?
What is the current preferred approach to daemonising Python scripts?

Broadly I would welcome any comments or opinions on any aspect of this.

thanks


问:
MVC : Does Code to save data in cache or session belongs in controller?
I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model?

I would add that I have other controller methods that will read this session value later.

```<code>  public ActionResult AddFriend(FriendsContext viewModel)
  {
        if (!ModelState.IsValid)
        {
            return View(viewModel);
        }

        // Start - Confused if the code block below belongs in Controller?

        Friend friend = new Friend();
        friend.FirstName = viewModel.FirstName;
        friend.LastName = viewModel.LastName;
        friend.Email = viewModel.UserEmail;

        httpContext.Session["latest-friend"] = friend;

        // End Confusion

        return RedirectToAction("Home");
    }
</code>```

I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.

```<code>public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext)
{
    httpContext.Session["latest-friend"] = friend;
}

public static Friend GetLatestFriend(HttpContextBase httpContext)
{
    return httpContext.Session["latest-friend"] as Friend;
}
</code>```

答: If it was me, I would create a new class called SessionManager (or something), where you can pass through your data to save the latest friend and retrieve it. That way you've got one spot where all of your session handling is done. </p>


答: In one of my previous jobs before I left, one of my tasks was to help with this document that contained various tidbits about the code base, which was a mix of VBScript, JScript, and C/C++ for the COM parts in addition to various mark-up languages as this was for a dot-com after all.  I believe it was nearly a dozen pages when I left and contained most of what I had learned in the ~9 or so months that I had been working there.  This is the best I've produced because of how it is the closest I've come to a good brain dump of all the things that were in my head in working with most of this code.  The leaving was more of a known issue when I started so in a sense it wasn't a shocking thing and it was kind of fun to try to spill the contents of my brain into a Word doc.</p>

Title: What's the best documentation you produce and why?

Body:
I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination.

So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests.

The bigger question is why is that the best documentation you produce?


答:
The obvious strategy would be to use a linear regression apporach like @DocBrown suggested. If you know the functional form, e.g. a simple linear relationship, getting your answer is rather straightforward. A big complication comes when the functional form is also unknown. Here some kind of optimization is needed to also fit the functional form. This optimization can be done using all kinds of optimizers, e.g. gradient descent, genetic algorithms.

I worked together with some people from Lubljana (Slovenia) who's main research interest is Equation Discovery. They do exactly the kind of things you are looking for, find equations for data that you have available. They find the functional form and the fitted coefficients using machine learning techniques. One additional technique they use is not to fit just one potential model, but a ensemble of possible models. See this link for some details.

Title: Find how the data has been processed

Body:
Well this has been a question I have puzzled about for a long time:

Suppose I have a dictionary of input:output like:

This

```<code>{2: 6,
 5: 15,
 20: 60,
 26: 78,
 ...
 982: 2946,
 997: 2991}
</code>```

where output = input*3.

or This

```<code>{0: 5,
 3: 8,
 17: 22,
 19: 24,
 ...
 991: 996,
 996: 1001}
</code>```

where output = input+5

or something else.

In short where there is a definite relation between input and output.

How can a program find the relation between the input and output, such that, given another input, the output can be calculated??

Is it possible to do the same with more complex calculations like output = 5*((input*5)+3)


问:
Joomla or development from scratch?
As someone who has very little experience in it, I would like to know what makes you think that Joomla can fulfill all you requirements?. What makes you choose it over development from scratch (or using a framework like Yii or Kohana).

What are the most common or crucial problem that you are facing when using Joomla? Since I don't have much experience in it, I would pressume that one of the biggest problem is flexibility. You can't scale or customize the behaviour of your app, and even if you could, you need to break some rule in Joomla, or wait for the next release. Is this true?.

Currently I am building a long term project, there might be a lot of specific functions and behaviours in it. I would like to build it from scratch or with help from some PHP frameworks. But I've seen so many websites (and some of them are great in terms of complexity) are using Joomla. This gave me some doubts about choosing the right tech.

I would like to know is there any, one or two ultimate reasons to choose Joomla/other.

答: I am using joomla since last 4 years. I have used it as framework to develop different kinds of web sites. There is nothing wrong to use Joomla. It has extensions to create a sandbox for custom extensions and it reduces much time. Numerous extensions are available already for free to use. And you can create your own in very short time.</p>

Title: Joomla or development from scratch?


问:
Prevent code from getting mess
I am a student and a freelance programmer. These days I am developing a software in VB6 which has recently crossed 100KB of source code.

The main problem, I face is, many times I have to refactor my existing source code which is really very boring. Also the size of my code base is not very big (only 100KB).

What are the techniques I should you use to prevent my code from getting mess?

答:
What language are you using?

If it is an object oriented language like Java or C++ make sure you understand OO Design principles like S.O.L.I.D. Also, learn some design patterns and try and analyse your current code to see if you could re-factor it to add some patterns. Design patterns will help with maintainability and extensibility in the future, and they will also help you communicate your implementation to other developers. Be careful not to use design patterns just for the sake of it, you want to avoid Needless Complexity.

Also, try and write code using the Test Driven Development approach, it forces you to really think about your design up front and write clean, testable and cohesive code.

Title: Prevent code from getting mess


问:
What are the best practices to secure a web API?
I need to build a web service API for our mobile app to interact with our server & database (in ASP.Net MVC 4, but that's hardly relevant). Wile most actions do not need users to be registered with our service, we would like to restrict access only to users of our app.

What are the methods to make sure that calls made from somewhere else (e.g. someone wanting all our data, or building an unofficial app) are rejected?

My initial idea is for the device to ask the server for a token, which is randomly generated and sent as is. All other methods will check that the request headers contain a specific one that will be md5 hash of the salted token.  The server knows the token and salt and is able to compute the hash and compares it with the one sent. In addition, the token as a limited lifespan, and the device must get another one every other hour.

That seems quite easy to implement and although probably not 100% proof, that seems to be a good idea. What do you think?

答:
As soon as you release the application, it might be reverse engineered. This means that there is nothing you can do to be 100% protected if the same application (same binaries, same settings) is distributed to all of your users.

If you can customize the application for every user, then you have a chance to maybe not forbid some other application to use your API, but at least limit this application by number of requests it can do to the API.

Imagine the following schema:

Client connects and sends its unique identifier (one identifier by user).

Server replies by sending a challenge encrypted with a public key. This public key is associated with the unique identifier previously sent.

Client solves the challenge by decrypting the data using a private key and sends the decrypted secret in plain back to the server.

Server verifies that the submitted secret corresponds to the one originally generated.

The developer who will hack your application and successfully obtain the private key would be able to use your API from his own application, but he will be identifier as himself for your server.

If the same user can do 10 000 requests to your API per day and in average, an active user makes 2 000 requests per day, it means that this developer would be able to use his application himself and maybe give it to his friends, but he wouldn't be able to, say, sell it to thousands of people, just because it will work only for a few minutes in the morning.

While this helps, it's not 100% proof neither. What if the hacker finds a way to extract the private key from your app when his own app is installed on the device?

Side note which doesn't answer your question, but still might be useful: don't think about an API as a tool for your primary product (mobile application). Think about it as a first class product itself, a product which may be paid. The same model is used for years by Amazon and Google, it starts to be actively used by Microsoft with Azure, etc.

As soon as you consider the API not as a secondary tool reduced to slavery for your shiny new mobile apps, but the actual product, at the same level as any application the user actually sees, you start thinking less about how to protect the API against the usage by other apps, and more about the monetization of the API itself. Such API can be used by your apps which are its customers, or any other apps, freely developed by anyone. This has several benefits:

Making an API so that it would be used only by your applications is difficult and expensive. This time and money can be used for something more useful.

Opening your API to the public can have a great benefit for both you and the world. Imagine you're a great architect and a great developer, so you've created an astonishingly great API, but your visual designer skills suck and you really don't understand anything about interaction design, etc. If you hide your API, the only thing people will know is that you've created a mobile application which is unusable and ugly. If your API is public, other developers will be attracted by its quality and write great applications for it, bringing you lots of money.

You never imagine how other people may use your APIs. This is what happened with Kinect. Originally, Microsoft created Kinect for games. When Microsoft opened the API to the public, they never imagined it would be used a few years later by scientific applications, health sector, etc. It's similar for web APIs: more developers are using it, more widespread the ideas would be.


问:
How did the term "hypervisor" come into use?
I've read about the "hypervisor" in hardware virtualization.  VMs are not my area, so I can't quite see where the term came from.

THe wikipedia article talks about how "the hardware's supervisor state was virtualized as well, allowing multiple operating systems to run concurrently in separate virtual machine contexts"

This implies that a supervisor process was virtualized.. which then probably originated a 'hyper'-visor.  Is this true?

答: "Hypervisor" goes back to the very beginnings of virtual machine systems: the CP/CMS projects at IBM's Cambridge Scientific Center, starting in 1964.  The "CP" part was the hypervisor, which created virtual machines, while the "CMS" part was the OS that typically ran inside the vms.  The oldest usage I'm aware of is in Goldberg & Popek's famous "Formal requirements for virtualizable third generation architectures" CACM paper from 1974.  At the time, the only extant example of a VM hypervisor was CP-67, the version of CP that ran on IBM's System 360 Model 67.


问:
If one is to learn a new programming language each year, what should the list be?
In chapter one of "The Pragmatic Programmer" the first learning goal is:

Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different approaches, you can help broaden your thinking and avoid getter struck in a rut. [...]

To achieve this over a career, the list of languages is likely to get quite long (particularly if you do not want to "progress" into management). Clearly the education of a programmer (or whatever form) is going to get you started with a core of commercially useful languages (the usual list from job posting: C, C++, Ruby, Python, JavaScript, C#, Java, VB, ...). Additionally a formal or informal learning programme is likely to have covered functional approaches (via something like Haskell, LISP or an ML derived language)

But once a reasonable subset of that list is learned- what's next, and why?

答: While I agree it is good to learn new languages (and even imperative through a long career), I think one a year is too much past the first five-ten years. What I would rather see is someone with this level of experience learning new things about the languages they already know. At some point you need depth as well as breadth of knowledge. So you can write an If construct in 12 languages, big whoop. I'd rather see someone who really digs in and become expert in at least one thing. And then the next few years become an expert at something else. Over a 30+year career, I want someone to have depth of knowledge not just the basics in a lot of things. </p>


答:
I do not mean this in a patronising manner but if possible you should consider moving away from VB6 for future work. In the meantime my personal view is that you should not be too concerned about the number of lines of code in your solution. The real concern is the cost of maintenance. If this is a solution that is going to evolve further then you should start breaking the application up into logical units (as suggested above SOLID is a great set of principles). I also suggest that with respect to the 'document, document, document' advice above you take a 'clean code' approach where you focus on making your code self-descriptive and simple. Documentation gets out-dated because is often not maintained. Furthermore if you write simple expressive code all you really need to document is the public API.

One last thought, refactoring is difficult without using TDD. Without a set of unit tests that describe behaviour any significant refactor's are risky because you may change the application's behaviour in an unexpected manner.

Title: Prevent code from getting mess

Body:
I am a student and a freelance programmer. These days I am developing a software in VB6 which has recently crossed 100KB of source code.

The main problem, I face is, many times I have to refactor my existing source code which is really very boring. Also the size of my code base is not very big (only 100KB).

What are the techniques I should you use to prevent my code from getting mess?


问:
How can we track how well we're preventing and avoiding security vulnerabilities?
It's pretty easy to track when we fix security vulnerabilities in existing code.  But to make sure the whole team is staying on their toes about writing secure code, I'd like to also track how well we are preventing and avoiding writing new security vulnerabilities.  What is the right way to measure that?</p>

答:
There is no answer, unfortunately. As noted in the comments, "How do you know if your elephant repellent has worn off?"

That said, if you want to report a somewhat informative metric, invest in a static code analysis tool (Fortify, Veracode, Checkmarx) and see how many issues it turns up. Such tools require tuning in order to find only the issues you are interested in.

A static analysis tool will not catch security defects in logic or design.


问:
Issues to be considered while loading jQuery?

I have seen many answers in SO regarding using Google's CDN to load jQuery instead of

loading it from the local server. In essence I understand this is the issue related with decreased latency, better caching. But I want to know the technical answer, perhaps an example mentioning why it is even an issue to just load a 30KB file. We see nowadays websites with rich multimedia features which do significant download from server, so in such light does this file size make any difference?

Also there are huge concerns regarding using such "heavy weight" library if all you are using is just a fraction of subset of features? And if you are going to use at all, it is recommended to use compressed version (30+ KB) instead of the uncompressed one(200+ KB)? I also know the usual answers to it, perhaps if someone can shed more insight to it?

My both questions mentioned above are essentially trying to raise the same issue. I would be very grateful for answers that can provide the perspective to it rather than usual answers in SO?

答:
As you know, it's all about performance!

If you are work on a large project, which covers modern UI concepts, maybe you will have bunch of different JavaScript libraries hosted on your server.
As you may know, browsers are limited to maximum of few (see 'connections per hostname' column) HTTP requests to specific host.

Let's say you have a site that needs to load a lot JavaScript libraries, and if they are minified, they are between 20-50KB each.

So, simply math: 10 libraries * 40KB = 400KB!

And it's very important to keep in mind that:

Access to particular resource (image, stylesheet, etc) is a separate
HTTP request.

There are still people who do not have very good    internet
connection or they are connected to public WiFi networks    that are
used by many people.

So I think in this case using of CDN (not only for jQuery, and whenever is possible) make sense because:

Increase parallel downloading overcoming the limitation of browsers.

Since CDN is used by a lot of sites nowаdays, there is a really big
chance to have already cached version of the resource.

It ensures that the user will get geographically close response.

And this point is valid both for your questions:

It reduces the amount of bandwidth used by your server (it may be a problem sometimes)

But there is something very important, which is ignored by many developers. They are using CDN to get latest version of a library, that is completely wrong! When new version is released, although in most cases, new functionality is added, there are cases when existing functionality can be removed (ex. function becomes deprecated) or modified!

So, it's a really good practice always to set a specific version of needed resource when you are using CDN.


问:
Automated Testing: Explaining its Business Value
To start I don't think this is a repeat of other questions on unit testing. What I'm looking for help with is articulating its value to a team of programmers, analysts, managers and testers. By automated tests, I don't think I need to make a distinction between unit tests (e.g. JUnit), BDD (e.g. JBehave, Fitness) and UI (Selenium , Watir) because I think they all provide similar value (but feel free to write an answer that disagrees :))

The following is a list I've identified, I'm looking for answers that help expand or refine:

Time/Cost Savings: writing automated tests can take more time than written test cases. However, considering tests are run multiple times, the marginal work (i.e. cost/time) to execute automated tests is several orders of magnitude less. That the automated tests are cheap to run facilitates changing the system over time.

Documentation: there is no truer way to know how a system works than its tests. Any other documentation is usually out of date the moment its written, but tests (at least those that pass) reveal how things actually work. This is true for both end-user AND API documentation.

Code Quality: test writing forces you to:

consider clients because tests are a client

breaks dependencies where making code testable often means figuring out how to make that code not require some other large system be available

答:
What businesses love is increasing value and lowering cost. You have to explain how automated testing will increase value since it does add an extra cost.

If your code is modular it will be possible to re-use it. Which means that the tests do not have to written all over again and you can just work on top of that existing code.

If there are legacy projects, automated testing makes it much easier to refactor. The technical debt has to be paid down at some point.

The documentation argument you provide isn't very good. The difference between keeping tests up to date and documentation up to date is just habit.

OwnerDisplayName: orangepips


问:
Can an 81 digit number generator lead to copyright infringement?
I'm looking to write a program that will generate valid sudoku puzzles. Essentially,  a sudoku puzzle is just an 81 digit number. (The blanks are zeroes.)  I would then like to use these puzzles in an Android app.

Is there any risk to using randomly generated puzzles in an app?  If another app has the same puzzle, am I infringing somehow?  All computer data is numbers, so theoretically a random number generator could stumble upon a copyrighted work at some point.

答:
This seems a lot like asking: Should I worry that something I write might have already been copyrighted by someone else?

The answer, of course, is that most people just don't worry about it. If you write something of any length yourself, rather than copying it from somewhere else, then the chance that you're going to write exactly the same thing that someone else did is pretty small. And if it ever does become an issue, you'll probably have some supporting evidence to show that you really did create the work yourself -- notes, books that you read on the topic, etc.

I think the same thing applies to your sudoku generator. The number of possible puzzles that your program could generate is huge: one source I found with a quick search says the number is 6.6709 * 10^21. Now, how many puzzles could have been copyrighted already? Millions, perhaps? Any way you look at it, the probability that someone playing your game happens upon a copyrighted puzzle must be vanishingly small. Also, the work that you are publishing is not a collection of canned puzzles -- it's just an algorithm that generates puzzles. Nobody can say that you copied their work (unless you lifted the code for generating puzzles from someone else).

TL/DR: Don't worry about it.

Also: I'm not a lawyer, and I'm not giving you legal advice here. I'm just pointing out the odds. If you have legal questions or concerns, talk to your own lawyer.


答:
IANAL, and you should never use legal advice given to you by a stranger on the internet. If you're at all worried contact a lawyer.

Having said that, I doubt very much that Sudoku is under copyright or that it might be possible to copyright an individual puzzle. What is copyrightable is the method of generation; your algorithm. Ensure you make your own up rather than using someone else's. Unless, of course, it's published with an open source licence.

P.S. I dispute your characterization of Sodoku as an 81 digit number; it's a number puzzle that uses 81 single digit numbers.

Title: Can an 81 digit number generator lead to copyright infringement?

Body:
I'm looking to write a program that will generate valid sudoku puzzles. Essentially,  a sudoku puzzle is just an 81 digit number. (The blanks are zeroes.)  I would then like to use these puzzles in an Android app.

Is there any risk to using randomly generated puzzles in an app?  If another app has the same puzzle, am I infringing somehow?  All computer data is numbers, so theoretically a random number generator could stumble upon a copyrighted work at some point.


答:
As you know, it's all about simplicity!

No matter if you're creating a large-scale web application which would be used by thousands of users every second, or a tiny little website used by you and maybe a few of your friends:

You may:

Go to JQuery website.

Verify that you already have the newest version.

If not, download it.

Copy it to the development directory.

Maybe set the permissions and attributes related to deployment.

Add the link to the file in your master page.

Verify that it works.

Or you can:

Ad the link to the CDN's JQuery file in your master page.

Verify that it works.

Using CDN is just easier and faster, without even considering an eventual and hypothetical performance impact. You add a link and it works. Simple as that.

What issues do you have to consider? The only one I know is that if you have to support both HTTP and HTTPS, the links are strange and look like that:  (notice the missing prefix). It seems that it is causing problems with some very old, very crappy browsers. If you need to ensure support for every browser created since 1990, make sure to search a bit more about this issue before using the CDN for JQuery.

Title: Issues to be considered while loading jQuery?

Body:
I have seen many answers in SO regarding using Google's CDN to load jQuery instead of

loading it from the local server. In essence I understand this is the issue related with decreased latency, better caching. But I want to know the technical answer, perhaps an example mentioning why it is even an issue to just load a 30KB file. We see nowadays websites with rich multimedia features which do significant download from server, so in such light does this file size make any difference?

Also there are huge concerns regarding using such "heavy weight" library if all you are using is just a fraction of subset of features? And if you are going to use at all, it is recommended to use compressed version (30+ KB) instead of the uncompressed one(200+ KB)? I also know the usual answers to it, perhaps if someone can shed more insight to it?

My both questions mentioned above are essentially trying to raise the same issue. I would be very grateful for answers that can provide the perspective to it rather than usual answers in SO?

Body:
As you know, it's all about simplicity!

No matter if you're creating a large-scale web application which would be used by thousands of users every second, or a tiny little website used by you and maybe a few of your friends:

You may:

Go to JQuery website.

Verify that you already have the newest version.

If not, download it.

Copy it to the development directory.

Maybe set the permissions and attributes related to deployment.

Add the link to the file in your master page.

Verify that it works.

Or you can:

Ad the link to the CDN's JQuery file in your master page.

Verify that it works.

Using CDN is just easier and faster, without even considering an eventual and hypothetical performance impact. You add a link and it works. Simple as that.

What issues do you have to consider? The only one I know is that if you have to support both HTTP and HTTPS, the links are strange and look like that: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> (notice the missing prefix). It seems that it is causing problems with some very old, very crappy browsers. If you need to ensure support for every browser created since 1990, make sure to search a bit more about this issue before using the CDN for JQuery.


问:
Coding style (do more, then simplify)
I'm a CS student and I have been coding for a few months shy of a year now, and I seem to have developed what I think may be a "bad" habit and I'm wondering if anyone does the same (or whether it's a bad habit at all). When I'm coding / solving a problem with code, I find that my initial implementation is lengthy and overly-complicated; in other words, there is a lot of extraneous code (variables, checks) that is simply not needed. When I finish the initial "draft," and make sure the code actually works, I simplify it and make it easier to understand/less verbose.

I think the reason I do this is that I have trouble foreseeing what I will need to complete a task and end up over-compensating and creating complexities that should not or need not exist. Anyone have any tips or advice on how to improve this facet of my coding style, or any input as to whether the habit is actually a bad one?

答: That habit is typical for TDD. First implement it and than refactor. I think every developer does not implement the best way on his first try. As long as you have unit tests to verify that everything still works after refactoring there's no problem with that.</p>

Title: Coding style (do more, then simplify)


答:
Sounds like a good habit to me. First rule in coding is to make it work. Once you've done that, clean up your code and make it neat, understandable and simpler if you can. </p>

<p>However - if you are spending a lot of time over designing your solution and wasting a lot of time creating stuff that doesn't need to exist, that's possibly a bad habit - like if you were creating a bunch of classes and just going a bit overdesiging mad. But as long as you're working towards "making it work" then it doesn't sound like it's a problem. </p>

Title: Coding style (do more, then simplify)

Body:
I'm a CS student and I have been coding for a few months shy of a year now, and I seem to have developed what I think may be a "bad" habit and I'm wondering if anyone does the same (or whether it's a bad habit at all). When I'm coding / solving a problem with code, I find that my initial implementation is lengthy and overly-complicated; in other words, there is a lot of extraneous code (variables, checks) that is simply not needed. When I finish the initial "draft," and make sure the code actually works, I simplify it and make it easier to understand/less verbose.

I think the reason I do this is that I have trouble foreseeing what I will need to complete a task and end up over-compensating and creating complexities that should not or need not exist. Anyone have any tips or advice on how to improve this facet of my coding style, or any input as to whether the habit is actually a bad one?

Body:
Sounds like a good habit to me. First rule in coding is to make it work. Once you've done that, clean up your code and make it neat, understandable and simpler if you can.

However - if you are spending a lot of time over designing your solution and wasting a lot of time creating stuff that doesn't need to exist, that's possibly a bad habit - like if you were creating a bunch of classes and just going a bit overdesiging mad. But as long as you're working towards "making it work" then it doesn't sound like it's a problem.


答:
Besides the points mentioned, it also reduces load on your webserver, especially if you don't have a proxy, so also static files are delivered via Apache or any other heavyload webserver.

Which again speeds up the performance of your website, even for other users.


答:
Just try to mark your extraneous code if possible. Variable checks can be written as assertions for example which add semantical information to your code, I.e. these properties have to be fulfilled etc. Since assertions are usually dropped in "release mode" (depending on language/plattform) lots of assertions do not have to be removed but can function as further debugging help when changing parts of your program.

Similarly for temporary variables that you use for code debugging, name them with a debug_ prefix or something similar, so you can tell their purpose right away.
Programming is an iterative process,therefore what you do is perfectly normal.

One thing to notice: Assertions can be even better than comments in explaining your code. Use them (wisely)!

Title: Coding style (do more, then simplify)


答:
My answer may be little off topic, but this method works for me.

Before you even start programming you have to think: what kind of structures I need to solve a problem, and what kind of algorithms.

Often you will find that solution already exist and that you only have to implement it into your project*. Never try to reinvent a wheel - if you need something there is always significant chance someone already done it better.

Once you do that you are only left with gluing those parts (algorithms and structures) together and that is usually simpler than thinking about a problem as a whole.

*That's why education is so important in IT. The more algorithms and kinds of structures you know the more often, during programming you will catch yourself thinking: "Oh, I know, I have to use this. Oh, and here I need to use that."

Title: Coding style (do more, then simplify)


答:
I use in code comments. I write them as I code, and comment each block explaining the process, not the specifics of how the code runs (no //set x = y comments!). I also use javadoc when writing Java code so that anyone using the code in our IDE has an instant rough guide to how to use my code.

For high level documentation (class structure, framework and installation instructions) I use our company wiki. That put all the information out in one place, rather than trying to distribute Word documents all over the place.


答:
I find that when I work out on paper what I want to do ahead of time, that I make less unnecessary code.  Sometimes I end up with several drafts on paper, so it's still an iterative process, but the iterations tend to be faster, since you don't have to get all the way to working code to realize that something you thought was a good idea won't work after all.  (It doesn't even have to be as detailed as pseudo-code; a simple drawing can be quite helpful.  Also, there's nothing magic about paper, whiteboards work well too.)

Cleaning up code is a good habit, but so is aiming for clean code in the first place.  You'll still need to clean things up even if you plan ahead, but you won't have quite as much of a mess to start with.

Title: Coding style (do more, then simplify)


问:
Starting a recurring project from scratch
We have a project that keeps recurring. The client expects us to run a website twice a year and this is happened for the last year and a half. I took the last working copy and based our latest website on it. Now, a co-worker has suggested that next time we should start from scratch instead of fighting against legacy code.

I have already started refactoring the existing code and so have the other developers who were on the project. The code is cleaner than before and it meets client needs. The refactoring was ongoing while we developed new features.

What are some good reasons to advise against starting from scratch?

答:
Rewriting it from scratch will likely take more time than refactoring and working with legacy code, unless the legacy code is truly a disaster.

Instead, I recommend spending some extra time during the beginning of each project to refactor the code more, to let you work with it more easily. This is probably a more time-effective approach, and over time, your code quality will improve


答:
1973

The term was in use at least as early as 1973, as seen in this advert from IPS Computer Marketing Corp. in Computerworld magazine (30 May 1973 - Vol. 7, No. 22):

360/651H or J System available for sale or lease Sept. 1973. Will supply with any number of selector channels. With 7074 Hypervisor.

1970

It appears in these two 1970 papers, with one quoting the other.

Operating systems architecture, H Katzan Jr - Proceedings of the May 5-7, 1970, spring joint computer conference:

... Hypervisors are particularly useful when it is necessary to run an emulator and an operating system at the same time. Similar to multiprogramming systems, a hypervisor is characterized by: (1) limited access; (2) batch utilization; (3) high throughput performance; (4) priority ...

Analysis of Major Computer Operating Systems, CS McIntosh, KP Choate, WC Mittwede - 1970 - DTIC Document (PDF):

As a result, this classification scheme should not be viewed as conflicting with other schemes which attempt to either describe different system environments or that are used for other purposes. For example, Harry Katzan, Jr., in a report presented at the 1970 Spring Joint Computer Conference entitled "Operating Systems Architecture, " describes five operating system types: multiprogramming, hypervisor multiprogramming, time-sharing, virtual systems, and tri-level operating systems. This classification scheme was developed to encompass a number of experimental and research-oriented systems, including some of those cited above. Consequently, the classification structure does not purport to be an
  inclusive representation of commercially available software. Nevertheless, since several of these system types are not represented by any commercially available system, this categorization can only be superficially applied to the commercial environment.

1969?

It also appears in earlier snippets in Google Books, but care must be taken as Google often has incorrect metadata. However, this 1969 description of the IBM 360/60 in Management Services, (Volumes 6-7, American Institute of Certified Public Accountants) seems possible (date check):

To operate in the multiprograming mode with both control systems simultaneously would require a minimum of 128K bytes of core memory, and thus a 360/40, since maximum core for a 360/30 is 65K bytes of memory. In addition, a hypervisor (a master control system requiring both hardware and software) would be required to partition memory between both control systems.

1966?

It may also appear in a paper by IBM: A Virtual Machine System for the 360/40 (1966) by R Adair, R Bayles, L Comeau, R Creasy, but Google Books only shows it as a result and no text. If someone has access to this paper online, perhaps they can confirm it.

Title: How did the term "hypervisor" come into use?

Body:
I've read about the "hypervisor" in hardware virtualization.  VMs are not my area, so I can't quite see where the term came from.

THe wikipedia article talks about how "the hardware's supervisor state was virtualized as well, allowing multiple operating systems to run concurrently in separate virtual machine contexts"

This implies that a supervisor process was virtualized.. which then probably originated a 'hyper'-visor.  Is this true?


答:
There are a few reasons to rewrite from scratch. I already mentioned them in another answer. In short, the reasons to reinvent the wheel I mentioned are:

Because someone doesn't know that the wheel exist already,

Because someone knows that the wheel exist, but doesn't like it,

Because someone believes she can make a commercial scale product,

Because it's fun.

In your case, none of those reasons seem to apply. The second reason might be valid if the code is really old and really bad (so bad it cannot be reasonably refactored), but from your answer, it seems it's not the case.

Joel Spolsky, on the other hand, mentioned why throwing away existent codebase and starting from scratch is a really, really bad idea. This article alone should convince your coworker that his suggestion may not be the best.

Title: Starting a recurring project from scratch

Body:
We have a project that keeps recurring. The client expects us to run a website twice a year and this is happened for the last year and a half. I took the last working copy and based our latest website on it. Now, a co-worker has suggested that next time we should start from scratch instead of fighting against legacy code.

I have already started refactoring the existing code and so have the other developers who were on the project. The code is cleaner than before and it meets client needs. The refactoring was ongoing while we developed new features.

What are some good reasons to advise against starting from scratch?


答:
"What I'm looking for help with is articulating its value to a team of programmers, analysts, managers and testers. By automated tests, I don't think I need to make a distinction between unit tests (e.g. JUnit), BDD (e.g. JBehave, Fitness) and UI (Selenium , Watir) because I think they all provide similar value (but feel free to write an answer that disagrees :))"

OK I'll take that challenge ;)

I mostly work with programmers and QA and my tools are ruby, rails, testunit, rspec, jasmine and selenium.

The BDD/TDD tools of rspec and testunit are part of programming.  You don't break them out and talk about them separately to management, you don't put them off due to lack of time, you include them in all your time estimates.  If really pushed asked how much time people have for you to explain computer science and programming to them.  I don't use these tests for the front end

GUI/UI/Jasmine/Selenium.  These are different.  I have these done by QA folks who have programmer backgrounds.  We make sure the tests are written to be as robust as possible and based on content not layout.  The (possibly new) cost of this should be explained as a shifted cost.  Instead of paying with broken software, lost customers and expensive fixes later, you pay a lot less (relatively) now with a few simple practices.

Title: Automated Testing: Explaining its Business Value

Body:
To start I don't think this is a repeat of other questions on unit testing. What I'm looking for help with is articulating its value to a team of programmers, analysts, managers and testers. By automated tests, I don't think I need to make a distinction between unit tests (e.g. JUnit), BDD (e.g. JBehave, Fitness) and UI (Selenium , Watir) because I think they all provide similar value (but feel free to write an answer that disagrees :))

The following is a list I've identified, I'm looking for answers that help expand or refine:

Time/Cost Savings: writing automated tests can take more time than written test cases. However, considering tests are run multiple times, the marginal work (i.e. cost/time) to execute automated tests is several orders of magnitude less. That the automated tests are cheap to run facilitates changing the system over time.

Documentation: there is no truer way to know how a system works than its tests. Any other documentation is usually out of date the moment its written, but tests (at least those that pass) reveal how things actually work. This is true for both end-user AND API documentation.

Code Quality: test writing forces you to:

consider clients because tests are a client

breaks dependencies where making code testable often means figuring out how to make that code not require some other large system be available


问:
What "sublicense" actually means?
First, it is clear that the right to sublicense doesn't give you the right to relicense.

Let's say that we have a library licensed under the MIT license(1 file), someone adds some features to the library but puts them under GPL(in the same 1 file). Or, if someone wants to sublicense, do they have to separate the code?

If someone wants to use the library, how are the licenses handled?

Let's say that the developers use only the MIT licensed code, without directly using some features under the GPL license, that are inside the same file.

Do they have to GPL their application because of the GPL licensed code?

Do they have to remove the GPL code in order to be free of the GPL restrictions or they can just use the library under the MIT permissions/restrictions as long as they don't use the GPL code?

答:
I am not a lawyer, nor do I play one on TV:

While the default answer for a question like this is just to talk to a lawyer, I think a better answer is to talk to the original author. Tell them what you are going to do with it and what your target audience is. Remember, the author does not waive his copyright for his work by releasing under a license, the author is free to choose what he wants to allow with it. The author can say "you may fork this library under this other license which has the requirements you seek" or just say "you may release your software using whatever license you want, I waive the requirement for X just as long as you do Y". I personally have gotten special permission to release to fork an author's open source software under Apache instead of GPL. Granted for a large, currently supported, project like Qt, this has HUGE repercussions - but this was a small project that they weren't maintaining anymore.

Considering that I see tons of open source applications released under the GPL, which I would say authors really don't understand what that really means. Remember, if you use GPL code, even if it's a single line, your entire application must be released under the terms of the GPL (that's a little extreme of course, no open source author would go after you for a single line - but it's the requirement of the license).

Also I don't agree with Chris Travers's answer.

Per this chart both BSD and MIT allow someone to release under a different license. Here is another source suggesting it allows sublicensing. I read through the new BSD license and it doesn't suggest anything about not allowing you to release under a different license - however it does have stipulations none of which forbid you to change the license in a derived product.

Title: What "sublicense" actually means?


问:
Delivering and caching files in asp.net
The question is - what is an effective way to deliver files to users? Consider an asp.net application which gives an ability to view various files. A kind of image library or web file directory. Key points are:

user can upload arbitrary files of size <= 10Mb

files are stored on disk

files never change

user can remove a file

there is a certain access check procedure for accessing a file

So I'd need to find some balance between availability (i.e. caching) and security (i.e. access control).

Currently user issues a request in a form /attachment/{id}, and a controller reads a file from a disk and sends it to a client:

```<code>if(HasAccess(user)) {
   var data = File.ReadAllBytes()
   return new FileResult(data);
}
</code>```

I suspect that's not an optimal way: it involves asp.net application pipeline and uses disks a lot. Can be this way optimized? Can I store such files in Output cache?

Are there other ways (not using Controller) to deliver files which should be considered?

答:
i have worked recently on a web project using asp.net (MVC3) and we had to implement two functionalities including fetching / storing files on / from the web server (file system).
One was file upload and download for user-file-exchange and the other was downloading report files (excel, pdf, csv, and so on).

I always tend and try to use the framework with which i am working to its full capacity, before writing something on my own, because i do believe it is (up to 99% ;) very thoroughly planed, created, optimized and tested to solve specific and real problems.

Having said this, you don't have soo many other options anyway, in my opinion. Why would you use ASP.NET and then trying to avoid the controller? The whole integrated security concept will be broken. Also do not forget logging - overriding the OnActionExecuting gives you a lot of power.

For our project we created custom attributes (customizing the frameworks security context) to decorate the controller methods directly like this:

```<code>[UserHasAccess(Roles.Download)]
public Attachment(int id)
{
    //...
}
</code>```

and thus saved the if part in the code, which makes it more clean and readable. Also why would you want to avoid the clean URI convention (asp.net routes) http:/domain.tld/attachment/id and use something more unreadable like http:/domain.tld/getfile.aspx?id=id?

We used also FileResult to deliver the files with the different mime types and to date we never had any problems.

About the caching - i think it does not make sense to cache files from the file system, unless you now exactly which top 25 files will be downloaded the most. Then yes, you could cache them. In our case the access to the FS proved to be bearable, so we do not cache the files.

Answer of the comment

Hi. In my opinion all best practice articles are regarding to the information or the data that is usually dynamically generated or belongs to the site and is unlikely to change (like navigation buttons for example) and not to files stored to the FS for example.

In our project we use caching for the lists we show (that can contain hunderds of items containing information, but not binary data!) and the pages (every page shows a predefined portion of the list). We do not cache files from the FS!

In your use case you have the point user can upload arbitrary files this could mean 1000 files every day. Would you cache them all? 1000 files x 5MB (in average) ~= approx. 5GB. How much memory has your web server? How often would you refresh the cache? Refreshing means again reading...

You could cache the most recent 100 and if the user who downloads the file is lucky enough to download exactly one of the cached files, then you will spare some time and file system access. In generally and statistically (if the file exchange is used a lot) probably not!

Do the math on paper and see it for yourself if its worth it, to cache the files or not.

I hope this clarifies my previous answer. Sorry for bringing the attributes and so, it was background for using the framework.

kind regards,
P.

Title: Delivering and caching files in asp.net

Body:
i have worked recently on a web project using asp.net (MVC3) and we had to implement two functionalities including fetching / storing files on / from the web server (file system).
One was file upload and download for user-file-exchange and the other was downloading report files (excel, pdf, csv, and so on).

I always tend and try to use the framework with which i am working to its full capacity, before writing something on my own, because i do believe it is (up to 99% ;) very thoroughly planed, created, optimized and tested to solve specific and real problems.

Having said this, you don't have soo many other options anyway, in my opinion. Why would you use ASP.NET and then trying to avoid the controller? The whole integrated security concept will be broken. Also do not forget logging - overriding the OnActionExecuting gives you a lot of power.

For our project we created custom attributes (customizing the frameworks security context) to decorate the controller methods directly like this:

[UserHasAccess(Roles.Download)]
public Attachment(int id)
{
    //...
}

and thus saved the if part in the code, which makes it more clean and readable. Also why would you want to avoid the clean URI convention (asp.net routes) http:/domain.tld/attachment/id and use something more unreadable like http:/domain.tld/getfile.aspx?id=id?

We used also FileResult to deliver the files with the different mime types and to date we never had any problems.

About the caching - i think it does not make sense to cache files from the file system, unless you now exactly which top 25 files will be downloaded the most. Then yes, you could cache them. In our case the access to the FS proved to be bearable, so we do not cache the files.

Answer of the comment

Hi. In my opinion all best practice articles are regarding to the information or the data that is usually dynamically generated or belongs to the site and is unlikely to change (like navigation buttons for example) and not to files stored to the FS for example.

In our project we use caching for the lists we show (that can contain hunderds of items containing information, but not binary data!) and the pages (every page shows a predefined portion of the list). We do not cache files from the FS!

In your use case you have the point user can upload arbitrary files this could mean 1000 files every day. Would you cache them all? 1000 files x 5MB (in average) ~= approx. 5GB. How much memory has your web server? How often would you refresh the cache? Refreshing means again reading...

You could cache the most recent 100 and if the user who downloads the file is lucky enough to download exactly one of the cached files, then you will spare some time and file system access. In generally and statistically (if the file exchange is used a lot) probably not!

Do the math on paper and see it for yourself if its worth it, to cache the files or not.

I hope this clarifies my previous answer. Sorry for bringing the attributes and so, it was background for using the framework.

kind regards,
P.


问:
What kind of algorithm could be used to produce an ordering which maximizes # of satisfied 'less than' constraints?
Let's say I have a set of items {e1, e2, ..., en}, and I also have a set of constraints {c1, c2, ..., cm}, with ci := ej appears before ek, for some j and k.

I want to produce an ordering of my items which maximizes the number of satisfied constraints, with the possibility that some of the constraints are contradictory. I'm not sure how to search for this, but I hope there is some known efficient algorithm for this.

It might also be helpful if, given weights for the constraints, I could instead maximize the total weight of the satisfied constraints, rather than just the number.

答:
You can do this with Linear Programming and Constraint Programming. It's helpful since many of the problems in this domain are NP-Hard. The specific algorithm in this case is typically known as the "Simplex Algorithm".

Some quick summaries:

Of Linear Programming:

Linear programming (LP, or linear optimization) is a mathematical method for determining a way to achieve the best outcome (such as maximum profit or lowest cost) in a given mathematical model for some list of requirements represented as linear relationships. Linear programming is a specific case of mathematical programming (mathematical optimization).
  More formally, linear programming is a technique for the optimization of a linear objective function, subject to linear equality and linear inequality constraints. Its feasible region is a convex polyhedron, which is a set defined as the intersection of finitely many half spaces, each of which is defined by a linear inequality. Its objective function is a real-valued affine function defined on this polyhedron. A linear programming algorithm finds a point in the polyhedron where this function has the smallest (or largest) value if such a point exists.

and Constraint Programming:

In computer science, constraint programming is a programming paradigm wherein relations between variables are stated in the form of constraints. Constraints differ from the common primitives of imperative programming languages in that they do not specify a step or sequence of steps to execute, but rather the properties of a solution to be found. This makes constraint programming a form of declarative programming. The constraints used in constraint programming are of various kinds: those used in constraint satisfaction problems (e.g. "A or B is true"), those solved by the simplex algorithm (e.g. "x ≤ 5"), and others. Constraints are usually embedded within a programming language or provided via separate software libraries.


问:
Are there pre-made commercial software licenses to choose from?
I currently have an open source project that is licensed under GPLv3.  I'd like to dual license it, so I can offer it for commercial use.  Are there any resources for choosing or creating a commercial software license?</p>

答:
What you want is a free software license without copyleft?

Because, GNU GPL, GNU LGPL and GNU FDL, allow commercial use.

If you want to link with proprietary software, then use the GNU LGPL.

If copyleft is not desired I suggest you to use the lib/libpng license.

You may just put the license as a comment on those source code files. Or cite properly elsewhere.

From the FSF and GNU view proprietary software is a unethical thing: It's take away people freedom and commonly impose Digital Restrictions Management (DRM).

Some useful links to know more about this ethical issue:

http://www.gnu.org/philosophy

http://upgradefromwindows8.com