问:
Decision tree (?) reduction
I need to check certain conditions (of size n) on an object and perform one of several options available (size m) based on the result. Seems to me it fits a tree.

Now. The tree is quite large and I wonder if there's a way to reduce it.

Here's a sample of it

The conditions are marked as c1,...,cn and the functions to perform are marked as f1,...,fm (the crossed zeros are dont-care values)

答:
Indeed, a tree is a good data structure for that. You can then create a BST which will allow to find by lookup a specific action based on the c1 to cn conditions.

Obviously, this has a huge benefit of avoiding ugly code such as:

if (c1) {
    if (c2) {
        if (c3) {
            ...
        }
        ...
    }
    ...
}
```

<p>Whether the BST can be simplified even more depends on the exact association between the conditions and the actions. Look for a pattern. Imagine what would happen if you put <em>c</em><sub>1</sub> after <em>c</em><sub>2</sub>.</p>

<p><strong>How do I search for the action?</strong></p>

<p>If you express your conditions as an array of <em>n</em> elements [<em>c</em><sub>1</sub>, <em>c</em><sub>1</sub>, ⋯ <em>c</em><sub>n</sub>], you can then search for the action either recursively or iteratively. For instance, a recursive approach would look like this:</p>

<pre class="lang-js prettyprint-override"><code>var findAction = function (conditions, node) {
    // `shift` also removes the element from the array.
    var currentCondition = conditions.shift();

    if (typeof node !== 'boolean') {
        return node;
    }

    return findAction(conditions, node[currentCondition]);
}
</code>```

which can be called like this:

var conditions = [false, false, true, false];
var tree = {
    true: {
        true: f1,
        false: {
            true: f2,
            false: f1
        }
    },
    false: {
        true: {
            true: f5,
            false: f3
        },
        false: {
            true: {
                true: f2,
                false: f6
            },
            false: f4
        }
    }
};

findAction(conditions, tree)(); // Will execute `f6`.
```

<p><strong>The Karnaugh map seems much easier...</strong></p>

<p>It is, but it also has a limitation: all your leafs should be at the same depth. This is actually the case in the table you've shown, but may not necessarily be the case in the real problem you are attempting to solve.</p>

<p>If, for instance, some nodes are two levels deep while others are eight levels deep, with Karnaugh map, you have to align them to be eight levels deep, which will probably result in <strong>severe duplication</strong> (but not necessarily in reduced maintainability; it may actually be that maintainability will only increase). With a BST, you don't have to do that.</p>

<p>A simplistic example of the following BST:</p>

<pre class="lang-js prettyprint-override"><code>var tree = {
    true: {
        true: f1,
        false: {
            true: {
                true: f2,
                false: f3
            },
            false: f4
        }
    },
    false: f5
};
</code>```

will be expressed like this Karnaugh map:

var tree = {
    true: {
        true: {
            true: {
                true: f1,
                false: f1
            },
            false: {
                true: f1,
                false: f1
            }
        },
        false: {
            true: {
                true: f2,
                false: f3
            },
            false: {
                true: f4,
                false: f4
            }
        }
    },
    false: {
        true: {
            true: {
                true: f5,
                false: f5
            },
            false: {
                true: f5,
                false: f5
            }
        },
        false: {
            true: {
                true: f5,
                false: f5
            },
            false: {
                true: f5,
                false: f5
            }
        }
    }
};
```

Title: Decision tree (?) reduction

Body:
Indeed, a tree is a good data structure for that. You can then create a BST which will allow to find by lookup a specific action based on the c1 to cn conditions.

Obviously, this has a huge benefit of avoiding ugly code such as:

if (c1) {
    if (c2) {
        if (c3) {
            ...
        }
        ...
    }
    ...
}

Whether the BST can be simplified even more depends on the exact association between the conditions and the actions. Look for a pattern. Imagine what would happen if you put c1 after c2.

How do I search for the action?

If you express your conditions as an array of n elements [c1, c1, ⋯ cn], you can then search for the action either recursively or iteratively. For instance, a recursive approach would look like this:

var findAction = function (conditions, node) {
    // `shift` also removes the element from the array.
    var currentCondition = conditions.shift();

    if (typeof node !== 'boolean') {
        return node;
    }

    return findAction(conditions, node[currentCondition]);
}

which can be called like this:

var conditions = [false, false, true, false];
var tree = {
    true: {
        true: f1,
        false: {
            true: f2,
            false: f1
        }
    },
    false: {
        true: {
            true: f5,
            false: f3
        },
        false: {
            true: {
                true: f2,
                false: f6
            },
            false: f4
        }
    }
};

findAction(conditions, tree)(); // Will execute `f6`.

The Karnaugh map seems much easier...

It is, but it also has a limitation: all your leafs should be at the same depth. This is actually the case in the table you've shown, but may not necessarily be the case in the real problem you are attempting to solve.

If, for instance, some nodes are two levels deep while others are eight levels deep, with Karnaugh map, you have to align them to be eight levels deep, which will probably result in severe duplication (but not necessarily in reduced maintainability; it may actually be that maintainability will only increase). With a BST, you don't have to do that.

A simplistic example of the following BST:

var tree = {
    true: {
        true: f1,
        false: {
            true: {
                true: f2,
                false: f3
            },
            false: f4
        }
    },
    false: f5
};

will be expressed like this Karnaugh map:

var tree = {
    true: {
        true: {
            true: {
                true: f1,
                false: f1
            },
            false: {
                true: f1,
                false: f1
            }
        },
        false: {
            true: {
                true: f2,
                false: f3
            },
            false: {
                true: f4,
                false: f4
            }
        }
    },
    false: {
        true: {
            true: {
                true: f5,
                false: f5
            },
            false: {
                true: f5,
                false: f5
            }
        },
        false: {
            true: {
                true: f5,
                false: f5
            },
            false: {
                true: f5,
                false: f5
            }
        }
    }
};


问:
Why do I have to run git add after making changes?
I started using git when I was studying for small projects and then the workflow was git add file when having made a new file and then git commit -m ... for subsequent changes.

Now I'm in a new professional larger project where we use git flow. we didn't have any actual problems with git but I wonder why I must make git add now every time I make changes. Is it because I always make a new branch for just myself when we use git flow and therefore I must add the files to an initially empty branch?

Can you please let me know how I can get more skilled at using git flow ?

答:
Often you have files which appear in your project directory which you don't want to have in your git repository. For example files the software reads and writes in its own directory as part of its operation. That's why git doesn't blindly index everything in the project directory but instead asks you to add files manually. Also, any binary files should usually not be added to git because it can not handle them well.

Also, sometimes you make multiple changes which are actually separate issues. In that case you often want to break it down into two separate commits by first adding the changes to one file, committing it, and then adding the others.

When this problem does not apply to you in your case, you can use git add --all to add all files in the directory. You can even use git commit --all to add and commit all files in your working tree with a single command.

ContentLicense: CC BY-SA 3.0


问:
Why is .compareTo() in an interface while .equals() is in a class in Java?
I want to know why the .compareTo() is in the Comparable interface while a method like .equals is in the Object class. To me, it seems arbitrary why a method like .compareTo() is not in the Object class already.

To use .compareTo(), you implement the Comparable interface and implement the .compareTo() method for your purposes. For the .equals() method, you simply override the method in your class, since all classes inherit from the Object class.

My question is why is a method like .compareTo() in an interface that you implement rather than in a class like Object? Likewise, why is the .equals() method in the class Object and not in some interface to be implemented?

答:
In addition to Snowman's excellent answer, remember that Comparable has been a generic interface for a long time. A type doesn't implement compareTo(object), it implements compareTo(T) where T is its own type. This cannot be implemented on object, since object does not know the class that will be derived from it.

object could have defined an compareTo(object) method, but this would have allowed not just what Snowman points out, a comparison between two ArrayList<T>s or between two Threads, but even a comparison between an ArrayList<T> and a Thread. That's even more nonsensical.


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答: I think the unnested ternary operator (i.e., a statement where it's used only once) is fine, but if you're nesting more than one, it becomes somewhat hard to read.</p>

Title: Ternary operator considered harmful?

ContentLicense: CC BY-SA 2.5


问:
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?

答:
Hash is not the unique solution for distributed VCS. But when deal with a distributed system, only the partial ordering of events can be recorded. (For VCS, the event can be a commit.) That is why maintain a monotonically increasing revision number is impossible. Usually we adopt something like vector clock (or vector timestamp) to record such partial-ordered relation. This is the solution used in Bazaar.

But why Git not uses vector clock but hash? I think the root cause is cherry-pick. When we perform cherry-pick on a repository, the partial ordering of commits is changing. Some commits' vector clocks must be re-assigned to represent the new partial ordering. However, such reassignment in distributed system would induce inconsistent vector clocks. That is the real problem which hashes deal with.


问:
Is JavaScript interpreted by design?
I am cautious of asking this question because it might appear overly fastidious. I just opened up JavaScript: The Definitive Guide, and it states of the first page of chapter 1

"JavaScript is a high-level, dynamic, untyped interpreted programming
  language”

So am I to take it that the interpreted part is a requirement in the language specification, or is it misleading to say that the language is an interpreted programming language when respecting the difference between a language and its many implementations?

There are no static compilers for JavaScript apparently -
https://stackoverflow.com/questions/1118138/is-there-a-native-machine-code-compiler-for-javascript so maybe it's just a reflection of this.

答:
The emergence of JIT compilers for script languages has blurred the line between compilation and interpretation to a point where the question doesn't mean all that much. Is it only interpretation when the engine reads a line of code and immediately executes it? (Shell scripts are still typically implemented this way.) Is it interpretation when the engine takes the whole file, immediately compiles it to some byte code, and then interprets the byte code? (The first-stage Mozilla engine works this way, as does CPython.) Is it interpretation when the engine parses a function at a time and JIT-compiles it to native code? What about those engines that compile the entire file to byte code, then JIT one function at a time as needed? (Most script engines these days work this way, and the main Java VM works this way too except that compiling to byte code happens ahead of time.)

There are many shades between compilation and interpretation.

I think the most useful definition for interpretation is "is fed the source code of the program at execution time, without a separate ahead-of-time step". By this definition, all the JavaScript engines are interpreters. But this is certainly not the only possible definition of interpretation.

But is JavaScript designed for interpretation? In a way, yes: it has an eval function as well as the Function constructor that you can give program code as a string which will be executed. The ability to dynamically construct program code at run time requires that the engine is capable of interpreting source code. But this doesn't mean that you can't make everything else ahead-of-time. Even in a compiled language like C++ and C# you can take source code, compile it in memory to new machine code and then execute that. There are even libraries for that: LLVM+Clang in C++ and the Roslyn project in C#.

Also, the delivery mechanism for JavaScript is source code; there is no recognized byte code form of it. C# and Java have their official byte code, and everyone expects C++ to be delivered as machine code. But this is still not an inherent aspect if the language, just a dominant usage scenario. In fact, JavaScript's close relative ActionScript in Flash is in fact delivered as byte code (the Flash compiler precompiles all scripts).

Title: Is JavaScript interpreted by design?


问:
How to avoid multiple calls to a REST API?
Suppose I have a REST API and I can fetch the list of my friends and the favorite songs of each friend in my list. Now I want to fetch all favorite songs of all my friends. The problem with REST API is that I can't do that just using only one request. I must make a request to get my friends and then do a request for each friend.

I have read about the framework that I don't remember the name that permit to do that in only one request.

Do you know an idea about the technology that can do that?

答:
Right now I am using Spring in order to handle the REST calls. It works with Java-Annotations and can also convert the objects you are returning to JSON on the fly.

I think it is pretty convenient to use so far and it works well in combination with Hibernate (ORM).

For example:

```<code>@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}
</code>```

Will give you the output:

```<code>{
    "id": 1,
    "content": "Hello, World!"
}
</code>```

But just take a look at this tutorial.

To avoid multiple calls you could just pass all necessary parameters in one call and simply return a list of friends and their songs. Processing large data is another thing Spring can do for you.

EDIT:

Reading over your question again I am not sure if what you wanted is a technology for REST calls or if you just need a powerful ORM tool. In that case, like mentioned before, Hibernate is a very powerful tool. It has its learning curve but I think it's worth it. If you go for Hibernate definitely take a look at this!

Body:
Right now I am using Spring in order to handle the REST calls. It works with Java-Annotations and can also convert the objects you are returning to JSON on the fly.

I think it is pretty convenient to use so far and it works well in combination with Hibernate (ORM).

For example:

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

Will give you the output:

{
    "id": 1,
    "content": "Hello, World!"
}

But just take a look at this tutorial.

To avoid multiple calls you could just pass all necessary parameters in one call and simply return a list of friends and their songs. Processing large data is another thing Spring can do for you.

EDIT:

Reading over your question again I am not sure if what you wanted is a technology for REST calls or if you just need a powerful ORM tool. In that case, like mentioned before, Hibernate is a very powerful tool. It has its learning curve but I think it's worth it. If you go for Hibernate definitely take a look at this!


问:
Modern.IE VM license
Microsoft provides some VMs for testing purposes (advertised on Stack Overflow) and I'm trying to understand the license terms. The one I don't really understand is

1.b. You may use the software for testing purposes only. You may not  use the software for commercial purposes.

My thoughts:

Testing a website in several browsers on several different virtual machines seems a quite professional approach. I hardly believe many private developers would do that. Of course they should, but which private developer has the time to do so?

If that's really only available to private developers, what is the offer to companies doing the same thing? I am missing the advertisement for a paid service.

Is testing by a company considered a commercial purpose? Can I use the VMs within a company for testing or not?

答:
We considered using these VMs at my workplace, and asked about using them.

Our internal Windows administrators checked and told us that "You may not use the software for commercial purposes." does indeed mean that you are not allowed to use it at all if you are a company, not even for testing purposes. I do not know where they obtained the information, but as they are responsible for our licensing, I see no reason not to trust them.

So the answer probably is:

No, a company may not use the VMs provided by http://modern.ie/ .

A company will have to obtain the appropriate number of Windows licenses, usually from their reseller. How to do this and how much it costs will depend on your contract with Microsoft.

Of course, as with all licensing questions, details depend on your jurisdictions. In some jurisdictions the restrictions in Microsoft's license may not be enforceable, so maybe you can still use them. For that you'd need some expert in copyright law.

Title: Modern.IE VM license


问:
What licence should I choose for my project?
I originally thought of creative commons when while reading a book about wordpress (professional wordpress), I learned that I should also specify that the product is provided

... WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE

and they recommend GNU GPL.  How do I write a license or select 1?

btw, what does MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE mean actually? Isn't without warranty enough?

答:
WTFPL - Do What The F*** You Want To Public License

```<code>       DO WHAT THE F*** YOU WANT TO PUBLIC LICENSE
                Version 2, December 2004
</code>```

Copyright (C) 2004 Sam Hocevar

Everyone is permitted to copy and distribute verbatim or modified
  copies of this license document,

  and changing it is allowed as long
  as the name is changed.

```<code>       DO WHAT THE F*** YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
</code>```

You just DO WHAT THE F*** YOU WANT TO.

Body:
WTFPL - Do What The F*** You Want To Public License

       DO WHAT THE F*** YOU WANT TO PUBLIC LICENSE
                Version 2, December 2004

Copyright (C) 2004 Sam Hocevar

Everyone is permitted to copy and distribute verbatim or modified
  copies of this license document,

  and changing it is allowed as long
  as the name is changed.

       DO WHAT THE F*** YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

You just DO WHAT THE F*** YOU WANT TO.


问:
What to do with abandoned issues in GitHub?
If someone opens an issue on GitHub but more information to reproduce the error is asked and never given, what's the normal procedure? Example.

Here the author states that the "nav breaks". While I believe it is fixed, I would like word from the author to make sure we were talking about the same thing. But sometimes the issue's reporter just disappears. Is it a good/common practice to set a expiration date for abandoned issues?

Something like these conditions:

A question is raised on the issue to be able to debug it.

Over 2-6 months have passed since the last unanswered question/comment from the dev team.

Bug cannot be reproduced at the time of closing it (for any reason, maybe they could never be reproduced).

A warning is issued 2 weeks before closing it.

What do projects normally do? I couldn't find anything on Google. Also, how would I document this? Does a simple note in the README.md detailing the points above and a comment in the issue explaining why it's being closed suffice?

Note: it's different from this question since the bug might still be relevant (or not), however there's lack of information.

答:
This is a dilemma: you cannot close the issue as "fixed", because you don't actually know if it was fixed, or at least even if some issue was fixed, you don't actually know whether this was the issue the reporter was talking about. On the other hand, you don't want to leave an issue that might have been fixed open, especially if you won't ever be able to close it because you'll never get confirmation.

So, you should close it, but probably not as "fixed". You could invent a custom close reason "maybefixed" or "unconfirmedfix" if you want to be positive or "reportervanished" if you don't. You could also just say "could not reproduce", and wait for the same bug to pop up for a more responsive reporter.

However, you should not expend resources on a bug for which you will never know whether it was actually fixed or not.


问:
Legitimate cases of having .equals() behaving inconsistently with .compareTo()?
Java documentation says it's "strongly recommended" to have them behaving consistently.

But are there legitimate cases of java/c#/python/etc Object.equals() method behaving inconsistently with the method Comparable.compareTo()?

答:
The "legitimate reason" for having equals() inconsistent with compareTo() is if they serve different real-world purposes.

Let's start with BigDecimal. If you're simply sorting a list of values, you probably don't care about scale. However, if you're checking for equality, what you're really checking is that the series of operations that led to this result are the same. To be honest, I'm surprised that the developers of BigDecimal did not choose to include rounding mode in their test for equality.

As another example, consider customer address entities stored in a database. You get cheaper postal rates if you sort addresses for mass mailings, so you might choose to base the natural ordering on the postal code and street address. However, even if two addresses are identical in all outward respects, they may not be equal, because a particular address belongs to a particular customer (and you'll get into all sorts of issues if you try to share them).

Those are two cases where equality requires a stronger guarantee than ordering. The reverse is possible although unlikely: I once implemented a system where I needed to ensure stable ordering of different instances, so added an additional test in comparison, such that different instances would never compare as 0. But I can't remember the details of that system, and can't come up with a good example on the spur of the moment.

As other people have said, you have to be careful when you use objects where equality and order are inconsistent. Personally, I prefer to implement a Comparator rather than have the classes be Comparable.


问:
Java: why do collections accept a Comparator but not (a hypothetical) Hasher and Equator?
This issue is most apparent when you have different implementations of an interface, and for the purposes of a particular collection you only care about the interface-level view of the objects. For example, suppose you had an interface like this:

```<code>public interface Person {
    int getId();
}
</code>```

The usual way to implement hashcode() and equals() in implementing classes would have code like this in the equals method:

```<code>if (getClass() != other.getClass()) {
    return false;
}
</code>```

This causes problems when you mix implementations of Person in a HashMap. If the HashMap only cares about the interface-level view of Person, then it could end up with duplicates that differ only in their implementing classes.

You could make this case work by using the same liberal equals() method for all the implementations, but then you run the risk of equals() doing the wrong thing in a different context (such as comparing two Persons that are backed by database records with version numbers).

My intuition tells me that equality should be defined per collection instead of per class. When using collections that rely on ordering, you can use a custom Comparator to pick the right ordering in each context. There is no analogue for hash-based collections. Why is this?

Just to clarify, this question is distinct from "Why is .compareTo() in an interface while .equals() is in a class in Java?" because it deals with the implementation of collections. compareTo() and equals()/hashcode() both suffer from the problem of universality when using collections: you can't pick different comparison functions for different collections. So for the purposes of this question, the inheritance hierarchy of an object doesn't matter at all; all that matters is whether the comparison function is defined per-object or per-collection.

答:
This design is sometimes known as "Universal Equality", it is the belief that whether two things are equal or not is a universal property.

What's more, equality is a property of two objects, but in OO, you always call a method on one single object, and that object gets to solely decide how to handle that method call. So, in a design like Java's, where equality is a property of one of the two objects being compared, it isn't even possible to guarantee some basic properties of equality such as symmetry (a == b ⇔ b == a), because in the first case, the method is being called on a and in the second case it is being called on b and due to the basic principles of OO, it is solely a's decision (in the first case) or b's decision (in the second case) whether or not it considers itself equal to the other one. The only way to gain symmetry is to have the two objects cooperate, but if they don't… tough luck.

One solution would be to make equality not a property of one object, but either a property of two objects, or a property of a third object. That latter option also solves the problem of universal equality, because if you make equality a property of a third "context" object, then you can imagine having different EqualityComparer objects for different contexts.

This is the design chosen for Haskell, for example, with the Eq typeclass. It is also the design chosen by some third-party Scala libraries (ScalaZ, for example), but not the Scala core or standard library, which uses universal equality for compatibility with the underlying host platform.

It is, interestingly, also the design chosen with Java's Comparable/Comparator interfaces. The designers of Java clearly were aware of the problem, but for some reason only solved it for ordering, but not for equality (or hashing).

So, as to the question

why is there a Comparator interface but no Hasher and Equator?

the answer is "I don't know". Clearly, the designers of Java were aware of the problem, as evidenced by the existence of Comparator, but they obviously didn't think it a problem for equality and hashing. Other languages and libraries make different choices.


问:
Pre-Processors vs Pure Web
It seems like within the last few years or so HTML/CSS/JavaScript Preprocessors have exploded in quantity and general use. They're still not as common as pure HTML, CSS, and JS/jQuery, but their overall popularity seems to be growing if sites like CodePen are any indication. After reading up on tutorials for Haml, Jade, SASS, Coffeescript, etc. I'm honestly slightly confused. They all have benefits, understandably, but really they seem like very short-sighted languages. With the exception of SASS/SCSS it seems like simple things like creating div tags in an HTML preprocessor or adding events in a JS preprocessor are made very, very simple, but then when you get into more complex functions or template creation, they become even more complex than the languages they're processing for.

All in all without the innate browser support that I doubt any of these preprocs will get none of the languages, to me, feel like they are in the running to fully succeed anywhere outside of their established user base. My issue is that I don't even see a benefit to really digging into any of the preproc languages. Using them I could make a website from the early millenium pretty easily, but really if I need to create a modern site it seems to be a waste of time to get in the know with any of them whereas I could just code it out with HTML/CSS/JS(JQuery).

My question is - Am I missing something in the larger scope of it all? What are the benefits to using these preproc'd languages, especially given the fact that they're not browser supported? As a web developer is it worth it to spend time to learn any of them?

答:
The overarching theme of your question seems to be succinctly summed up in the last paragraph: "What are the benefits to using these preproc'd languages, especially given the fact that they're not browser supported?"

What's fantastic about preprocessors is that they don't need to be supported by the browsers. They are taking the non-native-web input and then transforming it into something that the browser understands.

Why not use vanilla HTML, CSS, and JavaScript? The simple answer is to save you time. That's why preprocessors exist.

Some may save you time by creating fallbacks for older browsers automatically. Some may save you time by creating a more maintainable structure than HTML, CSS, or JavaScript alone. Some may save you time by checking for errors when you compile.

Sure, these preprocessors each have smaller user bases than the core technologies of the web. But that's ok. You are making websites for end users on the internet to see, not just for those who know Sass. At the end of the day, after all the preprocessing, it is only HTML, CSS, and JavaScript at the end.

Also, don't feel like you have to lump them all together - some preprocessors are great, some are not as great, some probably suck.

Pick the ones that make sense for you and your projects.

Title: Pre-Processors vs Pure Web


答:
There is no totally agreed upon definition of 'interpreted' versus 'compiled'. In the classic distinction, compiled languages produce a stand-alone binary executable, while interpreted languages requires a deployed runtime to execute the code. Virtual machines, bytecode and so on blurs the distinction.

But here is a possibly useful definition: An interpreted language is a language where the standard language runtime is able to take source code text as input and execute it. By that definition Perl, Python, Ruby, JavaScript and shell scripts and the like are interpreted (even if they use intermediate steps like bytecode or even native code). Java, C#, C etc. are not. And JavaScript is by definition interpreted, even if the spec does not use the exact word.

Title: Is JavaScript interpreted by design?

Body:
I am cautious of asking this question because it might appear overly fastidious. I just opened up JavaScript: The Definitive Guide, and it states of the first page of chapter 1

"JavaScript is a high-level, dynamic, untyped interpreted programming
  language”

So am I to take it that the interpreted part is a requirement in the language specification, or is it misleading to say that the language is an interpreted programming language when respecting the difference between a language and its many implementations?

There are no static compilers for JavaScript apparently -
https://stackoverflow.com/questions/1118138/is-there-a-native-machine-code-compiler-for-javascript so maybe it's just a reflection of this.


答:
Your main question was already answered, but you also asked about documenting the process and that needs answering too.

The solution I've seen in many projects is not to put it in the project's README.md, but in a special contribution README - a README file for contributors. This file describes everything you want the people contributing to your project to know - be it about the code(naming conventions, module organization etc.) or about the process(how to write commits, how to handle tickets etc.). This file can be another .MD file in the project, or placed in an entirely different repository(so it can be shared among all your projects). Just don't forget to link to it from the main README.md!

The point of separating that information from the main README is that usually only a fraction of the project's user directly contribute to it. Most of the users don't need to be bored with that information - they just need to know what your project does and how to use it, and that's what the main README should contain. In your project's case the contribution section is very small so it doesn't encumber the main README - but if you document all the workflows you want contributers to follow it won't fit there as nicely anymore...

Note that any user can open a bug, so if you have special requirements about bug opening you should put them in the main README(try to keep it shourt though - unlike code contributers, bug reporters will probably be less willing to go to great lengths to study and conform to your rules). However, the person that actually fixes the bug and closes the ticket(be it you or one of the contributers you have confirmed) is a direct contributer and can be expected to read the contribution README - so the process of closing tickets when the reporter does not respond should be described there.

Title: What to do with abandoned issues in GitHub?

Body:
If someone opens an issue on GitHub but more information to reproduce the error is asked and never given, what's the normal procedure? Example.

Here the author states that the "nav breaks". While I believe it is fixed, I would like word from the author to make sure we were talking about the same thing. But sometimes the issue's reporter just disappears. Is it a good/common practice to set a expiration date for abandoned issues?

Something like these conditions:

A question is raised on the issue to be able to debug it.

Over 2-6 months have passed since the last unanswered question/comment from the dev team.

Bug cannot be reproduced at the time of closing it (for any reason, maybe they could never be reproduced).

A warning is issued 2 weeks before closing it.

What do projects normally do? I couldn't find anything on Google. Also, how would I document this? Does a simple note in the README.md detailing the points above and a comment in the issue explaining why it's being closed suffice?

Note: it's different from this question since the bug might still be relevant (or not), however there's lack of information.


答:
I read this as more a question about the practices around how to handle an unverified bug (using github's issue tracker) than anything else.

To me, that is a rather straight forward answer based on other issue trackers I have used.  Github doesn't force anyone to use any workflow and this makes it very flexible... and rather useless in its default configuration.

Looking at Bugzilla's default workflow we get:

I'm going to point out a very important thing there - it gets resolved as fixed before it gets closed after being verified.  The basic Github workflow shows only the red (open) and green (closed) states.

Thus, one approach is use the labels within Github (your application's labels) to try to show the additional information. You can create a pair of labels that are 'unverified' and 'verified' to be applied once you close the issue.  Note that this is only one approach - if you search you can find dozens of different approaches to the use of labels.  Here, the question How to manage github issues for (priority, etc)? addresses this.

You have fixed it, from a developer's standpoint it is done. Close the issue on Github. Apply the 'unverified' label to it. Once someone familiar with the bug in the previous version says "yes, this fixed it" you can change the label to 'verified'.  If they say it didn't, then you reopen it.

Note also that there are other resolved states besides 'fixed'.  There is 'wontfix' (the fix is something that just can't be done with the current structure) and 'worksforme' (the bug can't be reproduced) and 'invalid' (you are filing a bug about the OS, not the application type things).


问:
How to know if an app is launched in windows service application
I'm trying to write a program which waits for a specific app (matlab in my case) to launch and does stuff when the app launches.

I see that I had to write a windows service application and managed get this working. I can see the service in Service Manager and can start-stop it. But I don't know how can "listen" or understand if Matlab (or any other app.) is launched. I'm  kinda newbie when it comes to Windows Programming. Can you help me in this?

I'm using c++ with visual studio 2013.

答:
I believe this answer on Stack Overflow may help.

https://stackoverflow.com/questions/1591342/c-how-to-determine-if-a-windows-process-is-running

You just need to know what the process name is for Matlab.

Also, just Google:

"windows check if process is running c++"


问:
Is Collection.stream().filter().forEach() inefficient compared to a standard for each loop?
IntelliJ IDEA recommended to me just now to replace the following for-each loop with a Java 8 "forEach" call:

```<code>    for (Object o : objects) {
        if (o instanceof SomeObject) {
            doSomething();
        }
    }
</code>```

The recommended call would like like this:

```<code>objects.stream().filter(o -> o instanceof SomeObject).forEach(o -> doSomething());
</code>```

Unless I'm misunderstanding how the underlying functionality of Stream works, it seems to me like using stream is an O(2n) operation as opposed to an O(n) operation for the standard for-each loop.

答:
Java streams do not iterate through your collection once for each statement, despite what the syntax implies. It applies the entire chain to each element, one element at a time.

In your case, the stream would operate exactly like the loop. Take an element, check it against your predicate, and then apply your operation, then move on to the next element.


答:
I would take one of two views, depending how confident I was that I was talking about the same thing as the original reporter:

1) Since the reporter is no longer available, deem that the bug in question means whatever it was you fixed. If it helps, attach test cases to make clear what failures you found. Describe in detail on the bug report what it was you fixed and leave a note like, "I believe this is what 'nav breaks' means, please reopen or raise a new bug if that's not what you meant". Mark the bug as fixed.

2) Since the reporter is no longer available, deem that the bug cannot be (known to be) reproduced, since only the reporter's word for it would confirm it's the same thing they reported. Raise a new bug to describe the thing you fixed, for the sake of credit mention that it was observed under the conditions described by the absent reporter, note on both that they may be duplicates, mark the new bug fixed and mark this one invalid or not reproducible with a note like, "I can't work out what you meant by 'nav breaks', but I've solved the problem that I did find. Please reopen or raise a new bug if the nav still breaks, describing in more detail what goes wrong".

As for timescale, I think it should depend on the project. If you are very responsive, and are dealing with this bug within days of it being raised, then people should understand that you won't wait weeks for a response before resolving the issue. On the other hand, if it's been on your slushpile for months then it can sit open for another month or two without causing you any trouble.

For this reason I don't think there's one particular time limit that constitutes "good practice", or that you need to publish your policy and stick to it. Certainly you wouldn't want to record that the reporter can't be contacted until you've made an effort to contact them. But I also don't see any point leaving multiple warnings counting down to a deadline: either they'll revisit the bug and want to say something, or they won't.


问:
How do I model this relationship so that it is valid by construction?
Imagine a device class that represents a physical real world mobile device, with fields like Enabled, Platform, Model IMEI, etc. Then, an operation class, which is something that needs to be done to a certain device, like DeviceEnablementOperation or LockOperation. This is a 'one device to many operations' relationship, and an operation cannot exist without being related to an existing device. Can I model this in such a way that the system will not allow certain types of operations to devices with certain platforms? For example, an Android device would not allow a DeviceEnablementOperation attached to it, while a Windows Phone device would.

Our current modeling started out considering only Android devices. At the time, we created the concept of operations as a poor man's event source, so that we could track what was done against a certain device via our API. Later on, we started supporting iOS devices too, and we introduced the Platform field using an enumeration class to differentiate them, like this:

public enum PlatformType : short
{
    ///
    /// Device is an Android.
    ///
    Android = 0,

    ///
    /// Device is an Windows platform.
    ///
    Windows = 1,

    //// Can not place the name iOS.

    ///
    /// Device is an iOS platform.
    ///
    Ios = 2,
}
```

<p>At that point in time, the requirements were being met correctly, but now we need to restrict certain types of operations to certain platforms. The current model does not automatically restrict this, so the current implementation considers a hardcoded list of supported operations for each platform, and uses this to reject the creation of some operations to certain devices.</p>

<p>What I'd like to do is change the modelling so that this restriction is more robustly enforced. I thought about using inheritance and creating <code>AndroidDevice</code>, <code>IosDevice</code> and <code>WindowsPhoneDevice</code> classes, but I still fail to see how I could restrict the relationship with operations themselves to cover this requirement. A device has operations, but not all devices support all operations.</p>

<p>The modelling for the operations themselves is very straightforward inheritance, like this:</p>

<pre class="lang-cs prettyprint-override"><code>public abstract class Operation
{
    protected Operation()
    {
        this.Logs = new List<OperationLog>();
    }

    public DateTime? CreationDate { get; set; }

    public virtual Device Device { get; set; }

    public int DeviceId { get; set; }

    public OperationStatus GeneralStatus { get; set; }

    public int Id { get; set; }

    public DateTime? LastUpdate { get; set; }

    public ICollection<OperationLog> Logs { get; internal set; }

    public DateTime? ReceiveDate { get; set; }
}
</code>```

And then derived operation types, like the ones I mentioned:

public sealed class LockOperation : Operation
{
    ///
    /// Gets or sets a value indicating whether the device must be locked or not.
    ///
    public bool Lock { get; set; }

    ///
    /// Gets or sets the device's lock password.
    ///
    public string Password { get; set; }
}
```

<p>and</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class EnablementOperation : Operation
{
    /// <summary>
    /// Gets or sets a value indicating whether the device should be enabled or disabled.
    /// </summary>
    public bool Enabled { get; set; }
}
</code>```

Is it possible to model this to better reflect the new requirement that I want? I'd somehow need a way to tell if a given operation is supported for a given device, and only allow the relationship to exist if the operation was supported.

I suppose I could try something using generics and inheritance on both the device and operation classes, for example:

public abstract class Device<TOperation>
{
    public ICollection<TOperation> Operations { get; set; }
    ...
}

public sealed class AndroidDevice : Device<AndroidOperation> {...}

public abstract class Operation {...}

public abstract class AndroidOperation {...}

public sealed LockOperation : AndroidOperation {...}
```

But this particular approach would need multiple inheritance to work, and since I'm using C# it is not possible. I could then try using interfaces to differentiate operations, but them I suspect it would be a problem when mapping this to a database later using an ORM.

I also can't really break everything into their own completely isolated classes, because I need the general concept of "devices that have operations", regardless of platform or operation type. That's why the base classes exist in our current model.

答:
I think interfaces in the form of the wrapper pattern are the way to go.

If you have an IPlatform interface and IAndroid, IOS (pun intended), etc. that extend it, you can write operations as wrapper objects following the wrapepr pattern.

Disclaimer: this is pseudo code, it's been too long since I did C#, you get the idea

Here's an operation that works on all devices.

```<code>class BreakDisplayOperation implements IPlatform {

BreakDisplayOperation (IPlatform platform) { // this is the  constructor
</code>```

One that only works on IWindows as in your .

```<code>class DeviceEnablementOperation implements IWindows {

DeviceEnablementOperation (IWindows platform) { // constructor
</code>```

The idea behind this is to delegate all method calls of the interface to the object received in the constructor, except for those that you want to manipulate by the operation.

IWindows (or IPlatform) probably includes a getter method for enable

```<code>bool isEnabled(); // or do this via get keyword, which C# has, if I remember correctly.
</code>```

DeviceEnablementOperation overrides this method an returns a value it defines itself, instead of receiving that value by delegating the call to the wrapped IWindows object, like so

class DeviceEnablementOperation implements IWindows {

```<code>bool isEnabled()
{
    return true;
}
</code>```

}

again, other things that are not manipulated by the operation are just delegated to the wrapepd object (assuming a member with same name as the constructor parameter:

```<code>class DeviceEnablementOperation implements IWindows {

    bool isEnabled() // modified
    {
        return true;
    }

    IMEI getIMEI() // delegated
    {
        return platform.getIMEI()
    }
}
</code>```

In the above examples, you'd have to do the delegation for all Operations again and again. To avoid this boilerplate, create super classes that do all delegations, then each specific Operation can override methods as necessary.

This all works because the interface inheritance branches, making individual platforms incompatible types because they are siblings in the hierarchy.

I know this abstracts the problem in a different way as you are currently doing it. It's a bit like Platform, Device and Operation all merge into the same thing.

You can apply many operations by wrapping the wrappers.

To get a list of all operations, add the getOperations(); method.

The super class of all Platforms will return a new empty list object. The super class of all Operations will again delegate that call to the wrapped object (which will eventually be a Platform), add itself to the list and return the list. (for possible other wrappers to ad themselves)

The problems of this approach:

somebody could implement both interface to merge them, breakign the separation

an IPlatform wrapper will be of that type, to use a specific wrapper again, a cast is necessary. You can work around this by duplicating the general purpose wrappers specifically typed for each platform. Not sure if generics could help you with this, but I have the feeling they do.

Body:
I think interfaces in the form of the wrapper pattern are the way to go.

If you have an IPlatform interface and IAndroid, IOS (pun intended), etc. that extend it, you can write operations as wrapper objects following the wrapepr pattern.

Disclaimer: this is pseudo code, it's been too long since I did C#, you get the idea

Here's an operation that works on all devices.

class BreakDisplayOperation implements IPlatform {

BreakDisplayOperation (IPlatform platform) { // this is the  constructor

One that only works on IWindows as in your .

class DeviceEnablementOperation implements IWindows {

DeviceEnablementOperation (IWindows platform) { // constructor

The idea behind this is to delegate all method calls of the interface to the object received in the constructor, except for those that you want to manipulate by the operation.

IWindows (or IPlatform) probably includes a getter method for enable

bool isEnabled(); // or do this via get keyword, which C# has, if I remember correctly.

DeviceEnablementOperation overrides this method an returns a value it defines itself, instead of receiving that value by delegating the call to the wrapped IWindows object, like so

class DeviceEnablementOperation implements IWindows {

bool isEnabled()
{
    return true;
}

}

again, other things that are not manipulated by the operation are just delegated to the wrapepd object (assuming a member with same name as the constructor parameter:

class DeviceEnablementOperation implements IWindows {

    bool isEnabled() // modified
    {
        return true;
    }

    IMEI getIMEI() // delegated
    {
        return platform.getIMEI()
    }
}

In the above examples, you'd have to do the delegation for all Operations again and again. To avoid this boilerplate, create super classes that do all delegations, then each specific Operation can override methods as necessary.

This all works because the interface inheritance branches, making individual platforms incompatible types because they are siblings in the hierarchy.

I know this abstracts the problem in a different way as you are currently doing it. It's a bit like Platform, Device and Operation all merge into the same thing.

You can apply many operations by wrapping the wrappers.

To get a list of all operations, add the getOperations(); method.

The super class of all Platforms will return a new empty list object. The super class of all Operations will again delegate that call to the wrapped object (which will eventually be a Platform), add itself to the list and return the list. (for possible other wrappers to ad themselves)

The problems of this approach:

somebody could implement both interface to merge them, breakign the separation

an IPlatform wrapper will be of that type, to use a specific wrapper again, a cast is necessary. You can work around this by duplicating the general purpose wrappers specifically typed for each platform. Not sure if generics could help you with this, but I have the feeling they do.


问:
is copyright string in gpl'ed program guarded from modification?
is copyright string in gpl'ed program guarded from modification, by gpl or by laws? for example, is it possible to change "2001-2010" to "2010 to 2010"? or maybe change spelling of copyright holder name or translate copyright holder name or the word "copyright" to other language? or remove additional info that is not copyright notice itself, for example, names of authors or sponsors, if there is any, and leave only copyright info? or add some additional words like "modified by"?</p>

答:
The copyright string is not part of the license.  If you read How to Use GNU Licenses for your own software, you will see that the copyright string is something that is added to each source file by the author.

The process involves adding two elements to each source file of your program: a copyright notice (such as “Copyright 1999 Terry Jones”), and a statement of copying permission, saying that the program is distributed under the terms of the GNU General Public License

If you have copied code from other programs covered by the same license, copy their copyright notices too. Put all the copyright notices together, right near the top of each file.

Changing someone else's copyright provision would be tantamount to fraud.  You can't do it anywhere else, so I don't see why you would be able to do it when applying the GPL.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答: Clean up "User Contributed Notes" on http://php.net. They are a real mess sometimes, while being a great value in general.</p>


问:
Is storing data directly in a list node better than storing a pointer to data?
Suppose we have two different doubly-linked list structures:

One has content of the node embedded directly in the node:

```<code>struct Content {
    // some stuff
};
struct Node {
    struct Node *next;
    struct Node *prev;
    struct Content content;
}
</code>```

The other has a pointer to content:

```<code>struct Content;
struct Node {
    struct Node *next;
    struct Node *prev;
    struct Content *content;
}
</code>```

What are considerations to prefer one option to the other? The points can be about everything: performance in different conditions, architecture, ease of modification, ease of manipulating the list, etc.

I'd like to gather knowledge about the trade-offs present.

Shown code is C, but the question also applies to C++, or any other language which has explicit pointers.

答:
I think it would be rare in practice to actually have the option. The decision will likely be made for you simply by the requirements of the application. The semantics of your two examples are very different. It's a typical by-value or by-reference decision. I think you just need to ask

```<code>Content myContent;
myContent.Value = "Some content";

Node myNode;
myNode.Content = myContent; // or myNode.Content = &myContent;
myNode.Content.Value = "Different content";
</code>```

At this point, what would you expect myContent.Value to be? Should changing the value in the list change the original object?

Body:
I think it would be rare in practice to actually have the option. The decision will likely be made for you simply by the requirements of the application. The semantics of your two examples are very different. It's a typical by-value or by-reference decision. I think you just need to ask

Content myContent;
myContent.Value = "Some content";

Node myNode;
myNode.Content = myContent; // or myNode.Content = &myContent;
myNode.Content.Value = "Different content";

At this point, what would you expect myContent.Value to be? Should changing the value in the list change the original object?


问:
Why is .compareTo() in an interface while .equals() is in a class in Java?
I want to know why the .compareTo() is in the Comparable interface while a method like .equals is in the Object class. To me, it seems arbitrary why a method like .compareTo() is not in the Object class already.

To use .compareTo(), you implement the Comparable interface and implement the .compareTo() method for your purposes. For the .equals() method, you simply override the method in your class, since all classes inherit from the Object class.

My question is why is a method like .compareTo() in an interface that you implement rather than in a class like Object? Likewise, why is the .equals() method in the class Object and not in some interface to be implemented?

答:
Suppose I have two object references: X identifies an instance of String holding the content "George"; Y identifies instance of Point holding the coordinates [12,34].  Consider the following two questions:

Do X and Y identify equivalent objects?

Should X sort before, after, or equivalent to Y?

The fact that X and Y identify instances of unrelated types does not pose any problem when considering the first question.  Objects can only be considered equivalent if their types share a common base that defines them as being equivalent; since String and Point have no such base (their only common base type regards all distinct objects as non-equivalent) the answer is simply "no".

The fact that the types are unrelated, however, poses a huge problem with regard to the second question.  Some types define ordering relationships among their instances, and some ordering relationships may even extend over multiple types [e.g. it would be possible for BigInteger and BigDecimal to define comparison methods that would allow instances of either type to be ranked relative to instances of the other], but it is not possible in general to take two arbitrary instances and ask "Should X sort before, after, or equivalent to Y" and derive a total ordering.  It would be possible to ask "Should X sort before, after, equivalent, or unranked with respect to Y" if objects were required to report a consistent ordering though not a total one, but most sorting algorithms require total orderings.  Thus, even if all objects could implement a compareTo method if "unranked" was a valid return, such a method wouldn't be useful enough to justify its existence.


问:
Are the default objects of VB a type of singleton?
Are the default objects supported by My keyword in VB.net is a kind of singleton? If not, what is the difference?

Again is this "default object" feature is something useful? If yes, then why it is not implemented in other languages like C#?

答:
It is not a Singleton.

My is just a namespace containing static classes, methods and properties that point to other parts of the .NET framework, and provide some additional capabilities (e.g. CopyDirectory)  Think of it as a set of shortcuts, a speed-dial of sorts.

Visual Basic provides language/compiler support with the My keyword.  You can use the My classes in C# by adding a reference to Microsoft.VisualBasic.dll, but it is awkward, and not all classes are compatible with C# (they are VB specific).  In C#, unless you want some of the VB capabilities (like "CopyDirectory"), it is more convenient to just reference the .NET framework classes directly, IMO.

Visual Basic has a somewhat different language philosophy than C# does.  Originally, VB was to be the "applications" language, and C# was to be the "systems" language.  Since then, the two languages have converged, and the feature sets of the two are almost indistinguishable, with a few notable differences (this being one, XML Literals being another).

I am quite certain that, if you asked Eric Lippert or one of the other members of the C# compiler team, they would tell you that implementing new features is a tug-of-war between available resources and feature importance, and that this particular feature just never hit threshold.

Navigate The .NET Framework And Your Projects With The My Namespace

http://msdn.microsoft.com/en-us/magazine/cc163680.aspx

My Namespace
 http://msdn.microsoft.com/en-us/vbasic/ms789188


问:
Yoda conditions: if you use more than one language?
Ive started coding for Wordpress and the coding standards recommend using Yoda conditions.

```<code>if ( true == $the_force ) {
    $victorious = you_will( $be );
}
</code>```

But I also do some Android development, Javascript and have plans for robotics programming and some languages don't like Yoda style.

Im planning NOT to use Yoda conditions for WP for the sake of consistency, I dont know if its going to cause any problems.

答:
Unless you are an extremely error-prone programmer with no code reviewers or automated linters to back you up, this particular choice is unlikely to be anything other than a stylistic preference with potentially minor benefits, so go right ahead.

It's worth noting that coding styles shouldn't necessarily be similar across languages. The most important rules in a coding style are generally motivated by how the language actually works (eg, in Javascript use === not ==), so they won't apply to other languages. However, there are rules that can be sanely applied to multiple languages, and those are usually the "cosmetic" choices like indentation, brace style, or whether or not to use yoda conditions.


答:
Coding standards are there to make it easy to visually parse the code. They are often different for each language, and rightly so.

If someone else is going to read this code, then keep to the Wordpress conventions when programming for Wordpress. If you are the only person who will read the code, then do what makes it easiest for you.

Personally, I wouldn't bother trying to keep the coding conventions for all of your projects consistent. I would keep the coding conventions for your projects in a particular language consistent.

The primary reason for this is that it will make it easier to get used to switching between coding standards, as it is almost certain that the various projects you will work on during your career will not use identical styles.

Title: Yoda conditions: if you use more than one language?

Body:
Ive started coding for Wordpress and the coding standards recommend using Yoda conditions.

```<code>if ( true == $the_force ) {
    $victorious = you_will( $be );
}
</code>```

But I also do some Android development, Javascript and have plans for robotics programming and some languages don't like Yoda style.

Im planning NOT to use Yoda conditions for WP for the sake of consistency, I dont know if its going to cause any problems.


问:
Alternative to using getters/setters in a simple class
I'm writing a minesweeper game with curses. To represent each tile, I wrote small Tile class that contains information about the possible state of each tile (whether or not it's flagged, whether or not it has a bomb under it, and whether or not it's "hidden"). This is the interface so far:

```<code>class Tile {
    bool hidden;
    bool containsBomb;
    bool hasFlag;

public:
    Tile(bool startWithBomb, bool startHidden = true);

    bool isHidden() const;
    void makeHidden();
    void unhide();

    bool hasBomb() const;
    void placeBomb();
    void removeBomb();

    bool hasFlag() const;
    void placeFlag();
    void removeFlag();

};
</code>```

I could have made the setters for each a single function, but I think them being separate will lead to more readable code (tile.setFlag(false) vs tile.removeFlag())

My problem is, this can potentially lead to "bad states". An unhidden tile shouldn't be able to contain a flag for example.

I was reading over this post, and several users "bash" using getters/setters; with good reasons.

My question is: Before I get farther in designing this class, is there a better way to set this up to avoid using generic getter/setters for each private flag?

答:
Yes, having exactly one getter/setter pair per private flag is a code smell. If you aren't providing a simple interface to hide some implementation details, you're not benefiting very much from using a class.

My main concrete suggestion would be to represent the internal state in a way that makes "bad states" theoretically impossible. For instance:

```<code>class Tile {
    enum DisplayState { DEFAULT, FLAGGED, KNOWN_EMPTY };
    DisplayState displayState;
    bool containsBomb;
    ...
};
</code>```

Notice that containsBomb can be true or false in any of the three states, so it makes sense to keep that member separate. It's up to you whether things like calling removeFlag() on a KNOWN_EMPTY tile should throw an exception or simply do nothing.

Now the big-picture issue. If the part of the code that uses Tile objects really does need all of these methods, i.e. full access to and control of the Tile's entire state, then it's not really clear how you benefit from making Tile a class (as opposed to a POD struct) in the first place. Perhaps it would be better to have a Board class with a few 2D arrays of booleans to represent all the flags/bombs/etc, since that class would be able to hide a lot of iteration logic from its users. I can't say for sure if that'd be an improvement without reading all of your code, but hopefully that helps.

Body:
Yes, having exactly one getter/setter pair per private flag is a code smell. If you aren't providing a simple interface to hide some implementation details, you're not benefiting very much from using a class.

My main concrete suggestion would be to represent the internal state in a way that makes "bad states" theoretically impossible. For instance:

class Tile {
    enum DisplayState { DEFAULT, FLAGGED, KNOWN_EMPTY };
    DisplayState displayState;
    bool containsBomb;
    ...
};

Notice that containsBomb can be true or false in any of the three states, so it makes sense to keep that member separate. It's up to you whether things like calling removeFlag() on a KNOWN_EMPTY tile should throw an exception or simply do nothing.

Now the big-picture issue. If the part of the code that uses Tile objects really does need all of these methods, i.e. full access to and control of the Tile's entire state, then it's not really clear how you benefit from making Tile a class (as opposed to a POD struct) in the first place. Perhaps it would be better to have a Board class with a few 2D arrays of booleans to represent all the flags/bombs/etc, since that class would be able to hide a lot of iteration logic from its users. I can't say for sure if that'd be an improvement without reading all of your code, but hopefully that helps.


答:
But are there legitimate cases of java/c#/python/etc Object.equals() method behaving inconsistently with the method Comparable.compareTo()?

Yes, for example, here is a legitimate case in Python 2.x. The float value for NaN does not compare equal (==) to itself, yet cmp() (equivalent to compareTo) will return 0 (equal), which is inconsistent with the result of ==:

```<code>>>> x = float('nan')
>>> x == x
False
>>> cmp(x, x)
0
</code>```

(Note: cmp() was removed in Python 3; that's why I specified Python 2.x only.)

NaN is kind of a special case in most languages, because IEEE 754 defines NaN as not equal to itself, something which is not true for basically any other value encountered in programming.

Interestingly, Java and C# do not have this inconsistency. Even though NaN in the primitive type double is not equal to itself using the primitive equality operator, the equals method of Double objects will test NaN equal to itself, to preserve consistency with compareTo and to allow use as keys in dictionaries. So they opted to make primitive equality and equals inconsistent, rather than make equals and compareTo inconssitent.

Ruby also does not have this inconsistency. NaN compared to itself with the <=> operator returns nil (incomparable). So they avoided the inconsistency by restricting comparability to a subset of numbers.

Title: Legitimate cases of having .equals() behaving inconsistently with .compareTo()?

Body:
Java documentation says it's "strongly recommended" to have them behaving consistently.

But are there legitimate cases of java/c#/python/etc Object.equals() method behaving inconsistently with the method Comparable.compareTo()?

Body:
But are there legitimate cases of java/c#/python/etc Object.equals() method behaving inconsistently with the method Comparable.compareTo()?

Yes, for example, here is a legitimate case in Python 2.x. The float value for NaN does not compare equal (==) to itself, yet cmp() (equivalent to compareTo) will return 0 (equal), which is inconsistent with the result of ==:

>>> x = float('nan')
>>> x == x
False
>>> cmp(x, x)
0

(Note: cmp() was removed in Python 3; that's why I specified Python 2.x only.)

NaN is kind of a special case in most languages, because IEEE 754 defines NaN as not equal to itself, something which is not true for basically any other value encountered in programming.

Interestingly, Java and C# do not have this inconsistency. Even though NaN in the primitive type double is not equal to itself using the primitive equality operator, the equals method of Double objects will test NaN equal to itself, to preserve consistency with compareTo and to allow use as keys in dictionaries. So they opted to make primitive equality and equals inconsistent, rather than make equals and compareTo inconssitent.

Ruby also does not have this inconsistency. NaN compared to itself with the <=> operator returns nil (incomparable). So they avoided the inconsistency by restricting comparability to a subset of numbers.


答:
My problem is, this can potentially lead to "bad states".

The opposite is true: The setter allows you to prevent "bad states".
You are the one to define the behaviour of the state machine, by specifying what happens when one variable changes.

An unhidden tile shouldn't be able to contain a flag for example.

Therefore, calling unhide() should set hasFlag to false and placeFlag() should only set hasFlag to true if hidden is true.

There is no such thing as a "bad state" because you should define your state machine well and handle every case. These setters are just the implementation of that state machine.

Reaching a "bad state" is a flaw in the transfer function.

Title: Alternative to using getters/setters in a simple class

Body:
I'm writing a minesweeper game with curses. To represent each tile, I wrote small Tile class that contains information about the possible state of each tile (whether or not it's flagged, whether or not it has a bomb under it, and whether or not it's "hidden"). This is the interface so far:

```<code>class Tile {
    bool hidden;
    bool containsBomb;
    bool hasFlag;

public:
    Tile(bool startWithBomb, bool startHidden = true);

    bool isHidden() const;
    void makeHidden();
    void unhide();

    bool hasBomb() const;
    void placeBomb();
    void removeBomb();

    bool hasFlag() const;
    void placeFlag();
    void removeFlag();

};
</code>```

I could have made the setters for each a single function, but I think them being separate will lead to more readable code (tile.setFlag(false) vs tile.removeFlag())

My problem is, this can potentially lead to "bad states". An unhidden tile shouldn't be able to contain a flag for example.

I was reading over this post, and several users "bash" using getters/setters; with good reasons.

My question is: Before I get farther in designing this class, is there a better way to set this up to avoid using generic getter/setters for each private flag?


问:
Development and testing PHP script that gets variables from external server
I have a web app that sends users to an offsite payment server to complete a transaction, and I'm working on the PHP page that users are returned to upon completion of the transaction. The script uses a lot of variables that are set by the external server, and I'm wondering what are the best practices for testing my script without having to actually go through doing a live transaction.

Do I include a file that sets all those variables to dummy values? Or just set those variables at the beginning of the script? (And then hopefully remember to remove this stuff before putting the script on production.)

答:
It sounds very much like Paypal payments are processed. Paypal allows for sandbox accounts purely for testing purposes.

Here is the link to Paypal testing guide

I heard good things about it from my friends.


问:
Why Should I Avoid Inline Scripting?
A knowledgeable friend recently looked at a website I helped launch, and commented something like "very cool site, shame about the inline scripting in the source code".

I'm definitely in a position to remove the inline scripting where it occurs; I'm vaguely aware that it's "a bad thing".  My question is: what are the real problems with inline scripting?  Is there a significant performance issue, or is it mostly just a matter of good style?  Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?  If you pulled up to a website, and took a peek at the source code, what factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

Okay, that question turned into multiple questions in the writing.  But basically, inline scripting - what's the deal?

答: One reason NOT to use InLine Javascript (not even onclick="DoThis(this)" on buttons), is if you intend to make your web application a Chrome App. So, if you are planning to port your web app into a Native Chrome App, start by NOT including ANY inline javascript. This is explained right at the beginning of what you will need to change (mandatorily) from your web app if you intend to "Chrome-etize" it.</p>

Title: Why Should I Avoid Inline Scripting?


问:
Polymorphism on repository interface for local and remote operations
I'm in the process of designing a facade ApiClient class that would abstract some CRUD operations between a local database and a remote one (through a REST web app).

Said ApiClient class depends on 2 other implementation classes (let's call them local repo and remote repo, whose responsibilities are to interact with the local database driver and with an http client, respectively.

That being said, some resources (let's call it ResourceA) are to be saved locally after being retrieved from the network, but it cannot be saved TO the network. An example of this would be the retrieval of a list of ResourceA and save each item locally, but there is no creation of ResourceA nor update it to the server-side.

Up to this point, the local repo should implement a save(ResourceA) operation, but remote repo shouldn't.

So the question is: should those 2 classes be an implementation of 2 different interfaces (local repo interface and remote repo interface), or both of them should implement a single interface, but on save operation remote repo should throw an invalid operation exception?

答: It's unclear from the question if remote repo doesn't support add/update operations at all or only for specific types. In case of the first option, I would go with 2 interfaces: IReadonlyRepo, IWritableRepo. In case of the second option, I would go with the exception approach.</p>


问:
Can I commerically use GPL licensed software on my server if I am only distributing the client software?
I understand the rules of the GPL stating that if I distribute any software using GPL code, then that code must be licensed under the GPL.

However, I'm wondering what the rules are in this case: I am creating a service where I will be selling and distributing client side software.

The client side software has absolutely no GPL code in it. It is 100% my own code.

However, the client software will be connecting to my server, which internally uses GPL code.

I am not distributing my server side software; the server side software will live on a dedicated server that I alone control, but the client side software will not work without connecting to said server.

Does this count as one software? If I were to do this, would I be required to license my client side source code as GPL? Or, can I sell the client side software without releasing its source code?

答:
Does the client software depend on the server software for its proper functioning?  In other words, will the client software work without being connected to the server?

If the answer to that is "yes," and the server merely provides an additional feature, and not core support, to your client software, then you're probably in the clear.  If the server software is an integral part of the client software and provides core functionality to the client software (i.e. the client software will not work without the server), then the combination is a derived work, covered under the GPL.


答:
Two processes communicating over a network does not entail the creation of a derived work the way linkage of an executable with a library does.  So the GPL code on the server does not apply to the client code.

Under the GPL, you are required to distribute the modified source code when you distribute binaries.  Since you're not distributing the server binaries, you're not required to distribute the server source code.

The GNU Affero GPL is a license similar to the GPL with additional verbage designed to close this very loop hole you wish to take advantage of (see: http://www.gnu.org/licenses/why-affero-gpl.html and http://en.wikipedia.org/wiki/Affero_General_Public_License#Examples_of_web_applications_under_GNU_AGPL).

Disclaimer: I'm a developer, not a lawyer.

Title: Can I commerically use GPL licensed software on my server if I am only distributing the client software?

Body:
I understand the rules of the GPL stating that if I distribute any software using GPL code, then that code must be licensed under the GPL.

However, I'm wondering what the rules are in this case: I am creating a service where I will be selling and distributing client side software.

The client side software has absolutely no GPL code in it. It is 100% my own code.

However, the client software will be connecting to my server, which internally uses GPL code.

I am not distributing my server side software; the server side software will live on a dedicated server that I alone control, but the client side software will not work without connecting to said server.

Does this count as one software? If I were to do this, would I be required to license my client side source code as GPL? Or, can I sell the client side software without releasing its source code?


答:
One argument I'm missing here is the possibility of increased protection against cross site scripting attacks.

It's possible to disable the execution of inline JavaScript in modern browser via the Content Security Policy. This reduced the risk of your site falling victim of XSS. This may be a more convincing argument to make to your management to invest in removing inline script.

Title: Why Should I Avoid Inline Scripting?

Body:
A knowledgeable friend recently looked at a website I helped launch, and commented something like "very cool site, shame about the inline scripting in the source code".

I'm definitely in a position to remove the inline scripting where it occurs; I'm vaguely aware that it's "a bad thing".  My question is: what are the real problems with inline scripting?  Is there a significant performance issue, or is it mostly just a matter of good style?  Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?  If you pulled up to a website, and took a peek at the source code, what factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

Okay, that question turned into multiple questions in the writing.  But basically, inline scripting - what's the deal?


问:
How to save images into files in a web application and avoid removing them with every build?
I am building a web application and users will be able to upload pics. And I want to store these images into files instead of storing them into the DB.

But if I saved these pics into relative paths to the web application, they will be removed with each build.

So how I can handle this and the best practices related to this issue.

答:
Good way to deal with this kind of issue is to have another domain/subdomain/(or even CDN service) that is dedicated to serving static files (images, scripts, stylesheets, documents, etc).

So for example in simple web applications:
Application path: /www/app/, Static files path: /www/static/

when user uploads a file, saving it to /www/static/complex/folder/structure/file.ext, and then save details about this uploaded file to your database.
and then serving the file trought static.my-amazing-web.app

What this will enable you to do is: easily leverage the users browser cache, do optimizations on the fly, scale out with CDN's when things start to get out of hand, and all kinds of fun stuff.

This will also enable you to implement more security for the files the users upload.
It is also good idea to have static file server that has execution of the files blocked, to improve the security of the server from malicious user uploads.


问:
Why do C# and Java use reference equality as the default for '=='?
I've been pondering for a while why Java and C# (and I'm sure other languages) default to reference equality for ==.

In the programming I do (which certainly is only a small subset of programming problems), I almost always want logical equality when comparing objects instead of reference equality. I was trying to think of why both of these languages went this route instead of inverting it and having == be logical equality and using .ReferenceEquals() for reference equality.

Obviously using reference equality is very simple to implement and it gives very consistent behavior, but it doesn't seem like it fits well with most of the programming practices I see today.

I don't wish to seem ignorant of the issues with trying to implement a logical comparison, and that it has to be implemented in every class. I also realize that these languages were designed a long time ago, but the general question stands.

Is there some major benefit of defaulting to this that I am simply missing, or does it seem reasonable that the default behavior should be logical equality, and defaulting back to reference equality it a logical equality doesn't exist for the class?

答:
I was trying to think of why both of these languages went this route instead of inverting it and having == be logical equality and using .ReferenceEquals() for reference equality.

Because the latter approach would be confusing. Consider:

```<code>if (null.ReferenceEquals(null)) System.out.println("ok");
</code>```

Should this code print "ok", or should it throw a NullPointerException?

Body:
I was trying to think of why both of these languages went this route instead of inverting it and having == be logical equality and using .ReferenceEquals() for reference equality.

Because the latter approach would be confusing. Consider:

if (null.ReferenceEquals(null)) System.out.println("ok");

Should this code print "ok", or should it throw a NullPointerException?


问:
Is returning a reference to inside a private vector bad practice?
I have the following trimmed class:

```<code>#include <vector>

#include "Tile.h"

class Board {

    std::vector<Tile> boardArr;

    // VVV Bad Practice? Safe?
    Tile& getTileAt(unsigned int x, unsigned int y);

public:

    Board(int width, int height);

};
</code>```

Note that the vector remains the same size once the class is initialized; I have no methods to modify it. From what I understand, vectors are guaranteed to not move around, unless it's required to resize, so a reference into it should be safe in this case.

From what I can tell, this should be safe. The method is private, so there shouldn't be any way for references to leak.

The best alternative to the above function is to return a copy of the Tile, modify it, then copy the modified tile back. I found using it directly a lot cleaner, so I'd prefer it if it's safe.

This will be single-threaded, and so far, it's only use is to do simple things to a tile, like toggle an internal flag. An example of how I'm using it:

```<code>TurnResult Board::flipTile(unsigned int x, unsigned int y) {
    return getTileAt(x, y).flipTile();
}

void Board::setTileFlag(unsigned int x, unsigned int y, bool flagState) {
    getTileAt(x, y).setFlag(flagState);
}
</code>```

答:
Yes, returning a reference to an element of a std::vector is safe, unless you change the number of elements in the container while holding on to the reference.

Whether it is a good practice can be debated, but that is mostly for public functions, where returning a reference to internal data breaks encapsulation.

If you know that the size of the board is completely fixed, then returning a reference from a private function is perfectly fine.


问:
How to quickly search through a very large list of strings / records on a database
I have the following problem: I have a database containing more than 2 million records.
Each record has a string field X and I want to display a list of records for which field X contains a certain string. Each record is about 500 bytes in size.

To make it more concrete: in the GUI of my application I have a text field where I can enter a string. Above the text field I have a table displaying the (first N, e.g. 100) records that match the string in the text field. When I type or delete one character in the text field, the table content must be updated on the fly.

I wonder if there is an efficient way of doing this using appropriate index structures and / or caching. As explained above, I only want to display the first N items that match the query. Therefore, for N small enough, it should not be a big issue loading the matching items from the database. Besides, caching items in main memory can make retrieval faster.

I think the main problem is how to find the matching items quickly, given the pattern string. Can I rely on some DBMS facilities, or do I have to build some in-memory index myself? Any ideas?

EDIT

I have run a first experiment. I have split the records into different text files (at most 200 records per file) and put the files in different directories (I used the content of one data field to determine the directory tree). I end up with about 50000 files in about 40000 directories. I have then run Lucene to index the files. Searching for a string with the Lucene demo program is pretty fast. Splitting and indexing took a few minutes: this is totally acceptable for me because it is a static data set that I want to query.

The next step is to integrate Lucene in the main program and use the hits returned by Lucene to load the relevant records into main memory.

答: Have you considered Sphinx? http://sphinxsearch.com if you can use a 3rd party tool this would be ideal for what your're trying to achieve, its much more efficient at full text search than any RDBMS that I have personally used.</p>


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
It has a place. I've worked at a lot of companies where the skill levels of developers range from terrible to wizard. Since the code has to be maintained, and I won't be there forever, I try to write stuff so that it looks like it belongs there (without looking at the comments with my initials, it is extremely rare for you to be able to look at code I've worked on to see where I made changes), and that someone with less skill than myself can maintain it. </p>

<p>While the ternary operator looks nitziffic and way cool, my experience is that line of code is going to be about impossible to maintain. At my current employer, we have products that have been shipping for almost 20 years. I wouldn't use that example anywhere. </p>

Title: Ternary operator considered harmful?

Body:
It has a place. I've worked at a lot of companies where the skill levels of developers range from terrible to wizard. Since the code has to be maintained, and I won't be there forever, I try to write stuff so that it looks like it belongs there (without looking at the comments with my initials, it is extremely rare for you to be able to look at code I've worked on to see where I made changes), and that someone with less skill than myself can maintain it.

While the ternary operator looks nitziffic and way cool, my experience is that line of code is going to be about impossible to maintain. At my current employer, we have products that have been shipping for almost 20 years. I wouldn't use that example anywhere.


问:
Is it possible to refactor inheritance to composition when virtual methods are called inside the base class?
Let's say I have a class called Country and two subclasses called AI and Player. The Country class has a number of virtual methods to allow player-specific or AI-specific behavior.

I want to make it possible for the player to switch countries during a game. To this end, I am refactoring the inheritance relation to composition. Then I will be able to switch out a Player's internal instance of Country for another at any time.

But this brings up a bit of a problem: When an external object attempts to call one of these virtual methods on a Player, it is delegated correctly to the Country method after any appropriate processing has been done. But when an internal Country method calls one of the virtual methods, the code in the Player or AI version no longer has a chance to run.

So now I'm left with updating every one of those methods to make sure both versions are called, which in itself is not a trivial task (infinite loops, anyone?).

This seems much harder than it ought to be. I've done similar refactorings before and never run into this issue. Why? Am I missing some blindingly obvious observation?

Edit for a concrete example now that I have access to the code again:

```<code>class Country
{
public:
    virtual void AddMoney(float money)
    {
        _vMoney += money;
    }
    void TakeLoan()
    {
        float loan = ...;
        AddMoney(loan); // <-- does not route through AI or Player implementation
    }
}
</code>```

```<code>class AI  // : public Country
{
private:
    Country *pCountry;

public:
    virtual void AddMoney(float x)
    {
        pCountry->AddMoney(x); // formerly Country::AddMoney(x)
        AllocateMoney(x);
    }
}
</code>```

答:
I'd got pretty much the same question, but this time in Java. I found one solution that uses non-static nested classes in java - which in C++ would translate to something like:

```<code>class AI  // : public Country
{
private:
    Country *pCountry;

public:
    class Super : public Country {
        AI* outerThis;

    public:
        Super(AI* outer, ...)
        {
            outerThis = outer;
        }

        virtual void AddMoney(float x)
        {
            Country::AddMoney(x);
            outerThis->AllocateMoney(x);
        }
    }

    // Just delegating calls to pCountry...
    virtual void AddMoney(float x)
    {
        pCountry->AddMoney(x);
    }
}
</code>```

Then of course you need to instantiate AI::Super in order to get a Country associated with a specific AI object. Perhaps instantiate it from the AI object itself (which removes the need for AI:Super to be public).

Basically replacing inheritance with composition is doing what's being done behind the scene explicitely. Behind the scene it's composition plus extending the virtual function dispatch table. In case of no virtual functions it's straight forward, but in the case of virtual functions you will have to take these into account. Normal way of doing this (behind the scenes) is to have the virtual table consisting of base class' entries (with overriden function replaced) followed by the derived class' entries, but it could also be implemented by having separate vtables for the base object (with overridden functions replaced) and one for the new virtual method's from the derived class (as in my example). In the latter case you could have the base object separately allocated and store just the pointer to it.

The only circular reference her is the AI <-> AI::Super which might result in circular calls. However the only calls from AI to AI::Super should be to wrap the methods from the base class, and calls from AI::Super to AI is analogous to calling methods in the Derived class no infinite recursions should arise.

Body:
I'd got pretty much the same question, but this time in Java. I found one solution that uses non-static nested classes in java - which in C++ would translate to something like:

class AI  // : public Country
{
private:
    Country *pCountry;

public:
    class Super : public Country {
        AI* outerThis;

    public:
        Super(AI* outer, ...)
        {
            outerThis = outer;
        }

        virtual void AddMoney(float x)
        {
            Country::AddMoney(x);
            outerThis->AllocateMoney(x);
        }
    }

    // Just delegating calls to pCountry...
    virtual void AddMoney(float x)
    {
        pCountry->AddMoney(x);
    }
}

Then of course you need to instantiate AI::Super in order to get a Country associated with a specific AI object. Perhaps instantiate it from the AI object itself (which removes the need for AI:Super to be public).

Basically replacing inheritance with composition is doing what's being done behind the scene explicitely. Behind the scene it's composition plus extending the virtual function dispatch table. In case of no virtual functions it's straight forward, but in the case of virtual functions you will have to take these into account. Normal way of doing this (behind the scenes) is to have the virtual table consisting of base class' entries (with overriden function replaced) followed by the derived class' entries, but it could also be implemented by having separate vtables for the base object (with overridden functions replaced) and one for the new virtual method's from the derived class (as in my example). In the latter case you could have the base object separately allocated and store just the pointer to it.

The only circular reference her is the AI <-> AI::Super which might result in circular calls. However the only calls from AI to AI::Super should be to wrap the methods from the base class, and calls from AI::Super to AI is analogous to calling methods in the Derived class no infinite recursions should arise.


问:
What was the date of the Java Alpha and Beta releases
The date of the public 1.0 release of Java is easy to find: January 23, 1996. But there were public Alpha and Beta releases before that, and in December 1995 Java already appeared on the list of Time Magazine's "Ten Best Products of 1995" (and I bet that earned someone in Sun's marketing team a fat bonus...).

I can't seem to find the exact dates of those alpha and beta release, though. Does anyone know these dates?

答:
It must have been March 23, 1995 when the first alpha version hit the public (according to this history which should mostly based on an articles published by sun).

In the first chapter they mention the third birthday of Java as March 23, 1998 and also on page 8 they mention that on the day after March 22, 1995 they announced it to the public.


问:
Can I release a git patch (diff) file of closed source/copyright code?
I've patched a bug in some code that is no longer being supported by it's owner but I would like to provide this to other members of the community.

A git.patch file technically contains copyright source code (in order to show what is removed/changed), does this make it illegal if I don't have permission from the owner?

Would this be considered "fair use"?

答:
If the project was released under an open-source license, then that license gives you permission to make modifications to the code and to distribute those modifications.

Most closed-source and proprietary licenses do not give you permission to make changes or to distribute (a changed version of) the software.

If you don't have permission to make changes, you are violating the rights of the copyright holder if you create (and distribute) a patch.