问:
Addition of double's is NOT Equal to Sum of the double as a whole
I am aware of the floating point errors as I had gained some knowledge with my question asked here in SE Floating Point Errors.

What I am finding it difficult to understand is, the output of the following program.

```<code>        double d1 = 0 + 1.123 + 2.456;
        double d2 = 3.579;

        float f1 = 0f + 1.123f + 2.456f;
        float f2 = 3.579f;

        long l1 = (long)(0 + 1.123 + 2.456);
        long l2 = (long)3.579;

        System.out.println(d1==d2);  // Output = false;
        System.out.println(f1==f2);  // Output = true;
        System.out.println(l1==l2);  // Output = true;
</code>```

Why is the output "false" for double and not for float, even when float is single precision 32 bit and double is double precision 64 bit. Oracle docs

Any help with this would be highly appreciated.

答:
Consider this hypothetical.

You have two data types.  One is a floating point number with 32 bits of precision that is base 3 (represented by the digits 0, 1, and 2).  The other is a floating point number with 64 bits of precision that is base 4.

Given this code:

```<code>float a = .3 + .6
float b = .9;

print(a == b)
</code>```

The comparison will return true if base 3 floats are used, and false if base 4 floats are used, even though the base 4 float has a much higher precision.

Why is this?  Because the numbers 3, 6, and 9 can be represented exactly in the base 3 float, but can only be approximated in the base 4 float, no matter how many digits of precision there are.

This is why floating point numbers should never be compared using ==.  They should always be compared using a range of allowable error.

Body:
Consider this hypothetical.

You have two data types.  One is a floating point number with 32 bits of precision that is base 3 (represented by the digits 0, 1, and 2).  The other is a floating point number with 64 bits of precision that is base 4.

Given this code:

float a = .3 + .6
float b = .9;

print(a == b)

The comparison will return true if base 3 floats are used, and false if base 4 floats are used, even though the base 4 float has a much higher precision.

Why is this?  Because the numbers 3, 6, and 9 can be represented exactly in the base 3 float, but can only be approximated in the base 4 float, no matter how many digits of precision there are.

This is why floating point numbers should never be compared using ==.  They should always be compared using a range of allowable error.


问:
Why don't companies ship multiple modules within a mobile app? Are there concerns about tight coupling?
Preface: My question does not exclusively pertain to Google and it doesn't exclusively pertain to iOS. I'm only using Google and iOS as examples because they are familiar to many. I could have just as easily used 'Company X', apps 'A', 'B', 'C', 'D', and 'E', and 'Android', but I wanted to keep my question rooted in the real world with a tangible example.

In the iOS app store, Google has many apps. At a glance, I can see 'Google Search', 'Google+', 'Google Maps', 'Google Earth', and 'Gmail'.

But I wonder - Why didn't Google simply create a 'Google' app which can provide all of the functionality that these five apps provide? The black menu bar at the top of each Google webpage makes this possible on the web; so why don't they make this possible by way of a menu button at the bottom of one "global" Google app?

Is Google concerned about tight coupling between the apps?

Is Google concerned about tight coupling between the teams that develop the apps?

Is Google concerned about app size?

Is Google concerned about the memory footprint or CPU load that such a monolithic app might incur when it is loaded?

[Not a rant. Merely playing devil's advocate.]

In spite of many advantages, some iOS critics say that multiple pages of apps leave the iPhone and the iPad feeling "cluttered". This is particularly relevant to my question because it seems a bit much to expect a user to know about (and manage) so many Google mobile offerings. From a product standpoint, and arguably a usability standpoint, it seems like it would be wise to ship a single app.

If you're curious, I own an iPhone and a Nexus 7; so I'm not wedded to either of the two major mobile platforms.

And I have a real problem to solve here - Whether to bundle multiple apps inside of one large app, or to distribute separate bits of functionality in multiple apps.

EDIT: In response, to @MichaelT's comment

While there is indeed a 2GB size limit for apps, the size of your sandbox is only limited by the remaining capacity on the device.

答:
they are each separate Programs, having them all running inside the same app would draw a lot of usage on the Device's Processor.  having them separate means that the processes can be divided and not all running at the same time on the same thread. doing it this way gives the OS the ability to put the apps on the back burner so that other processes/apps can use the full potential of the processor, you can't use them all at the same time anyway.

they could come as a bundle like Adobe's suite of applications, but that suite is made up of several separate applications so that they don't all have to be running at the same time just to use one of them.

ContentLicense: CC BY-SA 3.0


问:
How to make sprint planning fun
Not only are our sprint planning meetings not fun, they're downright dreadful.

The meetings are tedious, and boring, and take forever (a day, but it feels like a lot longer).

The developers complain about it, and dread upcoming plannings.

Our routine is pretty standard (user story inserted into sprint backlog by priority >> story is taken apart to tasks >> tasks are estimated in hours >> repeat), and I can't figure out what we're doing wrong.

How can we make the meetings more enjoyable?

...

Some more details, in response to requests for more information:

Why are the backlog items not inserted and prioritized before sprint kickoff?

User stories are indeed prioritized; we have no idea how long they'll take until we break them down into tasks! From the (excellent) answers here, I see that maybe we shouldn't estimate tasks at all, only the user stories. The reason we estimate tasks (and not stories) is because we've been getting story-estimates terribly wrong -- but I guess that's the subject for an altogether different question.

Why are developers complaining?

Meetings are long.

Meetings are monotonous. Story after story, task after task, struggling (yes, struggling) to estimate how long it will take and what it involves.

Estimating tasks makes user-story-estimation seem pointless.

The longer the meeting, the less focus in the room. The less focused colleagues are, the longer the meeting takes. A recursive hate-spiral develops. We've considered splitting the meeting into two days in order to keep people focused, but the developers wouldn't hear of it. One day of planning is bad enough; now we'll have two?!

Part of our problem is that we go into very small detail (in order to get more accurate estimations). But when we estimate roughly, we go way off the mark!

To sum up the question:

What are we doing wrong?

What additional ways are there to make the meeting generally more enjoyable?

答:
We are having a weekly sprint with a one hour meeting in which we discuss the previous sprint, what is left to do and then move on to the planning of coming week.
All within one hour.

This is of course because we found out that in our case following scrum too strictly would only waste too much time. That is because most stories are already discussed with our team members when the requester creates the user story.

I'm just saying that if your team dreads planning meetings, you should probably let go some of the "rules" of scrum.

Title: How to make sprint planning fun


问:
Premature optimization in deciding how to optimize?
We have a class that has been properly identified for optimization. We've done the profiling and testing, and it's a problem.

Now we have two possible approaches for optimizing this class:

There is some very low-hanging fruit. We can rewrite this in a few days in such a way that the interface and results aren't changed, so we don't have to change any code that uses the class. We can see what effect this has on performance and go from there. This seems to me to be a very low risk, low investment approach.

Since we're already going to be making changes, we could go all out in our optimization. The suggested approach would implement a third-party engine and require us to change the code that uses this class, as well as transform the existing client data that is sent to the class into a format usable by the third-party engine. This may not take too much longer to code, but there would be much more testing required. This seems like a very high-risk, high-investment change and will require a lot of extra testing to make sure we don't break the calling code and don't break the existing client data.

I of course can't test ahead of time, but the second approach will probably execute more quickly and be more memory-efficient. However, I'm not sure how much faster, and I'm not sure if the extra effort will even be worth it. I'm not sure that once we made the low-risk changes, we would still consider the the code to be a valid target for optimization.

You can probably guess which approach I would rather take. I'm at odds with a coworker on this one.

So here's my question: Is the second option premature optimization despite the fact that we've already identified this code for optimization? What's the approach that should be taken in this situation?

答:
Without details it is hard to know for sure, but from my occasional experience of maintaining third party components, I would much rather have control of in-house code than be reliant on others.  3rd-party software adds a new layer of administrative complexity to a project that needs a better justification than that it is probably faster. I recommend against integrating third party software unless you really have no  practical alternative.

It sounds to me that the case for that is unproven, so stick with option 1.


问:
API Authentication, One time token VS Dynamic tokens
We are working on a new project, we are two lead developers and got on a crossroad on how to use a token to secure the communication between the server and the client.

First Suggestion: (The one time token AKA Static Token)

the client requests a primary token, by sending the username and password and the current_time (this variable will be saved in the server's database and the client side too) to the api, the server interprets the input, and renders a hashed token (e.g. : 58f52c075aca5d3e07869598c4d66648) saves it in the database and returns it to the client.

The client now saves the primary token, and creates new hashed token using the primary token + the current_time variable sent in the authentication request (lets call this new token, main_token) also the server does the same and create the same token using the same algorithm.

Each time the client queries the server API, it sends the main_token to the server, now the server compares the token generated in it, with the main_token sent by the client, if it matches, it means the user is real

Second Suggestion: (Dynamic Token)

The client generates two random keys ($key1 = rand(10000,90000); $key2 = rand(10000,90000);) On each request on the API, the client creates a hash using the query type, and the two keys with a complex algorithm, and sends these two keys + the hash to the server

The server, using the same Algorithm used in the client, creates a hash, and compares is to the one sent by the client, if it matches, the server proceeds to deal with the query

Now, the question is, Which one is the most logical, and secure way to use for securing the API requests?

答:
I really like the first approach in general.

it's simple to understand and implement

it's secure (to my knowledge)

it's a not uncommon approach which I've seen used in the past

One thing I don't see mentioned about the first that you should keep in mind, the timestamp used to hash the token needs to have a TTL expiry that's exceedingly short (like 1 second) so you verify the message wasn't sent with the same timestamp and token from a message 12 hours earlier; obviously it would calculate as legit but is not in this case.

If these are the only two options you're considering though I'd just like to make sure you've looked at other approaches too, as there are many. More than I'm going to list in fact. These are some common auth approaches which are worth studying just to see if they might fit your purpose better, and if nothing else understanding them may give you some ideas to help tighten up whichever approach you do go with.

Do note, I am not a security expert.

OAuth/Federated

In this approach you have a 3rd party guarantor where the consuming code requests the token/cert/what have you from them and passes that to you, at this point all you need to do is ask the 3rd party if the key you were given is legit.

Pro:

Standards based

Issues will be found by others on other people's systems so you will find out if insecurity happens

Much less auth work will be needed by you

Con:

You have to deal with a 3rd party servicer and their API, or create and host your own "3rd party" to segregate the auth out of your main service.

For many services overkill, but conceptually worth considering

Asynchronous Certificates

Here you would have your clients encrypt their communications with a public cert you have shared with them when they created a user. On your side you would decrypt using the private key associated with there user. Generally you would initiate the communication with a challenge-response to show they can encrypt/decrypt as you expect identifying them as who they claim to be. Though "synchronous" approaches are possible which don't use the challenge-response, they have slightly less security and some time synchronization issues which can make them trickier.

from Novell (yeah I know, novell? really?)

Tokens use a variable as the basis to generate the one-time password.
  This variable is called the challenge. The two main methods for
  determining the variable used to generate the password are
  asynchronous or synchronous.

With the asynchronous or challenge-response method, the server
  software sends the token an external challenge---a randomly generated
  variable--- for the token device to encrypt. The token uses this
  challenge variable, the encryption algorithm, and the shared secret to
  generate the response---the correctly encrypted password.

With the synchronous method, the challenge variable used to generate
  the password is determined internally by the token and the server. A
  time counter, event counter, or time and event counter combination
  within each device is used as the basis for the challenge variable.
  Because the token and the server each separately and internally
  determine the challenge variable from their own counters, it is very
  important for their time counters and the event counters to stay
  synchronized. Because it is so easy for the server and the token to
  get out of sync, most implementations allow for a certain amount of
  drift between the counters. Usually, a small range or window of these
  counter values is used to compute the password. However, if the token
  and server get out of sync beyond this window, a special procedure is
  necessary to synchronize them.

Pro:

Certificates have CA roots which make them trustworthy and difficult to forge

There are standard facilities in operating systems for managing and maintaining cert stores easily

Well-studied approach, lots of information available on it

Expiry along with a variety of other things are in-built facilities of standard certificates, they are generally robust

Con:

Certificates can be tricky to work with programmatically

Depending on if you require an external CA, may not be free

May need to maintain cert stores manually to ensure expected root trusts are configured

NTLM

Don't laugh, if this is a smaller or internal only service and you're in a windows environment, there is nothing wrong with using standard NTLM authentication to guarantee access. Especially if you're working with IIS this is hands down the simplest approach. Easy to maintain and configure as well in a web.config.

Pro:

Extremely easy to configure, implement, and maintain

Con:

Minimal interoperability

Not sufficient for public facing authentication

Nonces

When working with nonces in your authentication approach, you supply a method to get a nonce on the service. This method returns a unique arbitrary string or piece of data ("a nonce") on each request. Every request to other methods now require a nonce to be retrieved, and used in the crypto algorithm for the request. The value here is that the server keeps track of the nonces used, and never allows reuse of a nonce, this completely prevents replay attacks because once a request with one nonce is made, a request with that nonce can never be made again. As nonces are requested they're added to a list of available nonces, as they're used they're moved from the available list to the used list. When generating a nonce you ensure what you generate is not on the used list and the available list will never again have one of the old ones and therefore no repeats can be made.

Pro:

Thwarts replay attacks quite well

Not altogether difficult to implement or understand

Con:

Requires clients make two requests for each one request (though may be lessened by requiring nonces for only certain requests)

Requires management of nonces, which should be transactional

Negatively affects performance by requiring the extra requests for nonces (transactionality further increases resource cost of working with nonces)


问:
Behavior Driven Development and Unit Testing in Python
We might be interested in starting to incorporate a unit test suite to our project, which is coded in Python (and it uses Redis, PostgreSQL and some third-party libraries, if that bears into the solution).  The benefits we want to achieve are:

Once the project is up to speed, we want to be able to specify new behavior quickly and efficiently, to help improve communication and team productivity.  Read: We want BDD, but have already started coding without it.

Excellent textual support (i.e. the tests can be read almost as natural text), so as to make it easier to write and read tests.

Ability to automatically run tests (at the very least, to be able to include the running in a Bash script or something like that).  We use Windows and Linux for development, and Linux servers, so Linux support is our primary requirement.

Integration with github.  I don't know if it is possible, but I've seen some projects in github which have a "Passing" or "Failing" status on them and it would be great to have that for our project.

What are good tools / libraries that can help us do this, and, most importantly, what are good ways to incorporate BDD into a Python project?

Thank you very much!  Any suggestions are appreciated.

答:
Try out pyspecs. Making tests easy to read and constantly running during development were two of my main goals in creating this project.

Test Code:

```<code>from pyspecs import given, when, then, and_, the, this

with given.two_operands:
    a = 2
    b = 3

    with when.supplied_to_the_add_function:
        total = a + b

        with then.the_total_should_be_mathmatically_correct:
            the(total).should.equal(5)

        with and_.the_total_should_be_greater_than_either_operand:
            the(total).should.be_greater_than(a)
            the(total).should.be_greater_than(b)

    with when.supplied_to_the_subtract_function:
        difference = b - a

        with then.the_difference_should_be_mathmatically_correct:
            the(difference).should.equal(1)
</code>```

Console Output:

```<code># run_pyspecs.py

  | • given two operands
  |   • when supplied to the add function
  |     • then the total should be mathmatically correct
  |     • and the total should be greater than either operand
  |   • when supplied to the subtract function
  |     • then the difference should be mathmatically correct

(ok) 6 passed (6 steps, 1 scenarios in 0.0002 seconds)
</code>```

Body:
Try out pyspecs. Making tests easy to read and constantly running during development were two of my main goals in creating this project.

Test Code:

from pyspecs import given, when, then, and_, the, this

with given.two_operands:
    a = 2
    b = 3

    with when.supplied_to_the_add_function:
        total = a + b

        with then.the_total_should_be_mathmatically_correct:
            the(total).should.equal(5)

        with and_.the_total_should_be_greater_than_either_operand:
            the(total).should.be_greater_than(a)
            the(total).should.be_greater_than(b)

    with when.supplied_to_the_subtract_function:
        difference = b - a

        with then.the_difference_should_be_mathmatically_correct:
            the(difference).should.equal(1)

Console Output:

# run_pyspecs.py

  | • given two operands
  |   • when supplied to the add function
  |     • then the total should be mathmatically correct
  |     • and the total should be greater than either operand
  |   • when supplied to the subtract function
  |     • then the difference should be mathmatically correct

(ok) 6 passed (6 steps, 1 scenarios in 0.0002 seconds)


问:
Are project managers useful in Scrum?
There are three roles defined in Scrum: Team, Product Owner and Scrum Master. There is no project manager, instead the project manager job is spread across the three roles.

For instance:

The Scrum Master: Responsible for the process. Removes impediments.

The Product Owner: Manages and prioritizes the list of work to be done to maximize ROI. Represents all interested parties (customers, stakeholders).

The Team: Self manage its work by estimating and distributing it among themselves. Responsible for meeting their own commitments.

So in Scrum, there is no longer a single person responsible for project success. There is no command-and-control structure in place. That seems to baffle a lot of people, specifically those not used to agile methods, and of course, PM's.

I'm really interested in this and what your experiences are, as I think this is one of the things that can make or break a Scrum implementation.

Do you agree with Scrum that a project manager is not needed? Do you think such a role is still required? Why?

答:
The Scrum roles are quite well defined (if they seem vague it is because they are meant to be applicable in different types of organizations), and since Scrum teams are always (well, commonly) of about the same size - i.e. not very big - it is relatively easy to agree on what they encompass, even if that varies depending on the underlying organization.

Reading the question, answers and comments above, it seems obvious that the definition of the project manager role is much more difficult to nail down. I am sure that you can find a nice and compendious general definition of a PM's role, but what that actually means in real life is a totally different story.

Anyway, as it works at my job, the project managers are very seldom involved with the actual "Scrumming". They are not allowed to be Scrum masters (a local conflict-of-interest rule that we all are quite happy about), and they are only product owners in exceptional cases.

So where I work, the project managers are still there, doing pretty much what they always have done. Meaning that they keep the project on track, act as a filter against too much paranoia and micro-management tendencies from "above", solving problems that need a more clout than we posses to solve, and so on.

I'm sure that this is quite different at other places, but for us it works great.

Edit: Maybe I should clarify that for us, a Scrum team does not replace a project team. One or more Scrum teams are started to perform the actual development work for (and usually in) a project. The Scrum team(s) can (and probably always do) consist of the old team members, except for the project leader :-)

ContentLicense: CC BY-SA 2.5

Title: Are project managers useful in Scrum?


问:
Why Python and not Lua?
Why has Python been backed by google and become so rapidly popular and Lua has not?

Do you know why Lua has stayed in background?

答: You can do everything with Lua, it's created as a scripting language to extend programs? Yes, but it's far from limited to it, there is a lot of libraries for Lua, and with the right tools(LuaJIT's FFI or tolua) you can even use a C/C++ Library on it. The reason that makes Python more used in my point of view are only age, Python is used as first languages in many colleges and schools, there is more people that know Python than Lua, and is much more easy to found a good library for Python than for Lua, because the language is more mature. Also, i don't know much about Python, but as much as i know, it's easy to hide your code from the end-user, what in Lua, isn't that easy, i'm right?</p>

Title: Why Python and not Lua?


问:
Static methods or static functions?
I was just reading https://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function and all of a sudden, the thing came to my mind was the static methods. </p>

<p>As static methods are no way associated with an object how can it be called as static methods (almost all developers do)? Is my understanding about the methods/functions is correct? </p>

答:
(Using Java terminology): Static methods can be associated with static members (members of the class object). If the methods don't access static members (nor IO resources or anything else that could change state), of if those members are final primitives or immutable objects (essentially constants), then such static methods could be called functions, but in general, because they potentially could access the class object's members, they're usually called static methods.

In order to count as a function, a method must be independent of any state; it must not cause any side effects nor be affected by any side effects. When called with specific parameters, it must always return the same result. Otherwise it's not a pure function.

That is, the following area is a function:

```<code>class MyClass {
    static final double pi = 3.14;
    static double area(double r) {
        return pi * r * r;
    }
}
</code>```

while the following getCallCount is not a function:

```<code>class MyClass {
    static int callCount = 0;
    static int getCallCount {
        return ++callCount;
    }
}
</code>```

In general, mutable (non-final) static members should be used with caution - someone would say that they should not be used at all - because they make a global state to the program, which likely turns out to be a bad design choice in the long run. There are exceptions, but be careful...

You don't even need static members to make static non-functions: System.nanoTime() is definitely not a pure function (because it returns different value on successive calls), even though it only accesses the computer's clock, not any static members.

Confusingly enough, you could also make non-static pure functions:

```<code>class MyClass {
    final double pi = 3.14;
    double area(double r) {
        return pi * r * r;
    }
}
</code>```

Now, although not static any more, area is still a pure function: it doesn't touch anything that could change. The fact that you would have to create an instance of MyClass to access area doesn't reduce its "functionness". Indeed, one could argue that this kind of pure functions should always be made static.

Title: Static methods or static functions?

Body:
(Using Java terminology): Static methods can be associated with static members (members of the class object). If the methods don't access static members (nor IO resources or anything else that could change state), of if those members are final primitives or immutable objects (essentially constants), then such static methods could be called functions, but in general, because they potentially could access the class object's members, they're usually called static methods.

In order to count as a function, a method must be independent of any state; it must not cause any side effects nor be affected by any side effects. When called with specific parameters, it must always return the same result. Otherwise it's not a pure function.

That is, the following area is a function:

class MyClass {
    static final double pi = 3.14;
    static double area(double r) {
        return pi * r * r;
    }
}

while the following getCallCount is not a function:

class MyClass {
    static int callCount = 0;
    static int getCallCount {
        return ++callCount;
    }
}

In general, mutable (non-final) static members should be used with caution - someone would say that they should not be used at all - because they make a global state to the program, which likely turns out to be a bad design choice in the long run. There are exceptions, but be careful...

You don't even need static members to make static non-functions: System.nanoTime() is definitely not a pure function (because it returns different value on successive calls), even though it only accesses the computer's clock, not any static members.

Confusingly enough, you could also make non-static pure functions:

class MyClass {
    final double pi = 3.14;
    double area(double r) {
        return pi * r * r;
    }
}

Now, although not static any more, area is still a pure function: it doesn't touch anything that could change. The fact that you would have to create an instance of MyClass to access area doesn't reduce its "functionness". Indeed, one could argue that this kind of pure functions should always be made static.


问:
What can go wrong if the Liskov substitution principle is violated?
I was following this highly voted question on possible violation of Liskov Substitution principle. I know what the Liskov Substitution principle is, but what is still not clear in my mind is what might go wrong if I as a developer do not think about the principle while writing object-oriented code.</p>

答:
I inherited a codebase recently that has some major Liskov violators in it.  In important classes.  This has caused me huge amounts of pain.  Let me explain why.

I have Class A, which derives from Class B.  Class A and Class B share a bunch of properties that Class A overrides with its own implementation.  Setting or getting a Class A property has a different effect to setting or getting the exact same property from Class B.

```<code>public Class A
{
    public virtual string Name
    {
        get; set;
    }
}

Class B : A
{
    public override string Name
    {
        get
        {
            return TranslateName(base.Name);
        }
        set
        {
            base.Name = value;
            FunctionWithSideEffects();
        }
    }
}
</code>```

Putting aside the fact that this is an utterly terrible way to do translation in .NET, there are a number of other issues with this code.

In this case Name is used as an index and a flow control variable in a number of places.  The above classes are littered throughout the codebase in both their raw and derived form.  Violating the Liskov substitution principle in this case means that I need to know the context of every single call to each of the functions that take the base class.

The code uses objects of both Class A and Class B, so I cannot simply make Class A abstract to force people to use Class B.

There are some very useful utility functions that operate on Class A and other very useful utility functions that operate on Class B.  Ideally I would like to be able to use any utility function that can operate on Class A on Class B.  Many of the functions that take a Class B could easily take a Class A if it was not for the violation of the LSP.

The worst thing about this is that this particular case is really hard to refactor as the entire application hinges on these two classes, operates on both classes all the time and would break in a hundred ways if I change this (which I am going to do anyway).

What I will have to do to fix this is create a NameTranslated property, which will be the Class B version of the Name property and very, very carefully change every reference to the derived Name property to use my new NameTranslated property.  However, getting even one of these references wrong the entire application could blow up.

Given that the codebase does not have unit tests around it, this is pretty close to being the most dangerous scenario that a developer can face.  If I don't change the violation I have to spend huge amounts of mental energy keeping track of what type of object is being operated on in each method and if I do fix the violation I could make the whole product explode at an inopportune time.

Body:
I inherited a codebase recently that has some major Liskov violators in it.  In important classes.  This has caused me huge amounts of pain.  Let me explain why.

I have Class A, which derives from Class B.  Class A and Class B share a bunch of properties that Class A overrides with its own implementation.  Setting or getting a Class A property has a different effect to setting or getting the exact same property from Class B.

public Class A
{
    public virtual string Name
    {
        get; set;
    }
}

Class B : A
{
    public override string Name
    {
        get
        {
            return TranslateName(base.Name);
        }
        set
        {
            base.Name = value;
            FunctionWithSideEffects();
        }
    }
}

Putting aside the fact that this is an utterly terrible way to do translation in .NET, there are a number of other issues with this code.

In this case Name is used as an index and a flow control variable in a number of places.  The above classes are littered throughout the codebase in both their raw and derived form.  Violating the Liskov substitution principle in this case means that I need to know the context of every single call to each of the functions that take the base class.

The code uses objects of both Class A and Class B, so I cannot simply make Class A abstract to force people to use Class B.

There are some very useful utility functions that operate on Class A and other very useful utility functions that operate on Class B.  Ideally I would like to be able to use any utility function that can operate on Class A on Class B.  Many of the functions that take a Class B could easily take a Class A if it was not for the violation of the LSP.

The worst thing about this is that this particular case is really hard to refactor as the entire application hinges on these two classes, operates on both classes all the time and would break in a hundred ways if I change this (which I am going to do anyway).

What I will have to do to fix this is create a NameTranslated property, which will be the Class B version of the Name property and very, very carefully change every reference to the derived Name property to use my new NameTranslated property.  However, getting even one of these references wrong the entire application could blow up.

Given that the codebase does not have unit tests around it, this is pretty close to being the most dangerous scenario that a developer can face.  If I don't change the violation I have to spend huge amounts of mental energy keeping track of what type of object is being operated on in each method and if I do fix the violation I could make the whole product explode at an inopportune time.


问:
Make shareware program free in some countries
Idea. To make my shareware program free in less-developed countries. Or release a free edition for these countries.

Purpose. More users, bug reports, extensions, active forum, etc. Anyway, 90% sales are in ~30 richest countries. Why not make it free in China, India, Russia...

Question. What are possible problems? I can't find info on this topic. It seems that almost nobody does it (I know only Windows 7 Home Basic).

Algorithm. How would you implement it? I know it's possible to detect country using IP. It's OK if would fail to detect in 20% cases. When country is detected, the user would get license key for free. Country detection and license key generation can be implemented in web server.

EDIT:
Country detection can be performed when user wants (clicks button 'Register for free'). Then program connects to my website, which detects country and generates a license key from user's hardware ID. Then the free key can be used on that PC like a purchased key, and no internet connection required. On other PC/hardware the user can simply repeat the procedure, as long as he/she is in one of these countries.

EDIT:
Country detection is easy and fast, i tested it with this php script+database. It worked with all IPs of my website visitors of this month. However some of them may actually live in other countries (see jwenting answer).

答:
There's no reliable technical way to control distribution so as to ensure different priced versions don't leach into other areas.

No, it's NOT possible to detect the country based on IP address. Address ranges may be handed out to specific national agencies, but it's quite possible to have an address assigned to another country, or indeed none at all.

For example, I live in country A and my ISP is a subsidiary of an ISP in country B, gets their IP ranges from their parent company which buys them in country C where they're cheaper. Or I work for a multinational that has a global IP range registered in their home country, which is different from the country I work for them (I may even travel between countries).

And what if your user puts it on his laptop and goes abroad, to a country where he'd have to pay another price, will his software stop working?

So the only way is legal, license policy and enforcement by disallowing the sale of regional versions in other regions. That's the way Microsoft does it (as well as others like Levi's, I can't order a pair of 501s from Amazon US for example because Levi's does not allow selling their products across regional borders, a company like Amazon would lose their dealership if they do so anyway).

If you're going to sell hardware/software bundles, you can of course put in something like the region coding used in DVD and BluRay players. And draw the ire of your customers in areas where you're charging extra...


答:
What you could try is to hardcode the language/text of your program into the compiled packages, one for each country/language you will support.

Then set prices per language and give those for free that you like. For China and Russia this will probably work, as they have very specific character sets, for India this will probably a bit more complicated, but may also work out.

This way you tie the country to the language, which is probably not what you wanted, however.

Title: Make shareware program free in some countries

Body:
Idea. To make my shareware program free in less-developed countries. Or release a free edition for these countries.

Purpose. More users, bug reports, extensions, active forum, etc. Anyway, 90% sales are in ~30 richest countries. Why not make it free in China, India, Russia...

Question. What are possible problems? I can't find info on this topic. It seems that almost nobody does it (I know only Windows 7 Home Basic).

Algorithm. How would you implement it? I know it's possible to detect country using IP. It's OK if would fail to detect in 20% cases. When country is detected, the user would get license key for free. Country detection and license key generation can be implemented in web server.

EDIT:
Country detection can be performed when user wants (clicks button 'Register for free'). Then program connects to my website, which detects country and generates a license key from user's hardware ID. Then the free key can be used on that PC like a purchased key, and no internet connection required. On other PC/hardware the user can simply repeat the procedure, as long as he/she is in one of these countries.

EDIT:
Country detection is easy and fast, i tested it with this php script+database. It worked with all IPs of my website visitors of this month. However some of them may actually live in other countries (see jwenting answer).


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: I was asked to write a report to show all sales and expenses for the future, a Nostradamus module for our accounts system :P He was very serious, it was not supposed to be a prediction but the actual values.</p>

OwnerDisplayName: Sean

LastEditorDisplayName: Sean


问:
What are the requirements for an open-source license inside an open-source license?
If I include an open source library in my project that is licensed under the MIT license, but contains BSD-licensed code that requires attribution (correctly attributed inside the project), is it my responsibility to attribute it again if I decide to use that library?  Normally this is not a problem (I would just credit everyone regardless of the license) but on a mobile platform there is not a lot of real estate or efficient ways to show / bundle these licenses.</p>

答:
BSD does not always require one to credit the author in the gui of their appplication.

As a matter of fact, only the 4-clause license (original "BSD License") requires attribution outside the source code and binary code of the application.

It states as follows:

```<code>Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by the <organization>.
4. Neither the name of the <organization> nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</code>```

The revised 3-clause licence has removed clause #3.

The later (FreeBSD) 2-clause licence has also removed clause #4.

That means that if the library uses the any BSD licence, you do need to attribute it somewhere in your gui.

In this case, perhaps adding a colophon page to your application might be a solution.

Body:
BSD does not always require one to credit the author in the gui of their appplication.

As a matter of fact, only the 4-clause license (original "BSD License") requires attribution outside the source code and binary code of the application.

It states as follows:

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by the <organization>.
4. Neither the name of the <organization> nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

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

The revised 3-clause licence has removed clause #3.

The later (FreeBSD) 2-clause licence has also removed clause #4.

That means that if the library uses the any BSD licence, you do need to attribute it somewhere in your gui.

In this case, perhaps adding a colophon page to your application might be a solution.


问:
Am I covered with GPL If I want to share open source code of project developed in my company?
I'm working in a company and in my job contract there are confidential clauses concerning code, documents, etc...

In the company we are working on an open source project (GPL V3). The project is not shared yet to the public.

Do I have the right to share the code of the project with people (out from the company)?

答:
[unlike the others, I am a lawyer, so my answer will be a bit legalese].

First, there is a difference between your confidentiality obligations (which, without seeing the exact clause, I cannot address specifically) and the terms of the licenses granted to your company (or to you, as their agent). However, I do assume that when posting here, you are letting people already know this, and might be in violation of these confidentiality obligations.

If you feel that your company is infringing the GPLv3, meaning that it distributes the software to its clients without granting them the rights and freedoms under the GPLv3, then I suggest you call your employer's counsel. Otherwise, I remind you that the GPLv3 deals with distribution of the code.

As long as you do not distribute the code (either object or source) and only using it in your own quarters, then you don't have to release it to anyone (think about how many projects Google / Facebook has that are web-based and are GPL'd).

Here is the specific section of the GPLv3 (not the FAQ, but the agreement):
Article 2 (basic permissions) allow you to do whatever you want as long as you do not distribute:

"You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you."

Article 6 relates to distribution, and states that "You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways". Note the "may". "May" means that you do not "have to", but if you do, then there are terms.

--
Jonathan.

BTW: Check out my "Open Sourcing Your Code" presentation here.


问:
How to detect root cause of problem or bug
Often in coding, I find it very slow and difficult to detect the root cause of a bug and sometimes I end up going to wrong point in my code. It's painful. I know that to detect the root cause of a bug is a very important skill for programmers. Does anybody have a trick or technique to suggest a good way of finding the root cause?</p>

答:
Testing a huge project at once will give you a headache. The best way to detect root cause of problem is to test the smallest units individually. When all the smallest units are correct then test bigger units made by 2 of them and so on till you get to the top.

Make a habit of maintaining test cases for all units so that if a new bug appears after you change some part then you don't have to write the whole thing again. You can apply the tests to see what is the problem and exactly where.

Maintaining individual modules separately with their test cases can be save you a lot of problems in the long runs. When you want to make changes make changes in the smallest units, test them and then use them.

That can help you in the long run. Believe me, I didn't have the habit of maintaining testing code alongwith the code and it made my life hell. I am trying to fix it. Don't make the same mistake.


答:
Ask why a lot, and keep asking it until the problem is clear.

Why did the code crash? Because we got a divide by zero.

Why did we get a divide by zero? Because X was zero.

Why was X zero? Because it was passed in by function foo.

Why did foo pass in a zero? Because it was set to the total number of relationships that the object has

Why did this object have zero relationships? Because that's the default value before the object is fully initialized

Why was the value not set to be greater than one during initialization? Because there is a set of cascading if statements without a final catch-all else statement.

Why did this object not satisfy any of the if statements? Because the code assumes that every object has at least one parent, or at least one child.

Is that a valid assumption?

This technique is often referred to as "5 Whys". You can read more about "5 Whys" on wikipedia.

You might also be interested in reading answers to the question What is your most useful technique for finding (or preventing) bugs?

Title: How to detect root cause of problem or bug

Body: Often in coding, I find it very slow and difficult to detect the root cause of a bug and sometimes I end up going to wrong point in my code. It's painful. I know that to detect the root cause of a bug is a very important skill for programmers. Does anybody have a trick or technique to suggest a good way of finding the root cause?</p>

ContentLicense: CC BY-SA 4.0


问:
License that grants the initial author all rights of derived/modified work?
Please note that I do not want to argue about the moral aspect of this question. I know that there are probably many different concerns.

I have been researching for a special license that could be used in a following scenario, but with no success:

Let's assume I have a software and want to release its source code, so that others can use it too. Since I don't want others to make changes and keep them closed I could the GPL. But here's the thing: Even if I profit from changes that other people do. I can relicense only my code because I'm not holding the copyrigth any code that not made by me. But I would like to.

I want to know if there is a ready-to-use license that will grant me (the initial author) the rigth to relicense any changes or code that was added by others. Or in even shorter terms: A GPL that does not count for me.

If you are interessted why I need this: I don't know if I will ever use my software for a commercial product. Probably not, but if I just use the GPL, I migth end up in a situation where I can't remove any other code since there are to many committers.

答:
There isn't a ready-made licence that does this, you have to enforce copyright attribution:

Require all contributers to your code base assign or licence their code to you, when submitting the code. If a piece of code doesn't come with this, don't include it. That way you maintain full control over the version you maintain.

Of course if you also licence your code as GPL, there's nothing to stop anyone forking your project at any time - the changes don't have to come back to you.


问:
Complex fetching of Domain Objects
Usually whenever I want to fetch an aggregate root by ID I just use some type of Repository::findByID(...) function

Whenever I started with DDD I thought factories where just a pattern to build new objects, but after meeting some aggregates needing one or two extra queries to load, I realized that Factory::objectWithID(...) were useful to also create instances of objects already existing in the database.

Now I have a tree relationship of entities, like Project->Task. The number of relations is huge and I have no framework providing lazy loading.

Since Tasks can be nested, have complexity of their own, and should not be fully retrieved in one query, I made Project and Task different aggregate roots

How should I retrieve and persist Tasks?. It seems that a ProjectFactory is not the solution this time because a Project does not contain the whole Task tree.

I still want some aggregate root like features for my Project, and since I am avoiding queries inside my entities, I decided to write the relationships inside a Project-Service-Aggregate. Now I can retrieve a single Project with a Repo::findByID() function, but fetching a Task looks like

```<code>ProjectAggregationService *service = ProjectAggregationService.new(SomeProject)
Task task_1 = service.findTask(...)
Task task_1_child_2 = service.findTaskChild(task_1,2)
</code>```

I am puzzled at this point because:

I have a service to represent entity relationships.

I am declaring many instances of a service, whereas  before, services tended to be quite unique objects.

Not having a clear object tree like Project.tasks[1].subtask[3] make the code above look like more complex than necessary.

Basically I could summarize my question to: Did I take the right approach?

I would greatly appreciate any comment on my reasoning. I am mostly concerned about degenerating my code with overblown complexity, but I still think that keeping references to queries and repos outside my entities implementation is a good goal.

答: I think logic like this is supposed to go into repository of specific aggregate. I would question if Project and Task need to be different aggregate roots. Aggregate roots should be decided based on business needs, not on (perceived) complexity. Either way I would create either ProjectRepository::getTasks(project) or TaskRepository::getTask(project, taskId). This way, you will keep number of services to minimum while still keeping logic where it is logical to look for it.

Title: Complex fetching of Domain Objects


答:
It sounds like you need a license which requires any downstream changes to be submitted back to you. I don't know of any that include this clause, you may need to have a lawyer write a custom license for you.

Open source projects that accept contributions from other developers oftentimes have the developers sign "contributor agreements" in which the developers either assign their copyright to the project owner, or grant the project owner a full-rights license. This frees the project owner to do whatever they need to with the developer contributions, without worrying about copyright and without worrying about getting permission after the fact.

You can generate your own contributor agreements at this site: http://www.harmonyagreements.org/

Title: License that grants the initial author all rights of derived/modified work?

Body:
Please note that I do not want to argue about the moral aspect of this question. I know that there are probably many different concerns.

I have been researching for a special license that could be used in a following scenario, but with no success:

Let's assume I have a software and want to release its source code, so that others can use it too. Since I don't want others to make changes and keep them closed I could the GPL. But here's the thing: Even if I profit from changes that other people do. I can relicense only my code because I'm not holding the copyrigth any code that not made by me. But I would like to.

I want to know if there is a ready-to-use license that will grant me (the initial author) the rigth to relicense any changes or code that was added by others. Or in even shorter terms: A GPL that does not count for me.

If you are interessted why I need this: I don't know if I will ever use my software for a commercial product. Probably not, but if I just use the GPL, I migth end up in a situation where I can't remove any other code since there are to many committers.


答:
We need to delay the site launch by
  two weeks because Mercury is in
  retrograde and it's a bad time to
  start new things.

Title: What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?

Body:
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.


问:
How to remove data redundancy in a table?
```<code>F1  F2  F3  C1  C2  C3
------------------------------------------------
A   B   C   1
D   E   F   2
A   B   C       3
D   E   F       4
A   B   C           5
D   E   F           6
</code>```

i have a table like this.
i need my table to be free from Data redundancy
like this

```<code>F1  F2  F3  C1  C2  C3
-----------------------
A   B   C   1   3   5
D   E   F   2   4   6
</code>```

i am unable to figure out the optimized logic.
can someone help me out.?

答:
I will assume you are talking about a table in a RDBMS.

That process is called normalization.

The problem is caused because TABLE1 doesn't have a primary key or at least a unique index to begin with.

If TABLE1 had a PK (or a unique index), say F1,F2,F3, you could not have inserted more than one row with the same values fort those columns. That would have forced you to update the rows instead of inserting a new one.

Your question is not clear, but if what you want is somehow get TABLE2 from TABLE1, this would do it:

```<code>create table2 as
select
    f1,
    f2,
    f3,
    max(c1) c1,
    max(c2) c2,
    max(c3) c3
from
    table1
group by
    f1, f2, f3
</code>```

as long as there is no overlapping values as the sample seems to suggest.

Body:
I will assume you are talking about a table in a RDBMS.

That process is called normalization.

The problem is caused because TABLE1 doesn't have a primary key or at least a unique index to begin with.

If TABLE1 had a PK (or a unique index), say F1,F2,F3, you could not have inserted more than one row with the same values fort those columns. That would have forced you to update the rows instead of inserting a new one.

Your question is not clear, but if what you want is somehow get TABLE2 from TABLE1, this would do it:

create table2 as
select
    f1,
    f2,
    f3,
    max(c1) c1,
    max(c2) c2,
    max(c3) c3
from
    table1
group by
    f1, f2, f3

as long as there is no overlapping values as the sample seems to suggest.


答:
Yeah nice question though may sound very abstract or poorly directed. However if it is directed or not, again depends your perspective.

Yess debugging is very very important skill. The best/perfect way to deal with them is to have holistic view to them, strategizing for them - along their life cycle.

I dont want to be theoretical here. To start with we can start with their source.

Bugs are introduces by us - developers, due to

lack of understanding of technology

lack of understanding of domain, business workflows

ignorance

Lack of understanding of domain and ignorance (unintentional - may be due to working under pressure etc.) are easy to deal with. Having solid technical understanding really takes nerves. Yess really. If you dont trust me just start off with JavaScript and try to master it. Its the most quirky/confusing language but still runs the World Wide Web. I am trying to learn it for many months and I believe am not even done with 5% of it yet. Just for an idea about how things may be confusing, you can  have a look at how confusing but still interesting the behavior of this keyword is in JavaScript at here.

Apart from understanding of tech other development habits like following coding/development standards, conventions (to which others adhere to and expect things to be in a specific way), proper design patterns will ease the development efforts -> leading to cleaner codebase -> less confusion -> thus effectively resulting/introducing in less bugs.

So the key rule in ensuring less bugs is - "Plan / learn all things,
  never go haphazard."

The next important thing is mastering debugging tools. Many developers do not take dedicated efforts to learn debugging tools. Every technology today have very sophisticated debugging tools. If you master one you can easily replicate the same skills in other technology. For example I first learnt Visual Studio features like  Autos, Locals, Breakpoints, Conditional breakpoints, Watches, Thread Window etc. These feature concepts follow similar names in other IDEs. So I was able to very quickly use same stuff in Eclipse. The same follows in web debuggers like Chrome developer tools, Firebug. However there are many technology related stuff too like Profilers and element inspectors in web debuggers. Also Visual Studio 2012-2013 brings many new features that really need very dedicated efforts to completely understand them and practice them.

So thats my second point:

Debugging Tools

If you know technology well, you know what you want to accomplish (business scenario/ domain knowledge) and if you know how to track things when they misbehave, you are a king.

Also there is no doubt there are these obvious factors - experience and practice. But more conscious you are while learning and developing more quicker you will be in tracking things.

As a personal experience - when I was working a lot on JSP, Expression Language and related stuff I was able to tell them what might be going wrong just by listening to their problem behavior. So soon you start recognizing things quickly.

And whenever I stuck in some weirdly behaving code, I put breakpoint before it, hit debug, when breakpoint is hit check if all locals and globals have desired value and then step through each line looking for any changes that happens to those locals and globals.

Finally we have google: attach "best practices" to technology name, hit search and keep reading like this.

A trick or something? Well sort of - breakpoints and step throughs always helped me. Sometimes when I dont understand whats going wrong I take snapshot of suspicious behavior I find (but dont understand completely) while stepping through and put that snapshot with explaination on stackoverflow. :) Or else you can use tools like JSFiddle to explain problem in action. After all what you want is to get things fixed quickly and properly. ;p

These links may help you

Visual Debugging Tools

Chrome Developer Tools

Body:
Yeah nice question though may sound very abstract or poorly directed. However if it is directed or not, again depends your perspective.

Yess debugging is very very important skill. The best/perfect way to deal with them is to have holistic view to them, strategizing for them - along their life cycle.

I dont want to be theoretical here. To start with we can start with their source.

Bugs are introduces by us - developers, due to

lack of understanding of technology

lack of understanding of domain, business workflows

ignorance

Lack of understanding of domain and ignorance (unintentional - may be due to working under pressure etc.) are easy to deal with. Having solid technical understanding really takes nerves. Yess really. If you dont trust me just start off with JavaScript and try to master it. Its the most quirky/confusing language but still runs the World Wide Web. I am trying to learn it for many months and I believe am not even done with 5% of it yet. Just for an idea about how things may be confusing, you can  have a look at how confusing but still interesting the behavior of this keyword is in JavaScript at here.

Apart from understanding of tech other development habits like following coding/development standards, conventions (to which others adhere to and expect things to be in a specific way), proper design patterns will ease the development efforts -> leading to cleaner codebase -> less confusion -> thus effectively resulting/introducing in less bugs.

So the key rule in ensuring less bugs is - "Plan / learn all things,
  never go haphazard."

The next important thing is mastering debugging tools. Many developers do not take dedicated efforts to learn debugging tools. Every technology today have very sophisticated debugging tools. If you master one you can easily replicate the same skills in other technology. For example I first learnt Visual Studio features like  Autos, Locals, Breakpoints, Conditional breakpoints, Watches, Thread Window etc. These feature concepts follow similar names in other IDEs. So I was able to very quickly use same stuff in Eclipse. The same follows in web debuggers like Chrome developer tools, Firebug. However there are many technology related stuff too like Profilers and element inspectors in web debuggers. Also Visual Studio 2012-2013 brings many new features that really need very dedicated efforts to completely understand them and practice them.

So thats my second point:

Debugging Tools

If you know technology well, you know what you want to accomplish (business scenario/ domain knowledge) and if you know how to track things when they misbehave, you are a king.

Also there is no doubt there are these obvious factors - experience and practice. But more conscious you are while learning and developing more quicker you will be in tracking things.

As a personal experience - when I was working a lot on JSP, Expression Language and related stuff I was able to tell them what might be going wrong just by listening to their problem behavior. So soon you start recognizing things quickly.

And whenever I stuck in some weirdly behaving code, I put breakpoint before it, hit debug, when breakpoint is hit check if all locals and globals have desired value and then step through each line looking for any changes that happens to those locals and globals.

Finally we have google: attach "best practices" to technology name, hit search and keep reading like <a href="https://www.google.co.in/search?q=javascript+security+best+practices&oq=JavaScript+secu&aqs=chrome.3.0j69i57j0l2j69i62l2.10331j0&sourceid=chrome&ie=UTF-8#sclient=psy-ab&q=javascript+best+practices&oq=javascript+best+practices&gs_l=serp.3..0j0i7j0j0i7.1518.1518.0.1917.1.1.0.0.0.0.240.240.2-1.1.0....0.0..1c.1.20.psy-ab.OQ7TS6x-Gpw&pbx=1&bav=on.2,or.r_cp.r_qf.&bvm=bv.49478099%2Cd.bmk%2Cpv.xjs.s.en_US.c75bKy5EQ0A.O&fp=3e6b2f5492a5cb55&biw=1280&bih=899" rel="nofollow">this.

A trick or something? Well sort of - breakpoints and step throughs always helped me. Sometimes when I dont understand whats going wrong I take snapshot of suspicious behavior I find (but dont understand completely) while stepping through and put that snapshot with explaination on stackoverflow. :) Or else you can use tools like JSFiddle to explain problem in action. After all what you want is to get things fixed quickly and properly. ;p

These links may help you

Visual Debugging Tools

Chrome Developer Tools


答:
I don't know what non-optimized logic you've tried, but this works on the dataset example you gave:</p>

```<code>select
     f1
    , f2
    , f3
    , max(c1) as c1
    , max(c2) as c2
    , max(c3) as c3
from #RawData
group by f1, f2, f3
</code>```

Title: How to remove data redundancy in a table?

Body:
```<code>F1  F2  F3  C1  C2  C3
------------------------------------------------
A   B   C   1
D   E   F   2
A   B   C       3
D   E   F       4
A   B   C           5
D   E   F           6
</code>```

i have a table like this.
i need my table to be free from Data redundancy
like this

```<code>F1  F2  F3  C1  C2  C3
-----------------------
A   B   C   1   3   5
D   E   F   2   4   6
</code>```

i am unable to figure out the optimized logic.
can someone help me out.?

Body:
I don't know what non-optimized logic you've tried, but this works on the dataset example you gave:

select
     f1
    , f2
    , f3
    , max(c1) as c1
    , max(c2) as c2
    , max(c3) as c3
from #RawData
group by f1, f2, f3


问:
Polymorphism versus authorization
I have something bother me in the understanding of polymorphism (vs role):

Note: I am using rails (but it's a general question)

I have 4 models:

User

Pro

Customer

Company

There is  a polymorphic association (profileable) between Pro/Customer and User [because Pro has many more fields for the registration process than Customer].

User is used for the session (I am using the devise gem)

Basically something very similar to this writing is used:

http://jeffsaracco.com/blog/2012/03/04/ruby-on-rails-polymorphic-user-model/

Company association

Now, I want to create my association with Company.

By now, only Pro has one Company (but I figure it could be other profileable_type which can also have a Company).

Customer doesn't have a Company.

In that case which association is preferable:

Approach 1

User has_one Company

Company belongs_to User

and manage authorization (with a gem like cancan) to permit company creation only for Pro (with my profileable_type field in the user table)

or:

Approach 2

Pro has_one Company

Company belongs_to Pro

So in that case I don't need any authorization management anymore (User (and by extension Customer) cannot create company by default)

Looking for pros/cons of the 2 approaches. I am pretty sure the first one is the best solution as I have a user_id in my company table which would be more generic and expandable than having a pro_id.. I would be pleased to be sure. Thanks!

答:
(Coming from C#/Java, hopefully you can translate back to rails:)  Approach 1 is the way to go.  User needs to be able to take a company, return a company, and let the code using the class know whether the first method stores anything and the second returns anything but null.  Customer would do nothing in the first method, return null from the second, and the last (third) method would return false.  Pro would actually save and return a company and return true for the third method.

This means you can pass around and work with User and forget about Pro's and Customer's most of the time.  And you can add in other subclasses (models?), some of which have companies and some of which don't, and all your code using User will still work without a change.  Add in a few other concepts besides companies and the benefits multiply.

Expanding:

User should not actually have the functionality to take a company, it just needs to look like it can so code doesn't always have to worry about whether or not a User is a Pro.  At some point a User may be asked if it can handle a company, and a Pro will say "yes" and and a Customer "no".  In C#/Java (and I'm hoping this translates somehow to rails) a call to "SetCompany" would probably throw an exception.  (A null return from "GetCompany" might be better than an exception.)

If another class, A, is created that can have a company, extending Pro is a good idea.  (Or having Pro and A extend a third abstract (or not) class that has the code to handle a company.)  But this is only visible inside the new class.  All the code written to handle User objects does not need to know about it, which is the whole point.  All you're really doing is putting the code to handle the companies in one place (DRY).  Nobody ever needs to ask if they've got an instance of a Pro.  They just ask a User object (extension unknown) if it can handle a company.

And you might someday need a User extension that handles companies, but in such a different way you don't want to use the Pro code at all.  With User "handling" companies, this can all be done transparently.

Title: Polymorphism versus authorization


问:
What are the deliverables to give to the client for a web application ?
I have completed a web application which is basically developed in PHP and is just another regular web application. Usually when I deliver the final production release I just handover the code documentation and the architecture information to the client. However, for this particular project the client insists on having the complete in and out data about the project. </p>

<p>So I'm just wondering... What are the mandatory technical and non technical docs that I can give my client apart from the code and architecture documentations ? </p>

<p>(Also it would be kinda cool to hit the client about various stats and data about the project so that he would actually know the amount of work involved and how cool the product actually is.) </p>

答:
In addition to the really good answer of FrustratedWithFormsDesigner I'd like to say what the non technical documents include (as we did it):

the analysis data: what did the customer tell you when you first talked about requirements?

the offer you made:

the product requirement document

and the functional specification document

which together act as a sort of contract about what you must do and what you expect

the customer to deliver during development as well as the estimated time and cost.

the specification including review protocols, usecases and testplans, testresults

the design in UML and all corresponding documents

the documentation of sourcecode (doxygen or whatever)

the manual and installation guidelines

the final actual amount of resources (time and money) used for the project, so you can write an invoice

some customers want the meeting protocols, too which is then an extension to the "decisions document" mentioned above

Hope that is what you were looking for.


问:
How can I distinguish between one-worded expressions and two-worded expressions?
I was told to create two lists concerning most frequently used words from a plain text (10 Mb arbitrary texts) as monograms (for single worded expressions such as human, water, is) and bigrams  (for two-worded expressions such as basketball team, united states and etc)

I am stuck here and don't know how I can go about it! And how I can distinguish between these two?

My domain is not English, I only gave those examples to make my intention and meaning more clear.

答:
You can try to read from text word by word and make 2 instances of Dictionary, one for monograms and one for bigrams, having the expression as Key and occurrence as Value. With this you can make some statistics about expressions usage.
You can also use database storage for bigger files.</p>


问:
Why does git use hashes instead of revision numbers?
I always wondered why git prefers hashes over revision numbers. Revision numbers are much clearer and easier to refer to (in my opinion): There is a difference between telling someone to take a look at revision 1200 or commit 92ba93e! (Just to give one example).

So, is there any reason for this design?

答: A single, monotonically increasing revision number only really makes sense for a centralized version control system, where all revisions flow to a single place that can track and assign numbers.  Once you get into the DVCS world, where numerous copies of the repository exist and changes are being pulled from and pushed to them in arbitrary workflows, the concept just doesn't apply.  (For example, there's no one place to assign revision numbers - if I fork your repository and you decide a year later to pull my changes, how could a system ensure that our revision numbers don't conflict?)</p>


答:
You need hashes in a distributed system. Let's say you and a colleague are both working on the same repository and you both commit a change locally and then push it. Who gets to be revision number 1200 and who is revision number 1201 given neither party has any knowledge about each other? The only realistic technical solution is to create a hash of the changes using a known method and link things up based on that.

Interestingly HG does support version numbers but they are explicitly a local-only feature -- your repository has one set, your co-worker's repo will have a different set depending on how they pushed and pulled. It does make command line usage a bit more friendly than Git though.

Title: Why does git use hashes instead of revision numbers?

Body:
I always wondered why git prefers hashes over revision numbers. Revision numbers are much clearer and easier to refer to (in my opinion): There is a difference between telling someone to take a look at revision 1200 or commit 92ba93e! (Just to give one example).

So, is there any reason for this design?


答:
In layman's words:

Hashes are intended to be nearly universally unique.  It is NOT guaranteed but it is extremely unlikely that the same SHA's are generated for different content.  In practical term for a given project you can treat it as unique.

With revision numbers you would have to use a namespace in order to reffer specifically to revision 1200.

Git can work both distributed and/or centralized. So how do you get revision numbers correct and unique ?

Also using revision numbers would create the false spectation that newer revisions should have higher numbers, and that would not be true because of branching, merging, rebasing, etc.

You always have the option to put tags to commits.


问:
What is the proper way of nesting resources in REST model?
I'm designing a REST API of service and got stuck on proper way to nest resources.

Resources: partners, tickets, settings

Connections between resources:

partner has many tickets,

partner has set of settings,

Bussines logic:

you can list all partners as anonymous user,

you can add new ticket to specified partner as anonymous user,

only partner can list his tickets,

only partner can modify his tickets,

only partner can list settings,

only partner can modify settings,

What I did till now:

Partner resources

GET /partners - list all partners

GET /partners/:id - show details of the partner specified by :id parameter

GET /partners/:partner_id/tickets - list of partner's tickets

GET /partners/:partner_id/tickets/:id - details of the specified partner's ticket

POST /partners/:partner_id/tickets - saves new ticket

PUT /partners/:partner_id/tickets/:id - updates the ticket specified by :id parameter

GET /partners/:partner_id/settings - list partner's settings

PUT /partners/:partner_id/settings - update partner's settings

Problem/Question

Would it be proper way to split nested resources (tickets, settings) to seperate resources or duplicate them as seperate resources?

E.g.

GET /tickets/:id

POST /tickets

PUT /tickets/:id

GET /settings

PUT /settings

答:
HATEOAS:

GET /partners/:partner_id/tickets - list of partner's tickets, that is, returns a list of URIs, probably of the form /tickets/:id

GET /partners/:partner_id/tickets/:id - not needed

POST /partners/:partner_id/tickets - creates a ticket and associates to the partner, returns a 201 with the new URI, of the form /tickets/:id


问:
Difference between Zend Framework & Zend Server?
The title tells everything about my question but still let me elaborate to clarify : I know very well about the ZEND Framework but what about the Zend server?

Does it work like Apache server or anything else? What is the main difference between these two? I also know that Zend Server is a product of the Zend Company but where is it used?

答:
Zend Framework

Is a PHP source code library that allows you to write PHP web applications. It includes a MVC framework, handles dispatching of requests and contains useful utilities that most PHP programmers need.

It does not depend upon a specific web server and can run under any web server running a compatible version of PHP.

Zend Server

Is a repackaged version of Apache. It contains a control panel that allows you to configure PHP settings (those found in the php.ini file), and also enable/disable extensions for PHP.

Zend Server has a free community version and a commercial version. With all of it's features enabled, it allows a PHP application to support Zend's caching, code compiling and obfuscation.

Now I've run regular Apache with PHP, and Zend Server on the same machines. In most cases I've found Zend Server to perform better (despite the fact that it's also using Apache). Out of the box Zend Server comes configured better to run PHP. If you are an expert at installing PHP on Apache then you might be able to reproduce the results, but for the average programmer I recommend Zend Server if it's an option.

https://stackoverflow.com/questions/730915/is-zend-server-just-apc-and-apache-munched-together-into-an-install


问:
How to represent days and time graphically for a project I have done
How to represent the days and hours of different tasks(design, development, testing) of a software project in a graphical way.

I tried using a Gantt chart for it, but it does not represent the hours but just days, of a particular task, in a project.

Is there any way to do this in software management, I need this to show it to a client for a project I did.

Here is some of the values I intend to use.

```<code>●   Research time
   ○    Days 10 - 8 hours * 10 = 80
●   Design time
   ○    Days 10 -8 hours * 10 = 80
●   Development time
   ○    Days 15 – 8 hours times 15 = 120
●   Testing time
   ○    Days 3 – 8 hours times 3 = 24
</code>```

答:
Check out Google charts. They offer many many different types of chart formats. From researching all the available charts, you might be able to find one that will offer what you need.

The Advanced Example of the timeline chart might be something you can adapt to what you need. You may be able to colour code:

Research time

Design time

Development time

Testing time

Have have multiple charts per task.


问:
Should I repeat condition checking code or put it in a function?
I have a bunch of calls to a method that may or may not need to be made depending on whether certain features are enabled or not. As such, I've wrapped these calls in if blocks checking the enabled statuses.

The arguments to the method in each of these calls use some long variable names, so I've broken them out into different lines for readability / to adhere to our line-length coding standard.

These large method-call blocks, combined with the condition checks to see if they should be run (exacerbated by the mandate that we enclose all if blocks in braces), are quite noisy.

So I have something like this:

```<code>if (FeatureSettings.FeatureXIsEnalbed)
{
    this.TheMethodImCalling(
        FeatureSettings.ReallyLongFeatureXSettingAName,
        FeatureSettings.ReallyLongFeatureXSettingBName,
        ...);
}

if (FeatureSettings.FeatureYIsEnalbed)
{
    this.TheMethodImCalling(
        FeatureSettings.ReallyLongFeatureYSettingAName,
        FeatureSettings.ReallyLongFeatureYSettingBName,
        ...);
}

if (FeatureSettings.FeatureZIsEnalbed)
{
    this.TheMethodImCalling(
        FeatureSettings.ReallyLongFeatureZSettingAName,
        FeatureSettings.ReallyLongFeatureZSettingBName,
        ...);
}
</code>```

To reduce the noise and redundancy in this code I was thinking of taking the if block structure and putting it inside TheMethodImCalling, then passing in the ...IsEnabled value along with the rest of the arguments.

This seems somewhat silly though as I would effectively be calling the method and telling it "Don't do anything." when a feature wasn't enabled.

Now, I could probably make the code a bit more readable by assigning the long settings to shorter temporary variables or even fields of an Arguments class that I would then pass to the method, but those don't address the core question:

Should I repeat the condition checking code or put it in the function?

Or is there an alternative I should consider? (Both options seem somewhat smelly...)

答:
You may not have a choice here: if evaluating the ReallyLongFeatureZSettingAName property when FeatureSettings.FeatureZIsEnalbed equals false results in throwing an exception, the idea of passing the "guarding" FeatureSettings.FeatureZIsEnalbed to TheMethodImCalling will trigger an exception:

```<code>this.TheMethodImCallingIfEnabled(
    FeatureSettings.FeatureZIsEnalbed,
    FeatureSettings.ReallyLongFeatureZSettingAName,
    FeatureSettings.ReallyLongFeatureZSettingBName,
    ...);
</code>```

Depending on your target language, you may be able to shorten your code by "inverting" the call sequence: for example, in C# you could add this method to FeatureSettings

```<code>class FeatureSettings {
    ...
    public void RunIfEnabledZ(Func<string,string> callback) {
        if(FeatureZIsEnalbed) {
            callback(ReallyLongFeatureZSettingAName, ReallyLongFeatureZSettingBName);
        }
    }
}
...
var theCallback = (a, b) =>  this.TheMethodImCalling(a, b, ...);
FeatureSettings.RunIfEnabledX(theMethod);
FeatureSettings.RunIfEnabledY(theMethod);
FeatureSettings.RunIfEnabledZ(theMethod);
</code>```

Body:
You may not have a choice here: if evaluating the ReallyLongFeatureZSettingAName property when FeatureSettings.FeatureZIsEnalbed equals false results in throwing an exception, the idea of passing the "guarding" FeatureSettings.FeatureZIsEnalbed to TheMethodImCalling will trigger an exception:

this.TheMethodImCallingIfEnabled(
    FeatureSettings.FeatureZIsEnalbed,
    FeatureSettings.ReallyLongFeatureZSettingAName,
    FeatureSettings.ReallyLongFeatureZSettingBName,
    ...);

Depending on your target language, you may be able to shorten your code by "inverting" the call sequence: for example, in C# you could add this method to FeatureSettings

class FeatureSettings {
    ...
    public void RunIfEnabledZ(Func<string,string> callback) {
        if(FeatureZIsEnalbed) {
            callback(ReallyLongFeatureZSettingAName, ReallyLongFeatureZSettingBName);
        }
    }
}
...
var theCallback = (a, b) =>  this.TheMethodImCalling(a, b, ...);
FeatureSettings.RunIfEnabledX(theMethod);
FeatureSettings.RunIfEnabledY(theMethod);
FeatureSettings.RunIfEnabledZ(theMethod);


问:
Where to Perform Authentication in REST API Server?
I am working on a set of REST APIs that needs to be secured so that only authenticated calls will be performed. There will be multiple web apps to service these APIs. Is there a best-practice approach as to where the authentication should occur?

I have thought of two possible places.

Have each web app perform the authentication by using a shared authentication service. This seems to be in line with tools like Spring Security, which is configured at the web app level.

Protect each web app with a "gateway" for security. In this approach, the web app never receives unauthenticated calls. This seems to be the approach of Apache HTTP Server Authentication. With this approach, would you use Apache or nginx to protect it, or something else in between Apache/nginx and your web app?

For additional reference, the authentication is similar to services like AWS that have a non-secret identifier combined with a shared secret key. I am also considering using HMAC. Also, we are writing the web services in Java using Spring.

Update: To clarify, each request needs to be authenticated with the identifier and secret key. This is similar to how AWS REST requests work.

答:
The greatest concern IMHO is ease of use by developers, so assuming you are publishing an SDK or library as a compliment to your API, you can secure a client's calls any number of ways provided you keep it simple for the developer. But perhaps that is obvious?

That being said, I think the most straightforward way is HMAC. That gives you both the means to authenticate, but also the means by which you can verify the integrity of the message contents/payload. Plus, it is a common enough approach whereby most developers can find plenty of sample code to implement it for virtually any platform.

The question I might ask of you in return is, what is the data you need to secure? Are there any kind of industry standards you should conform to?

Otherwise, HTTP Basic auth over HTTPS only, or simply passing in a username/password parameters along with the request over HTTPS only might be sufficient (knowing full well though that this is not the most secure form of auth holistically speaking). Knowing that, if this is insufficient to your customers, you can always add additional forms of authentication down the road.


答:
There is nothing wrong with a guard condition at the top of a function, but I would consider two things first: (1) what is the normal use case -- does it normally get called with yes or no? And then (2) is it externally visible?  Can they do the same kind of check?

Calling a method which does nothing 99% of the time, is a bad idea -- it's misleading.

If your function is externally exposed, and called from elsewhere your condition may not make sense, and then they just always pass true.

It would be better if your function could calculate FeatureIsEnabled itself.

Title: Should I repeat condition checking code or put it in a function?

Body:
I have a bunch of calls to a method that may or may not need to be made depending on whether certain features are enabled or not. As such, I've wrapped these calls in if blocks checking the enabled statuses.

The arguments to the method in each of these calls use some long variable names, so I've broken them out into different lines for readability / to adhere to our line-length coding standard.

These large method-call blocks, combined with the condition checks to see if they should be run (exacerbated by the mandate that we enclose all if blocks in braces), are quite noisy.

So I have something like this:

```<code>if (FeatureSettings.FeatureXIsEnalbed)
{
    this.TheMethodImCalling(
        FeatureSettings.ReallyLongFeatureXSettingAName,
        FeatureSettings.ReallyLongFeatureXSettingBName,
        ...);
}

if (FeatureSettings.FeatureYIsEnalbed)
{
    this.TheMethodImCalling(
        FeatureSettings.ReallyLongFeatureYSettingAName,
        FeatureSettings.ReallyLongFeatureYSettingBName,
        ...);
}

if (FeatureSettings.FeatureZIsEnalbed)
{
    this.TheMethodImCalling(
        FeatureSettings.ReallyLongFeatureZSettingAName,
        FeatureSettings.ReallyLongFeatureZSettingBName,
        ...);
}
</code>```

To reduce the noise and redundancy in this code I was thinking of taking the if block structure and putting it inside TheMethodImCalling, then passing in the ...IsEnabled value along with the rest of the arguments.

This seems somewhat silly though as I would effectively be calling the method and telling it "Don't do anything." when a feature wasn't enabled.

Now, I could probably make the code a bit more readable by assigning the long settings to shorter temporary variables or even fields of an Arguments class that I would then pass to the method, but those don't address the core question:

Should I repeat the condition checking code or put it in the function?

Or is there an alternative I should consider? (Both options seem somewhat smelly...)


答:
Usually when something feels awkward like that, it's because you need to refactor your objects to more logically allocate the responsibilities.  If you have a bunch of these, my personal preference would be to put them in a list, and call them like this:

```<code>for feature in enabledFeatures:
    feature.process()
</code>```

That way you're not even wasting a conditional check on disabled features, which is especially useful when your ratio of disabled to enabled features is high.

Body:
Usually when something feels awkward like that, it's because you need to refactor your objects to more logically allocate the responsibilities.  If you have a bunch of these, my personal preference would be to put them in a list, and call them like this:

for feature in enabledFeatures:
    feature.process()

That way you're not even wasting a conditional check on disabled features, which is especially useful when your ratio of disabled to enabled features is high.


答:
As others have said, a copyright-assignment contributor agreement is closest to what you want. However, a contributor agreement only covers individuals who opt into it; there is nothing to stop someone from forking your open source project and making changes without agreeing to your copyright-assignment agreement.

From what you've said, you'd like to have a license that says, "You can use, copy, and modify this software, but by doing so you agree that you grant to the original author all rights to any changes you make." It's not clear that this is a legally tenable provision to have in your license. I'd question what court would uphold such a software license that automatically lays claim to totally new code authored by a user. (In any case, most developers would stay far away from it.)

Instead, what you'd probably have to do is make your project non-free. Have a license that says, "You can use and share this software, but changing it is not allowed." Then, require developers to sign a contract that exempts them from the no-modification clause in exchange for copyright assignment of their modified versions. (If you choose to do this, consult a lawyer to confirm that this strategy is tenable and to draft the license and contract text for you.) This will still likely scare away developers, but you might have a more legally sound footing.

The final option is to use an actual vetted copyleft license like the GPL, refuse to accept code from people who won't assign copyright to you, and accept the fact that you may have competing free projects that fork your code. For example, Google (with Android) and Oracle (with MySQL) have taken this approach. The main advantage you have over your competitors is that they must play by the rules of the GPL at all times (since they build on your GPL'd core software), but you do not (because you own the copyright to all code in your codebase).


答:
In layman's words:

The code seems ok to me.

It has a very small cyclomatic complexity.

I see no noise in having to close the if's curly brackets.

Having simple sequential "if" blocks *is not a code smell*.

But if you thing the list of conditional proccesses will be growing in the future you should be considering the "Command" or "Chain of responsability" design patterns. That way you will not need the ifs with their corresponding curly braces that bother you so much.


问:
Make shareware program free in some countries
Idea. To make my shareware program free in less-developed countries. Or release a free edition for these countries.

Purpose. More users, bug reports, extensions, active forum, etc. Anyway, 90% sales are in ~30 richest countries. Why not make it free in China, India, Russia...

Question. What are possible problems? I can't find info on this topic. It seems that almost nobody does it (I know only Windows 7 Home Basic).

Algorithm. How would you implement it? I know it's possible to detect country using IP. It's OK if would fail to detect in 20% cases. When country is detected, the user would get license key for free. Country detection and license key generation can be implemented in web server.

EDIT:
Country detection can be performed when user wants (clicks button 'Register for free'). Then program connects to my website, which detects country and generates a license key from user's hardware ID. Then the free key can be used on that PC like a purchased key, and no internet connection required. On other PC/hardware the user can simply repeat the procedure, as long as he/she is in one of these countries.

EDIT:
Country detection is easy and fast, i tested it with this php script+database. It worked with all IPs of my website visitors of this month. However some of them may actually live in other countries (see jwenting answer).

答:
One possibility is to not have any enforcement at all, with no nagging for registration (any reminders are unintrusive). Legally, the license states that only people in certain places can use the software for free, but you don't do anything to block people from using it for free elsewhere.

I believe this model has worked for some companies in the past, but these days there's such a big assumption that software should be available for free anyway. So it's possible, but it could mean you never have anyone pay at all.

A lot probably depends on who your target customers are, and what the software does.