问:
What is the difference between _Procedural Generation_ and _Random Generation_?
Today, I got into an argument about the term "procedural generation".

My point was that its different from "classic" random generation in that procedural generation is based on a more mathematical, fractal-based, algorithm leading to a more "realistic" distribution and the usual randomness of most languages are based on a pseudo-random-number generator, leading to an "unrealistic", in a way, ugly, distribution. This discussion was made with a heightmap in mind.

The discussion left me somehow unconvinced about my own arguments though, so, is there more to it? Or am I the one who is, in fact, simply wrong?

答:
First off, everything a computer does is by definition pseudo-random, unless it is actually connected to a radioactivity counting device or something similar. It doesn't matter whether you use fractal iterative systems, linear equations or whatever - the same seed will produce the same sequence (and that is often good, e.g. for creating rliable test suites).

Certainly there are good and bad algorithms for producing random sequences by computer, but the definition of what is "realistic" (much less "ugly") is by no means uncontested. As a very basic example, you would naively expect a random series of binary digits to have equals amounts of 0 and 1 values, but actually this definition would make every other item completely predictable, and the resulting sequence very, very predictable.

Actual random sequences of binary digits tend to have roughly equal amounts of 0s and 1s, and the ratio tends to approach 0.5 as the sequence grows, but the absolute number of 0s and 1s is actually more likely to become more unequal over time. (Getting exactly 500,000 0s and 500,000 1s from a million random digits is quite improbable.) So you see that the definition of "random" is rather more complicated than just "unpredictable" or "evenly distributed", and there is no complete consensus on what the definition should be or which properties of sequences are actually needed for a given task. I'm not certain which of those properties can be improved with fractal generators over the standard linear congruential generators, but I expect more knowledgeable people will post some.


问:
How is Pash licensed?
Pash is an open source reimplementation of Windows PowerShell. It was released in 2008, and has been idle since then. I would like to take up the mantle.

It's not clear what the license is. There is no LICENSE file or license details in the code.

The only reference to a license I can find is on this page: http://sourceforge.net/projects/pash/ where it says:

"License: BSD License, GNU General Public License (GPL)"

But I'm not sure if I can take that as authoritative.

I have tried to contact the author but he has not responded.

I would hate to proceed with this project and later discover that I am violating a license, and have the project crippled as a result.

答:
You can take that as authoritative as far as the original author considered it.

During project registration on SourceForge, you have to choose a license and you have to elaborate on what your project is and what you intend to do with it. Non-OSS projects aren't allowed on SourceForge and only admins of a project can change the license categorization, so you can be pretty sure that only the author could have set this.

Not having a license file in your source tree is really bad idea as it leads to confusing situation. If the project ever got removed from SourceForge, there will be no way of finding out about its license. I would recommend that your first commit should be clarifying this.

Do you know that SourceForge has procedures for taking over abandoned projects? You can also open a support ticket with SourceForge asking them about possible license changes in the past.

ContentLicense: CC BY-SA 3.0

Title: How is Pash licensed?


问:
Wiki/markup in enterprise as documentation
Why it is less common to use wiki/markup in enterprise as documentation?

They use Word document instead.

Wiki/markup are in text format, which is version control friendly.

答:
In the big enterprise the documentation is out-sourced, or is not written by developers. The end-user documentation is written by Technical writers. These people are proficient in the technical details, but not necessarily be interested in learning the new syntax for wiki/tex. What matters for end user is pdf or something like that. There are software (mostly paid) which can convert doc to other formats.  The cost for these software is smaller than the cost of training of the technical writers.

Other point is the documentation will be simple to version control if it is only text which can be written in wiki/Tex. But then binary objects like images creates issues. Version controlling binary objects is difficult. In my experience version controlling a simple jpeg image is as difficult as version controlling an entire .doc file.

Most of times the non-technical managers will have to take a look at the raw document and or modify it. Manager's time is very costly and also it is difficult for them to learn new tools. .doc being easy as WYSWIG is preferred by them.


问:
Misconceptions about purely functional languages?
I often encounter the following statements / arguments:

Pure functional programming languages do not allow side effects (and are therefore of little use in practice because any useful program does have side effects, e.g. when it interacts with the external world).

Pure functional programming languages do not allow to write a program that maintains state (which makes programming very awkward because in many application you do need state).

I am not an expert in functional languages but here is what I have understood about these topics until now.

Regarding point 1, you can interact with the environment in purely functional languages but you have to explicitly mark the code (functions) that introduces side effects (e.g. in Haskell by means of monadic types). Also, as far as I know computing by side effects (destructively updating data) should also be possible (using monadic types?) even though it is not the preferred way of working.

Regarding point 2, as far as I know you can represent state by threading values through several computation steps (in Haskell, again, using monadic types) but I have no practical experience doing this and my understanding is rather vague.

So, are the two statements above correct in any sense or are they just misconceptions about purely functional languages? If they are misconceptions, how did they come about?
Could you write a (possibly small) code snippet illustrating the Haskell idiomatic way to (1) implement side effects and (2) implement a computation with state?

答:
IMHO you are confused because there is a difference between a pure language and a pure function. Let us begin with the function. A function is pure if it will (given the same input) always return the same value and does not cause any observable side effects. Typical examples are mathematical functions like f(x) = x * x. Now consider an implementation of this function. It would be pure in most languages even those which are not generally considered pure functional languages e.g. ML. Even a Java or C++ method with this behavior can be considered as pure.

So what is a pure language? Strictly speaking one might expect that a pure language does not let you express functions that are not pure. Let us call this the idealistic definition of a pure language. Such a behavior is highly desirable. Why? Well the nice thing about a program consisting of only pure functions is that you can replace the function application with its value without changing the meaning of the program. This makes very easy to reason about programs because once you know the result you can forget the way it was computed. Purity might also allows the compiler to perform certain aggressive optimizations.

So what if you need some internal state? You can mimic state in a pure language simply by adding the state before the computation as an input parameter and the state after the computation as part of the result. Instead of Int -> Bool you get something like Int -> State -> (Bool, State). You simply make the dependency  explicit (which is considered good practice in any programming paradigm). BTW there is a monad that is a particularly elegant way to combine such state-mimicking functions into bigger state-mimicking functions. This way you definitely can "maintain state" in a pure language. But you have to make it explicit.

So does this mean I can interact with the outside? After all a useful program must interact with the real world in order to be useful. But input and output are obviously not pure. Writing a specific byte to a specific file might be fine for the first time. But executing the exact same operation a second time might return an error because the disk is full. Clearly there exists no pure language (in the idealistic meaning) that can write to a file.

So we are faced with a dilemma. We want mostly pure functions but some side effects are absolutely required and those are not pure. Now a realistic definition of a pure language would be that there has to be some means to separate the pure parts from the other parts. The mechanism must ensure that no impure operation sneaks its way into the pure parts.

In Haskell this is done with the IO type. You cannot destruct an IO result (without unsafe mechanisms). Thus you can only process IO results with functions that are defined in the IO module themselves. Luckily there is a very flexible combinators which allows you to take an IO result and process it in a function as long as that function returns another IO result. This combinator is called bind (or >>=) and has the type IO a -> (a -> IO b) -> IO b. If you generalize this concept you arrive at the monad class and IO happens to be an instance of it.


答:
For the purposes of this answer I define "purely functional language" to mean a functional language in which functions are referentially transparent, i.e. calling the same function multiple times with the same arguments will always produce the same results. This is, I believe, the usual definition of a purely functional language.

Pure functional programming languages do not allow side effects (and are therefore of little use in practice because any useful program does have side effects, e.g. when it interacts with the external world).

The easiest way to achieve referential transparency would indeed be to disallow side effects and there are indeed languages in which that is the case (mostly domain specific ones). However it is certainly not the only way and most general purpose purely functional languages (Haskell, Clean, ...) do allow side effect.

Also saying that a programming language without side effects is little use in practice isn't really fair I think - certainly not for domain specific languages, but even for general purpose languages, I'd imagine a language can be quite useful without providing side effects. Maybe not for console applications, but I think GUI applications can be nicely implemented without side-effects in, say, the functional reactive paradigm.

Regarding point 1, you can interact with the environment in purely functional languages but you have to explicitly mark the code (functions) that introduces them (e.g. in Haskell by means of monadic types).

That's a bit over simplifying it. Just having a system where side-effecting functions need to be marked as such (similar to const-correctness in C++, but with general side-effects) is not enough to ensure referential transparency. You need to ensure that a program can never call a function multiple times with the same arguments and get different results. You could either do that by making things like readLine be something that's not a function (that's what Haskell does with the IO monad) or you could make it impossible to call side-effecting functions multiple times with the same argument (that's what Clean does). In the latter case the compiler would ensure that every time you call a side-effecting function, you do so with a fresh argument, and it would reject any program where you pass the same argument to a side-effecting function twice.

Pure functional programming languages do not allow to write a program that maintains state (which makes programming very awkward because in many application you do need state).

Again, a purely functional language might very well disallow mutable state, but it's certainly possible to be pure and still have mutable state, if you implement it in the same way as I described with side-effects above. Really mutable state is just another form of side-effects.

That said, functional programming languages definitely do discourage mutable state - pure ones especially so. And I don't think that that makes programming awkward - quite the opposite. Sometimes (but not all that often) mutable state can't be avoided without losing performance or clarity (which is why languages like Haskell do have facilities for mutable state), but most often it can.

If they are misconceptions, how did they come about?

I think many people simply read "a function must produce the same result when called with the same arguments" and conclude from that that it's not possible to implement something like readLine or code that maintains mutable state. So they're simply not aware of the "cheats" that purely functional languages can use to introduce these things without breaking referential transparency.

Also mutable state is heavily discourages in functional languages, so it isn't all that much of a leap to assume it's not allowed at all in purely functional ones.

Could you write a (possibly small) code snippet illustrating the Haskell idiomatic way to (1) implement side effects and (2) implement a computation with state?

Here's an application in Pseudo-Haskell that asks the user for a name and greets him. Pseudo-Haskell is a language that I just invented, which has Haskell's IO system, but uses more conventional syntax, more descriptive function names and has no do-notation (as that would just distract from how exactly the IO monad works):

```<code>greet(name) = print("Hello, " ++ name ++ "!")
main = composeMonad(readLine, greet)
</code>```

The clue here is that readLine is a value of type IO<String> and composeMonad is a function that takes an argument of type IO<T> (for some type T) and another argument that is a function which takes an argument of type T and returns a value of type IO (for some type U). print is a function that takes a string and returns a value of type IO<void>.

A value of type IO is a value that "encodes" a given action that produces a value of type A. composeMonad(m, f) produces a new IO value that encodes the action of m followed by the action of f(x), where x is the value produces by performing the action of m.

Mutable state would look like this:

```<code>counter = mutableVariable(0)
increaseCounter(cnt) =
    setIncreasedValue(oldValue) = setValue(cnt, oldValue + 1)
    composeMonad(getValue(cnt), setIncreasedValue)

printCounter(cnt) = composeMonad( getValue(cnt), print )

main = composeVoidMonad( increaseCounter(counter), printCounter(counter) )
</code>```

Here mutableVariable is a function that takes value of any type T and produces a MutableVariable<T>. The function getValue takes MutableVariable and returns an IO<T> that produces its current value. setValue takes a MutableVariable<T> and a T and returns an IO<void> that sets the value. composeVoidMonad is the same as composeMonad except that the first argument is an IO that does not produce a sensible value and the second argument is another monad, not a function that returns a monad.

In Haskell there's some syntactic sugar, that makes this whole ordeal less painful, but it's still obvious that mutable state is something that language doesn't really want you to do.

Title: Misconceptions about purely functional languages?

Body:
I often encounter the following statements / arguments:

Pure functional programming languages do not allow side effects (and are therefore of little use in practice because any useful program does have side effects, e.g. when it interacts with the external world).

Pure functional programming languages do not allow to write a program that maintains state (which makes programming very awkward because in many application you do need state).

I am not an expert in functional languages but here is what I have understood about these topics until now.

Regarding point 1, you can interact with the environment in purely functional languages but you have to explicitly mark the code (functions) that introduces side effects (e.g. in Haskell by means of monadic types). Also, as far as I know computing by side effects (destructively updating data) should also be possible (using monadic types?) even though it is not the preferred way of working.

Regarding point 2, as far as I know you can represent state by threading values through several computation steps (in Haskell, again, using monadic types) but I have no practical experience doing this and my understanding is rather vague.

So, are the two statements above correct in any sense or are they just misconceptions about purely functional languages? If they are misconceptions, how did they come about?
Could you write a (possibly small) code snippet illustrating the Haskell idiomatic way to (1) implement side effects and (2) implement a computation with state?

Body:
For the purposes of this answer I define "purely functional language" to mean a functional language in which functions are referentially transparent, i.e. calling the same function multiple times with the same arguments will always produce the same results. This is, I believe, the usual definition of a purely functional language.

Pure functional programming languages do not allow side effects (and are therefore of little use in practice because any useful program does have side effects, e.g. when it interacts with the external world).

The easiest way to achieve referential transparency would indeed be to disallow side effects and there are indeed languages in which that is the case (mostly domain specific ones). However it is certainly not the only way and most general purpose purely functional languages (Haskell, Clean, ...) do allow side effect.

Also saying that a programming language without side effects is little use in practice isn't really fair I think - certainly not for domain specific languages, but even for general purpose languages, I'd imagine a language can be quite useful without providing side effects. Maybe not for console applications, but I think GUI applications can be nicely implemented without side-effects in, say, the functional reactive paradigm.

Regarding point 1, you can interact with the environment in purely functional languages but you have to explicitly mark the code (functions) that introduces them (e.g. in Haskell by means of monadic types).

That's a bit over simplifying it. Just having a system where side-effecting functions need to be marked as such (similar to const-correctness in C++, but with general side-effects) is not enough to ensure referential transparency. You need to ensure that a program can never call a function multiple times with the same arguments and get different results. You could either do that by making things like readLine be something that's not a function (that's what Haskell does with the IO monad) or you could make it impossible to call side-effecting functions multiple times with the same argument (that's what Clean does). In the latter case the compiler would ensure that every time you call a side-effecting function, you do so with a fresh argument, and it would reject any program where you pass the same argument to a side-effecting function twice.

Pure functional programming languages do not allow to write a program that maintains state (which makes programming very awkward because in many application you do need state).

Again, a purely functional language might very well disallow mutable state, but it's certainly possible to be pure and still have mutable state, if you implement it in the same way as I described with side-effects above. Really mutable state is just another form of side-effects.

That said, functional programming languages definitely do discourage mutable state - pure ones especially so. And I don't think that that makes programming awkward - quite the opposite. Sometimes (but not all that often) mutable state can't be avoided without losing performance or clarity (which is why languages like Haskell do have facilities for mutable state), but most often it can.

If they are misconceptions, how did they come about?

I think many people simply read "a function must produce the same result when called with the same arguments" and conclude from that that it's not possible to implement something like readLine or code that maintains mutable state. So they're simply not aware of the "cheats" that purely functional languages can use to introduce these things without breaking referential transparency.

Also mutable state is heavily discourages in functional languages, so it isn't all that much of a leap to assume it's not allowed at all in purely functional ones.

Could you write a (possibly small) code snippet illustrating the Haskell idiomatic way to (1) implement side effects and (2) implement a computation with state?

Here's an application in Pseudo-Haskell that asks the user for a name and greets him. Pseudo-Haskell is a language that I just invented, which has Haskell's IO system, but uses more conventional syntax, more descriptive function names and has no do-notation (as that would just distract from how exactly the IO monad works):

greet(name) = print("Hello, " ++ name ++ "!")
main = composeMonad(readLine, greet)

The clue here is that readLine is a value of type IO<String> and composeMonad is a function that takes an argument of type IO<T> (for some type T) and another argument that is a function which takes an argument of type T and returns a value of type IO<U> (for some type U). print is a function that takes a string and returns a value of type IO<void>.

A value of type IO<A> is a value that "encodes" a given action that produces a value of type A. composeMonad(m, f) produces a new IO value that encodes the action of m followed by the action of f(x), where x is the value produces by performing the action of m.

Mutable state would look like this:

counter = mutableVariable(0)
increaseCounter(cnt) =
    setIncreasedValue(oldValue) = setValue(cnt, oldValue + 1)
    composeMonad(getValue(cnt), setIncreasedValue)

printCounter(cnt) = composeMonad( getValue(cnt), print )

main = composeVoidMonad( increaseCounter(counter), printCounter(counter) )

Here mutableVariable is a function that takes value of any type T and produces a MutableVariable<T>. The function getValue takes MutableVariable and returns an IO<T> that produces its current value. setValue takes a MutableVariable<T> and a T and returns an IO<void> that sets the value. composeVoidMonad is the same as composeMonad except that the first argument is an IO that does not produce a sensible value and the second argument is another monad, not a function that returns a monad.

In Haskell there's some syntactic sugar, that makes this whole ordeal less painful, but it's still obvious that mutable state is something that language doesn't really want you to do.


答:
procedural generation means there is a seed which defines all output and no matter how many times you regenerate with the same seed you get the same output each time, which you see used for example in minecraft and dwarf fortress

true random generation takes extra external entropy to add to the initial seed so each time it runs you get a different output

it is important to note that both approaches can result in both good and bad generation

common psuedo random generators used for this are linear congruential generators and mercenne twisters, either of which can be sufficient if used correctly

for example minecraft uses a LCG (as in java's stock standard Random implementation) for it's map generation

Title: What is the difference between _Procedural Generation_ and _Random Generation_?

Body:
Today, I got into an argument about the term "procedural generation".

My point was that its different from "classic" random generation in that procedural generation is based on a more mathematical, fractal-based, algorithm leading to a more "realistic" distribution and the usual randomness of most languages are based on a pseudo-random-number generator, leading to an "unrealistic", in a way, ugly, distribution. This discussion was made with a heightmap in mind.

The discussion left me somehow unconvinced about my own arguments though, so, is there more to it? Or am I the one who is, in fact, simply wrong?


答:
I think you're wrong. Procedural is not the opposite of random; procedural is the opposite of handmade.

its different from "classic" random generation in the way that
  procedural is based on a more mathematical, fractal based, algorithm
  leading to a more "realistic" distribution and the usual randomness of
  most languages are based on a pseudo-random-number generator, leading
  to an "unrealistic", in a way, ugly, distribution.

Both of the schemes you are describing here are procedural. The first is arguably better, more sophisticated, but both:

take a small input (the seed);

use that seed and nothing else, along with an algorithmic process, to produce the output

Now, it might well be that when people talk about procedural generation, what they usually talk about are complicated generation schemes based on carefully refined algorithms - but they are still random in the sense that the input is a random variate.

The "'unrealistic', in a way, ugly, distribution[s]" you mention? Those are procedural too - just using a relatively unsophisticated procedural generation scheme.


问:
Is the addition of a duration to a date-time defined in ISO 8601?
I've writing a date-time library, and need to implement the addition of a duration to a date-time.

If I add a 1 month duration: P1M to the 31st March 2012: 2012-03-31, does the standard define what the result is?

Because the resulting date (31st April) does not exist, there are at least two options:

Fall back to the last day of the resulting month. This is the approach currently taken by the ThreeTen API, the (alpha) reference implementation of JSR-310:

ZonedDateTime date = ZonedDateTime.parse("2012-03-31T00:00:00Z");
Period duration = Period.parse("P1M");
System.out.println(date.plus(duration).toString());

// 2012-04-30T00:00Z
```

<ul>
<li>Carry the extra day to the next month. This is the approach taken by the DateTime class in PHP:</li>
</ul>

<pre class="lang-php prettyprint-override"><code>$date = new DateTime('2012-03-31T00:00:00Z');
$duration = new DateInterval('P1M');
echo $date->add($duration)->format('c');

// 2012-05-01T00:00:00+00:00
</code>```

I'm surprised that two date-time libraries contradict on this point, so I'm wondering whether the standard defines the result of this operation?

答:
That's an edge case. I got no specifications to back my statement up, but...

You should use the last date of the next month. Else you have added two months and not one month.


问:
Functional programming compared to OOP with classes
I have been interested in some of the concepts of functional programming lately. I have used OOP for some time now. I can see how I would build a fairly complex app in OOP. Each object would know how to do things that object does. Or anything it's parents class does as well. So I can simply tell Person().speak() to make the person talk.

But how do I do similar things in functional programming? I see how functions are first class items. But that function only does one specific thing. Would I simply have a say() method floating around and call it with an equivalent of Person() argument so I know what kind of thing is saying something?

So I can see the simple things, just how would I do the comparable of OOP and objects in functional programming, so I can modularize and organize my code base?

For reference, my primary experience with OOP is Python, PHP, and some C#. The languages that I am looking at that have functional features are Scala and Haskell. Though I am leaning towards Scala.

Basic Example (Python):

```<code>Animal(object):
    def say(self, what):
        print(what)

Dog(Animal):
    def say(self, what):
        super().say('dog barks: {0}'.format(what))

Cat(Animal):
    def say(self, what):
        super().say('cat meows: {0}'.format(what))

dog = Dog()
cat = Cat()
dog.say('ruff')
cat.say('purr')
</code>```

答:
it really depends on what you want to accomplish.

if you just need a way to organize behaviour based on selective criteria, you can use e.g. a dictionary (hash-table) with function-objects. in python it could be something along the lines of:

```<code>def bark(what):
    print "barks: {0}".format(what)

def meow(what):
    print "meows: {0}".format(what)

def climb(how):
    print "climbs: {0}".format(how)

if __name__ == "__main__":
    animals = {'dog': {'say': bark},
               'cat': {'say': meow,
                       'climb': climb}}
    animals['dog']['say']("ruff")
    animals['cat']['say']("purr")
    animals['cat']['climb']("well")
</code>```

note however, that (a) there are no 'instances' of dog or cat and (b) you will have to keep track of the 'type' of your objects yourself.

like for example: pets = [['martin','dog','grrrh'], ['martha', 'cat', 'zzzz']]. then you could do a list comprehension like [animals[pet[1]]['say'](pet[2]) for pet in pets]

Body:
it really depends on what you want to accomplish.

if you just need a way to organize behaviour based on selective criteria, you can use e.g. a dictionary (hash-table) with function-objects. in python it could be something along the lines of:

def bark(what):
    print "barks: {0}".format(what)

def meow(what):
    print "meows: {0}".format(what)

def climb(how):
    print "climbs: {0}".format(how)

if __name__ == "__main__":
    animals = {'dog': {'say': bark},
               'cat': {'say': meow,
                       'climb': climb}}
    animals['dog']['say']("ruff")
    animals['cat']['say']("purr")
    animals['cat']['climb']("well")

note however, that (a) there are no 'instances' of dog or cat and (b) you will have to keep track of the 'type' of your objects yourself.

like for example: pets = [['martin','dog','grrrh'], ['martha', 'cat', 'zzzz']]. then you could do a list comprehension like [animals[pet[1]]['say'](pet[2]) for pet in pets]


问:
How many types of programming languages are there?
Basically, I want to learn lots of programming languages to become a great programmer.  I know only a handful to depth and I was hoping someone could elaborate on how many classes or types of programming languages there are.  Like how you would lump them together if you had to learn them in groups.

Coming from a Java background, I'm familiar with static typing, but I know that in addition to dynamic typing there has to be such variety in available languages that I would love to see a categorical breakdown if possible.

答:
I think a short-cut to all these is to learn enough Lisp to do some semi-useful things. Most of these paradigms started out as ways of using Lisp, so it's a simple way to try things.

There are a number of "kinds" of languages around, but new ones can always appear. Basically, the purpose of a language is to permit encoding of ideas, concepts, or requirements, as directly as possible. To that end, there can be situations where existing paradigms are wanting, and a new one might be needed.

One way to look at is in terms of surface structure. How directly does it allow you to encode ideas concisely, so that if you change your mind about what you want, the corresponding change to the code is also easy, with little chance to introduce bugs.

Another way to look at it is in terms of control structure. When the language is executed (if it is) what is the order in which things happen, to accomplish what you want? Examples are: simple straight-through execution, recursion, backtrack, parallelism. One I (modest cough) discovered was differential execution.

Another useful viewpoint is that any time a data structure is designed, a language is born. Data is "executed" by the application programs that comb through it and do things, just as a program is just a bunch of data (like byte codes) that are used by an interpreter to do things.

ContentLicense: CC BY-SA 2.5


答:
Adding by months makes no sense. You should only add by days or fractions of days. Even years can be problematic when dealing with leap days. Did you mean one year or 365 days or 366 days?

You should establish relative addition. Are you looking for end of the month, first of the month, or last workday of the month?

For end of month I use:
To calculate the last day of April

increment month by one unit beyond the month, adjusting the year as necessary;

change day of month to one;

Then subtract one day unit;

Title: Is the addition of a duration to a date-time defined in ISO 8601?

Body:
I've writing a date-time library, and need to implement the addition of a duration to a date-time.

If I add a 1 month duration: P1M to the 31st March 2012: 2012-03-31, does the standard define what the result is?

Because the resulting date (31st April) does not exist, there are at least two options:

Fall back to the last day of the resulting month. This is the approach currently taken by the ThreeTen API, the (alpha) reference implementation of JSR-310:

ZonedDateTime date = ZonedDateTime.parse("2012-03-31T00:00:00Z");
Period duration = Period.parse("P1M");
System.out.println(date.plus(duration).toString());

// 2012-04-30T00:00Z
```

<ul>
<li>Carry the extra day to the next month. This is the approach taken by the DateTime class in PHP:</li>
</ul>

<pre class="lang-php prettyprint-override"><code>$date = new DateTime('2012-03-31T00:00:00Z');
$duration = new DateInterval('P1M');
echo $date->add($duration)->format('c');

// 2012-05-01T00:00:00+00:00
</code>```

I'm surprised that two date-time libraries contradict on this point, so I'm wondering whether the standard defines the result of this operation?


问:
What is the difference between a Program Manager and a Project Manager?
Is a Program Manager a person who manages mutiple projects (under a single program) which are in turn managed by Project Managers?

Or is a Program Manager a person as defined by Joel Spolsky here.

NOTE: I am not referring to this.

答:
It really appears to depend on the company.

At Sun, they had program managers who were essentially interfaces between the technical teams and the bureaucracy.  One program manager would be assigned to several such teams and would make sure that, say, the required information is passed to the various architecture boards, open-source licensing policies are maintained, and they would convene regular status meetings of "program teams" that included the technical teams plus associated marketing and other folks.

This usage is perhaps vaguely related to some of the other explanations given here, but you can see that it really depends.


答:
I work in financial domain, and I understand there are different conventions to follow these corner cases.

Follow Wikipedia article Day Count Convention for details.

ISO_8601 does not have any specific value for month as duration, but the link The Mathematics of the ISO 8601 Calendar suggest month as 30.6, year as 365.25, with additional handling for leap years.


问:
Open source license with backlink requirement
I'm developing a Javascript library, and I'm thinking about releasing it under an open source license (e.g. GPL, BSD, MIT) — but that requires that websites that use the software link back to my website.

Do you know about any such licenses? And how have they formulated the attribution part of the license text?

Do you think this BSD-license would do what you think that I want? (I suppose it doesn't :-))

[...]
  3. Each website that redistributes this work must include a visible rel=follow link to my-website.example.com, reachable via rel=follow
  links from each page where the software is being redistributed.

  (For example, you could have a link back to your homepage, and from your
  homepage to an About-Us section, which could link to a Credits
  section)

I realize that some companies wouldn't want to use the library because of legal issues with interpreting non-standard licenses (have a look at this answer: https://softwareengineering.stackexchange.com/a/156859/54906). — After half a year, or perhaps some years, I license the work under plain GPL + MIT too (in addition to the original license).

答:
Yes, you can create a license that says that.  No, you shouldn't do it.

First, what's the point?  If you're trying to get attribution for your work, there are a number of licenses that already require that.  Creative Commons has a number of licenses that should fit the bill.

Requiring a link-back is dubious at best.  There's no guarantee you'll get any extra traffic, and how would you enforce that sort of a request?  More importantly, why would you impose an annoying restriction upon the future users of your product?  You're just scaring them away.

Trying to game search engines with a link back is also a dubious endeavor.  Just because you think the engines work a particular way now doesn't mean that they will continue to work that way in the future.  My third point below really focuses on this aspect.  Search engines are amongst the most rapidly changing technologies.

Second, why are you even considering changing the license structure at a later point in time?  Again, what's your point?  Pick the license or licenses that meets / meet your aims and stick with it.  Changing the license structure is a great way to annoy and scare off your existing user base as well as scaring away future users.  The future users will say "he did this once, what's to keep him from doing it again?"

Changing a license may mean nothing to you, but for organizations using your product it means more work.  The new license has to be reviewed; it may not mesh with their legal requirements; it may force them to pick a new product to provide the same function.  Don't do it unless you really have to.

Moving to a dual license structure later on doesn't bypass any of that additional work that you're creating for your users as you don't necessarily know which categories they're going to fall into.  *They* have the potential liability, so *they* are the ones who have to perform the review.

You mentioned selective enforcement of the license in one of your comments, and you might be considering that as a way of avoiding some of the problems brought up by this second point.  However, selective enforcement is tantamount to discrimination.  In some jurisdictions it will be tolerated, but in other jurisdictions you'll lose all rights to enforcement.  If you put a non-enforcement clause in writing then you're merely compounding the issue by creating confusion about what the terms of the license truly are.

Third, your suggested phrasing of the change is brittle.  Specifying a technology or implementation in something that it supposed to outlast various technologies is a bad idea.  How would people comply in the future if the requirement is technically infeasible?  The answer is they won't and that means they won't use your product either.

If you want to gain traction with your product manipulating the license (or search engines) is not the way to do it.  The best way to gain traction is to simply write a great product.  Make it available; show how great it is; keep the support active; and it will grow.

If you're worried about a competitor copying your source then don't release the source.  Ever.  License and Copyright only protect you if you can prove that those aspects were violated.  Proving the violation can be amazingly difficult to do.  All of the machinations you've suggested merely make it harder for legitimate users to use your product and do very little to keep future competitors from stealing your product.  By definition, criminals don't obey the law.


问:
Is there any reason not to go directly from client-side Javascript to a database?

Possible Duplicate:

  Writing Web “server less” applications

So, let's say I'm going to build a Stack Exchange clone and I decide to use something like CouchDB as my backend store. If I use their built-in authentication and database-level authorization, is there any reason not to allow the client-side Javascript to write directly to the publicly available CouchDB server? Since this is basically a CRUD application and the business logic consists of "Only the author can edit their post" I don't see much of a need to have a layer between the client-side stuff and the database. I would simply use validation on the CouchDB side to make sure someone isn't putting in garbage data and make sure that permissions are set properly so that users can only read their own _user data. The rendering would be done client-side by something like AngularJS. In essence you could just have a CouchDB server and a bunch of "static" pages and you're good to go. You wouldn't need any kind of server-side processing, just something that could serve up the HTML pages.

Opening my database up to the world seems wrong, but in this scenario I can't think of why as long as permissions are set properly. It goes against my instinct as a web developer, but I can't think of a good reason. So, why is this a bad idea?

EDIT: Looks like there is a similar discussion here: Writing Web "server less" applications

EDIT: Awesome discussion so far, and I appreciate everyone's feedback! I feel like I should add a few generic assumptions instead of calling out CouchDB and AngularJS specifically. So let's assume that:

The database can authenticate users directly from its hidden store

All database communication would happen over SSL

Data validation can (but maybe shouldn't?) be handled by the database

The only authorization we care about other than admin functions is someone only being allowed to edit their own post

We're perfectly fine with everyone being able to read all data (EXCEPT user records which may contain password hashes)

Administrative functions would be restricted by database authorization

No one can add themselves to an administrator role

The database is relatively easy to scale

There is little to no true business logic; this is a basic CRUD app

答:
Doing as you suggest creates a tight(er) coupling between your client side language and your database.

That can be okay - there's less code to write and maintain, and in theory debugging could / should go a little quicker.

On the other hand, it makes other aspects more difficult.  If / when you need to change either of those technologies, you'll have a harder time because of the tight coupling between them.

Protecting yourself against attacks will be (quite) a bit more difficult.  You're assuming that the client will always present nicely formatted requests to the database.  That presumes no one will ever hack the client side code to insert malicious statements.  In other words, they'll "borrow" your authentication mechanisms and replace the normal client code with theirs.

I wouldn't recommend it, and many would vehemently tell you not to.  But it can be done.


答:
Since this is basically a CRUD application and the business logic consists of "Only the author can edit their post" I don't see much of a need to have a layer between the client-side stuff and the database. I would simply use validation on the CouchDB side to make sure someone isn't putting in garbage data and make sure that permissions are set properly so that users can only read their own _user data.

Well, placing your authorization (the security concerns) and logic validation away from Database  provides separation of concerns in your software system. Thus you may test, maintain, scale and reuse your logical code blocks with less risks of braking the functionality in the system.

Providing ability for client input directly communicate with Database has very big potential to screw up the data.

This also means that avoiding/removing tight coupling make your software system more maintainable and SOLID.

Title: Is there any reason not to go directly from client-side Javascript to a database?

Body:
Possible Duplicate:

  Writing Web “server less” applications

So, let's say I'm going to build a Stack Exchange clone and I decide to use something like CouchDB as my backend store. If I use their built-in authentication and database-level authorization, is there any reason not to allow the client-side Javascript to write directly to the publicly available CouchDB server? Since this is basically a CRUD application and the business logic consists of "Only the author can edit their post" I don't see much of a need to have a layer between the client-side stuff and the database. I would simply use validation on the CouchDB side to make sure someone isn't putting in garbage data and make sure that permissions are set properly so that users can only read their own _user data. The rendering would be done client-side by something like AngularJS. In essence you could just have a CouchDB server and a bunch of "static" pages and you're good to go. You wouldn't need any kind of server-side processing, just something that could serve up the HTML pages.

Opening my database up to the world seems wrong, but in this scenario I can't think of why as long as permissions are set properly. It goes against my instinct as a web developer, but I can't think of a good reason. So, why is this a bad idea?

EDIT: Looks like there is a similar discussion here: Writing Web "server less" applications

EDIT: Awesome discussion so far, and I appreciate everyone's feedback! I feel like I should add a few generic assumptions instead of calling out CouchDB and AngularJS specifically. So let's assume that:

The database can authenticate users directly from its hidden store

All database communication would happen over SSL

Data validation can (but maybe shouldn't?) be handled by the database

The only authorization we care about other than admin functions is someone only being allowed to edit their own post

We're perfectly fine with everyone being able to read all data (EXCEPT user records which may contain password hashes)

Administrative functions would be restricted by database authorization

No one can add themselves to an administrator role

The database is relatively easy to scale

There is little to no true business logic; this is a basic CRUD app


答: Your client cannot use your web app if javascript is disabled (or not supported on the browser of his device) if javascript is the only database-access-layer.</p>


答: If your security checks and business logic are contained in your client side javascript, they can be overridden by a malicious user. As an alternative, you can leverage a JavaScript based server-side technology (like Node.JS) to handle validation, authorization, and the like.


问:
Should UTF-16 be considered harmful?
I'm going to ask what is probably quite a controversial question: "Should one of the most
popular encodings, UTF-16, be considered harmful?"

Why do I ask this question?

How many programmers are aware of the fact that UTF-16 is actually a variable length encoding? By this I mean that there are code points that, represented as surrogate pairs, take more than one element.

I know; lots of applications, frameworks and APIs use UTF-16, such as Java's String, C#'s String, Win32 APIs, Qt GUI libraries, the ICU Unicode library, etc.  However, with all of that, there are lots of basic bugs in the processing of characters out of BMP (characters that should be encoded using two UTF-16 elements).

For example, try to edit one of these characters:

𝄞 (U+1D11E) MUSICAL SYMBOL G CLEF

𝕥 (U+1D565) MATHEMATICAL DOUBLE-STRUCK SMALL T

𝟶 (U+1D7F6) MATHEMATICAL MONOSPACE DIGIT ZERO

𠂊 (U+2008A) Han Character

You may miss some, depending on what fonts you have installed.  These characters are all outside of the BMP (Basic Multilingual Plane).  If you cannot see these characters, you can also try looking at them in the Unicode Character reference.

For example, try to create file names in Windows that include these characters; try to delete these characters with a "backspace" to see how they behave in different applications that use UTF-16. I did some tests and the results are quite bad:

Opera has problem with editing them (delete required 2 presses on backspace)

Notepad can't deal with them correctly (delete required 2 presses on backspace)

File names editing in Window dialogs in broken (delete required 2 presses on backspace)

All QT3 applications can't deal with them - show two empty squares instead of one symbol.

Python encodes such characters incorrectly when used directly u'X'!=unicode('X','utf-16') on some platforms when X in character outside of BMP.

Python 2.5 unicodedata fails to get properties on such characters when python compiled with UTF-16 Unicode strings.

StackOverflow seems to remove these characters from the text if edited directly in as Unicode characters (these characters are shown using HTML Unicode escapes).

WinForms TextBox may generate invalid string when limited with MaxLength.

It seems that such bugs are extremely easy to find in many applications that use UTF-16.

So... Do you think that UTF-16 should be considered harmful?

答:
Since I cannot yet comment, I post this as an answer, since it seems I cannot otherwise contact the authors of utf8everywhere.org. It's a shame I don't automatically get the comment privilege, since I have enough reputation on other stackexchanges.

This is meant as a comment to the Opinion: Yes, UTF-16 should be considered harmful answer.

One little correction:

To prevent one from accidentally passing a UTF-8 char* into ANSI-string versions of Windows-API functions, one should define UNICODE, not _UNICODE. _UNICODE maps functions like _tcslen to wcslen, not MessageBox to MessageBoxW. Instead, the UNICODE define takes care of the latter.
For proof, this is from MS Visual Studio 2005's WinUser.h header:

```<code>#ifdef UNICODE
#define MessageBox  MessageBoxW
#else
#define MessageBox  MessageBoxA
#endif // !UNICODE
</code>```

At the very minimum, this error should be corrected on utf8everywhere.org.

A suggestion:

Perhaps the guide should contain an example of explicit use of the Wide-string version of a data structure, to make it less easy to miss/forget it. Using Wide-string versions of data structures on top of using Wide-string versions of functions makes it even less likely that one accidentally calls an ANSI-string version of such a function.

Example of the example:

```<code>WIN32_FIND_DATAW data; // Note the W at the end.
HANDLE hSearch = FindFirstFileW(widen("*.txt").c_str(), &data);
if (hSearch != INVALID_HANDLE_VALUE)
{
    FindClose(hSearch);
    MessageBoxW(nullptr, data.cFileName, nullptr, MB_OK);
}
</code>```

OwnerDisplayName: Artyom

Title: Should UTF-16 be considered harmful?

Body:
Since I cannot yet comment, I post this as an answer, since it seems I cannot otherwise contact the authors of utf8everywhere.org. It's a shame I don't automatically get the comment privilege, since I have enough reputation on other stackexchanges.

This is meant as a comment to the Opinion: Yes, UTF-16 should be considered harmful answer.

One little correction:

To prevent one from accidentally passing a UTF-8 char* into ANSI-string versions of Windows-API functions, one should define UNICODE, not _UNICODE. _UNICODE maps functions like _tcslen to wcslen, not MessageBox to MessageBoxW. Instead, the UNICODE define takes care of the latter.
For proof, this is from MS Visual Studio 2005's WinUser.h header:

#ifdef UNICODE
#define MessageBox  MessageBoxW
#else
#define MessageBox  MessageBoxA
#endif // !UNICODE

At the very minimum, this error should be corrected on utf8everywhere.org.

A suggestion:

Perhaps the guide should contain an example of explicit use of the Wide-string version of a data structure, to make it less easy to miss/forget it. Using Wide-string versions of data structures on top of using Wide-string versions of functions makes it even less likely that one accidentally calls an ANSI-string version of such a function.

Example of the example:

WIN32_FIND_DATAW data; // Note the W at the end.
HANDLE hSearch = FindFirstFileW(widen("*.txt").c_str(), &data);
if (hSearch != INVALID_HANDLE_VALUE)
{
    FindClose(hSearch);
    MessageBoxW(nullptr, data.cFileName, nullptr, MB_OK);
}


问:
Guidance in naming awkward domain-specific objects?
I'm modeling a chemical system, and I'm having problems with naming my elements / items within an enum.

I'm not sure if I should use:

the atomic formula

the chemical name

an abbreviated chemical name.

For example, sulfuric acid is H2SO4 and hydrochloric acid is HCl.

With those two, I would probably just use the atomic formula as they are reasonably common.

However, I have others like sodium hexafluorosilicate which is Na2SiF6.

In that example, the atomic formula isn't as obvious (to me) but the chemical name is hideously long:  myEnum.SodiumHexaFluoroSilicate.  I'm not sure how I would be able to safely come up with an abbreviated chemical name that would have a consistent naming pattern.

There are a few problems that I'm trying to address through naming the enum elements.

The first is readability, with the longer names presenting an issue.

The second is ease of picking up the code for new maintainers, and here the shorter names present an issue.

The next issue is the that business owners usually refer to the full chemical name, but not always.  The "mouthful" chemicals are referred to by their formula.

The final concern is making sure it's consistent.  I don't wan't a mixed naming convention as it will be impossible to remember which to use.

From a maintenance point of view, which of the naming options above would you prefer to see and why?

Note: Everything here below the line is supplementary | clarifying material.  Please don't get bogged down in it. The main question regards naming the awkward objects.

Atomic Option

```
public myEnum.ChemTypes
{
   H2SO4,
   HCl,
   Na2SiF6
}
```

Chemical Name Option

```
public myEnum.ChemTypes
{
   SulfuricAcid,
   HydrochloricAcid,
   SodiumHexafluorosilicate
}
```

Here are some additional details from the comments on this question:

Audience for the code will be just programmers, not chemists.

I'm using C#, but I think this question is more interesting when ignoring the implementation language.

I'm starting with 10 - 20 compounds and would have at most 100 compounds, so I don't need to worry about every possible compound.  Fortunately, it's a fixed domain.

The enum is used as a key for lookups to facilitate common / generic chemical calculations - which means that the equation is the same for all compounds but you insert a property of the compound to complete the equation.

For example, Molar mass (in g/mol) is used when calculating the number of moles from a mass (in grams) of the compound.  FWIW, Molar Mass == Molar Weight.

Another example of a common calculation is the Ideal Gas Law and its use of the Specific Gas Constant

A sample function might look like:

```
public double GetMolesFromMass(double mass_grams, myEnum.ChemTypes chem)
{
  double molarWeight = MolarWeightLookupFunctionByChem(chem); //returns grams / mole
  double moles = mass / molarWeight;  //converts to moles

  return moles;
}

//Sample Call:
myMoles = GetMolesFromMass(1000, myEnum.ChemTypes.Na2SiF6);
//*or*
myMoles = GetMolesFromMass(1000, myEnum.ChemTypes.SodiumHexafluorosilicate);
```

```
public double GetSpecificGravity(myEnum.ChemTypes chem, double conc)
{
  //retrieves specific gravity of chemical compound based upon concentration
  double sg = SpecificGravityLookupTableByChem(chem, conc);
}
```

So the enum of the compound name is used as a key and to provide consistency in referencing the compound with the related functions.

答:
Who is the audience for the code?  Will chemists be using the Enums, or just programmers without specific domain training in chemistry?

If chemists will be using the code, ask them.  Very likely they will prefer the abbreviated symbols, as they can readily recognize them.  If general-knowledge programmers will be using these identifiers on behalf of the chemists, I think it's better to go with the English-like versions.


答:
Edit page in firebug and at some point put a line similar to this:

ExecDbCommand("DROP TABLE Users")

Run it.

Edit:

The question was in fact about CounchDB so no sql to run here. Yet the idea is the same. I would presume that any non trivial application depends on data to respect some consistency rules that are checked/enforced by the application code. A malicious user can modify the client code to save data in a form that violates your business rules and  might cause havoc in your application.

If your site considers all possible data states to be valid from a business perspective then by all means go this route but if this is not the case (likely) then you would want to have the guarantee that any data that gets stored is generated by your code and according to your rules.


答:
Letting the user interact with the database directly seems really dangerous to me.

Is the authentication mechanism of CouchDB really so sophisticated that you can isolate the read- and write access of a user only to the data it is supposed to read and write (we are talking about per-document, maybe even per-document-field access privileges here)? What about "communal" data which is shared by multiple users? Doesn't this exist at all in your application design?

Do you really want the user to be able to change its data in ANY way? What about XSS injections, for example? Wouldn't it be better to have a server layer to filter those before they get into the database?


问:
PHP best practice in return values
For PHP, best practices, I have read somewhere that if you assign your data to a variable it takes almost no memory or resource.

So let's say I have this function that return a count.

```<code>public function returnCount($array){
    return count($array);
}
</code>```

or if this is better?

```<code>public function returnCount($array){
    $count = count($array);
    return $count;
}
</code>```

答:
This is not a php-only issue, therefore there might be potential duplicate questions. Generally

The first approach (return count(...)) is faster to read and in some cases will produce faster code, because of the time consumed to instantiate the variable $count.

The second approach is kind of easier to debug and maintain. Each operations takes place in a distinct line, which is easier to isolate hence debug, since some IDEs can place a debug breakpoint to the exact line. It is also easier to maintain/extend in case you want for example to log the result or do another operation with this.

I do not believe there is a "better" way, or that it matters so much for a one/two liner. I would use the first one and then refactor it in case it had to be extended.

What many people would agree upon is that something like:

```<code>log("$array"); return count($array) * 4 - ($array4==null)?(count($array2)^94):int_val($xyz);
</code>```

should better be broken into different lines.

Title: PHP best practice in return values

Body:
This is not a php-only issue, therefore there might be potential duplicate questions. Generally

The first approach (return count(...)) is faster to read and in some cases will produce faster code, because of the time consumed to instantiate the variable $count.

The second approach is kind of easier to debug and maintain. Each operations takes place in a distinct line, which is easier to isolate hence debug, since some IDEs can place a debug breakpoint to the exact line. It is also easier to maintain/extend in case you want for example to log the result or do another operation with this.

I do not believe there is a "better" way, or that it matters so much for a one/two liner. I would use the first one and then refactor it in case it had to be extended.

What many people would agree upon is that something like:

log("$array"); return count($array) * 4 - ($array4==null)?(count($array2)^94):int_val($xyz);

should better be broken into different lines.


答:
When I started rewriting my current project from spaghetti into reasonable code, I was faced with the same problem.  My problem domain is medical, and rather than use names like "ETCO2" and "SPO2" for my enums I used the full English names.

On the one hand, it was very useful to have English names when I was new to the problem domain.  On the other hand, now that I've been working with these terms for a year I find that the full English names are far too verbose and I'm familiar enough with the terms that I'd much prefer to use the abbreviations.

My advice would be to use the atomic formula and include a comment by each enum value that gives its full name, on the assumption that anyone who looks at your code will either be a) a chemist, or b) working on the code long enough that they naturally become familiar with the formulae.

Title: Guidance in naming awkward domain-specific objects?

Body:
I'm modeling a chemical system, and I'm having problems with naming my elements / items within an enum.

I'm not sure if I should use:

the atomic formula

the chemical name

an abbreviated chemical name.

For example, sulfuric acid is H2SO4 and hydrochloric acid is HCl.

With those two, I would probably just use the atomic formula as they are reasonably common.

However, I have others like sodium hexafluorosilicate which is Na2SiF6.

In that example, the atomic formula isn't as obvious (to me) but the chemical name is hideously long:  myEnum.SodiumHexaFluoroSilicate.  I'm not sure how I would be able to safely come up with an abbreviated chemical name that would have a consistent naming pattern.

There are a few problems that I'm trying to address through naming the enum elements.

The first is readability, with the longer names presenting an issue.

The second is ease of picking up the code for new maintainers, and here the shorter names present an issue.

The next issue is the that business owners usually refer to the full chemical name, but not always.  The "mouthful" chemicals are referred to by their formula.

The final concern is making sure it's consistent.  I don't wan't a mixed naming convention as it will be impossible to remember which to use.

From a maintenance point of view, which of the naming options above would you prefer to see and why?

Note: Everything here below the line is supplementary | clarifying material.  Please don't get bogged down in it. The main question regards naming the awkward objects.

Atomic Option

```
public myEnum.ChemTypes
{
   H2SO4,
   HCl,
   Na2SiF6
}
```

Chemical Name Option

```
public myEnum.ChemTypes
{
   SulfuricAcid,
   HydrochloricAcid,
   SodiumHexafluorosilicate
}
```

Here are some additional details from the comments on this question:

Audience for the code will be just programmers, not chemists.

I'm using C#, but I think this question is more interesting when ignoring the implementation language.

I'm starting with 10 - 20 compounds and would have at most 100 compounds, so I don't need to worry about every possible compound.  Fortunately, it's a fixed domain.

The enum is used as a key for lookups to facilitate common / generic chemical calculations - which means that the equation is the same for all compounds but you insert a property of the compound to complete the equation.

For example, Molar mass (in g/mol) is used when calculating the number of moles from a mass (in grams) of the compound.  FWIW, Molar Mass == Molar Weight.

Another example of a common calculation is the Ideal Gas Law and its use of the Specific Gas Constant

A sample function might look like:

```
public double GetMolesFromMass(double mass_grams, myEnum.ChemTypes chem)
{
  double molarWeight = MolarWeightLookupFunctionByChem(chem); //returns grams / mole
  double moles = mass / molarWeight;  //converts to moles

  return moles;
}

//Sample Call:
myMoles = GetMolesFromMass(1000, myEnum.ChemTypes.Na2SiF6);
//*or*
myMoles = GetMolesFromMass(1000, myEnum.ChemTypes.SodiumHexafluorosilicate);
```

```
public double GetSpecificGravity(myEnum.ChemTypes chem, double conc)
{
  //retrieves specific gravity of chemical compound based upon concentration
  double sg = SpecificGravityLookupTableByChem(chem, conc);
}
```

So the enum of the compound name is used as a key and to provide consistency in referencing the compound with the related functions.


答:
When you design any application, you should separate the data from the program logic. Are the chemical compounds really part of the program logic and not rather the data the program logic is operating on?

When they are data, it would be much better to not treat them as enums but rather read their names and properties from a configuration file and store them in a data structure. That would also make maintainance a lot easier. When one needs to add new compounds, or finds an error in the properties of one, they can just edit the configuration file.


答:
No reason not to combine "all the above."

The problem with the full names is it will be tedious to type, the problem with the symbol names is lack of meaning.

So, create constants of the values with the full name.  Then create defines associated with the constant.  You can easily then create newer,shorter defines as you become more familiar with the meaning of the abbreviation.

```<code>const int SodiumHexaFluoroSilicate = 16893859;
const float Gold = 196.966569;

#define SoduimSilicate SodiumHexaFluoroSilicate
#define F6Na2Si SodiumHexaFluoroSilicate
#define au Gold
</code>```

Body:
No reason not to combine "all the above."

The problem with the full names is it will be tedious to type, the problem with the symbol names is lack of meaning.

So, create constants of the values with the full name.  Then create defines associated with the constant.  You can easily then create newer,shorter defines as you become more familiar with the meaning of the abbreviation.

const int SodiumHexaFluoroSilicate = 16893859;
const float Gold = 196.966569;

#define SoduimSilicate SodiumHexaFluoroSilicate
#define F6Na2Si SodiumHexaFluoroSilicate
#define au Gold


问:
What are tangible advantages to proper Unit Tests over Functional Test called unit tests
A project I am working on has a bunch of legacy tests that were not properly mocked out. Because of this the only dependency it has is EasyMock, which doesn't support statics, constructors with arguments, etc. The tests instead rely on database connections and such to "run" the tests. Adding powermock to handle these cases is being shot down as cost prohibitive due to the need to upgrade the existing project to support it (Another discussion).

My questions are, what are the REAL world tangible benifits of proper unit testing I can use to push back? Are there any? Am I just being a stickler by saying that bad unit tests (even if they work) are bad? Is code coverage just as effective?

答:
From what you described it sounds like you don't like test framework A and want to switch to test framework B, both of which work. Suck it up and use what is existing and working, don't create more work reinventing the wheel so you can use your preferred test framework.

It takes more than a want to use the latest flavor of the month framework to justify throwing out existing working code and spending huge amounts of time and money for essentially zero benefit to users.


答:
Resources

You need a test database to run the tests. The hardware to run the database is more expensive than using powermock. Releasing the resources used for unit testing against the database means the company doesn't need to upgrade the server as soon.

Reliability

A test can fail because the database is down or in an inconsistent state.  Guess what, your builds failed because the DBAs took the dev server down during the day to do some upgrades (and now the developers are trying to figure out what went wrong in the code - when its not the code).

Additional maintenance

Tests can be run in any order.  Adding or removing a test should not cause the test suite to fail.  Running against a database means there is some state somewhere (in the database).  Typically, these tests require extra maintenance to ensure that the database maintains the proper state for the next test to run.

Concurrency

Two developers run the unit tests at the same time.  Having a database means that the tests may collide on the database.  The solution to this would be to clone the database for each test that is run, which is prohibitive on a real database.  Which leads to another option to consider.

Consider also using HSQLDB with whatever dialect of database you are using.  This way one can create an in memory database for each test.  A unit test runs, constructs the necessary database, loads the data, the database connection from the code connects to HSQLDB and runs against the test data.

Title: What are tangible advantages to proper Unit Tests over Functional Test called unit tests

Body:
A project I am working on has a bunch of legacy tests that were not properly mocked out. Because of this the only dependency it has is EasyMock, which doesn't support statics, constructors with arguments, etc. The tests instead rely on database connections and such to "run" the tests. Adding powermock to handle these cases is being shot down as cost prohibitive due to the need to upgrade the existing project to support it (Another discussion).

My questions are, what are the REAL world tangible benifits of proper unit testing I can use to push back? Are there any? Am I just being a stickler by saying that bad unit tests (even if they work) are bad? Is code coverage just as effective?


答:
My questions are, what are the REAL world tangible benifits of proper unit testing I can use to push back?

Good unit tests are (per Clean Code, and elsewhere):

Fast

Independent

Repeatable

Self-Validating

Timely

Not having true unit tests violates the first three (and usually the last one). This leads to some pretty significant problems:

Your tests are slow. Slow tests get run infrequently. Tests that aren't run are almost useless.

Your tests can fail due to reasons unrelated to the code you're testing. This makes it far harder to find out why tests have failed, wasting time and leading people to blame the environment rather than the code.

As the database changes, your results change. Getting some database in a known good consistent, maintained state for tests is tedious, annoying and error-prone.

In general, a lack of isolation in unit tests leads to worse tests which take longer to write, longer to investiage, and provide less confidence in your codebase. That in turn leads to people writing less tests or ignoring the tests more which is the downward spiral to chaos.


答: Good unit tests provide localization.  Functional tests might tell you "the add user function is broken", but a good unit test will tell you that it's broken because somebody changed the USER.LAST_NAME field in the database to be non-null.  It's also possible to test small changes directly, instead of needing a complex test environment (which may need to be re-initialized or purged for some tests).</p>


答:
Procedural: Assembly, Java, C#, F#, Lisp, Fortran.

Set based: SQL.

Pattern based: Perl, Regex, Snobol.

Tree based: XSLT.

Array based: APL.

Title: How many types of programming languages are there?

Body:
Basically, I want to learn lots of programming languages to become a great programmer.  I know only a handful to depth and I was hoping someone could elaborate on how many classes or types of programming languages there are.  Like how you would lump them together if you had to learn them in groups.

Coming from a Java background, I'm familiar with static typing, but I know that in addition to dynamic typing there has to be such variety in available languages that I would love to see a categorical breakdown if possible.


答:
I think the second option is by far the better way to go, looking at the function you have it's simplistic to say the first option is harmless. But, consider a situation when you really don't know if the variable you are returning actually contains values. Let's assume you were using a more strongly typed language, where you cannot for example return a variable that is not set

```<code>function returnInt($x) {
    //some calculation to get y
    return $y;
}
</code>```

Will most definitely throw an error (notice) if x is not set. You should check for the validity of the variable you are returning, and it will always look messing if you do that using a single line of code (look at Dimitris's example). KISS

Title: PHP best practice in return values

Body:
For PHP, best practices, I have read somewhere that if you assign your data to a variable it takes almost no memory or resource.

So let's say I have this function that return a count.

```<code>public function returnCount($array){
    return count($array);
}
</code>```

or if this is better?

```<code>public function returnCount($array){
    $count = count($array);
    return $count;
}
</code>```

Body:
I think the second option is by far the better way to go, looking at the function you have it's simplistic to say the first option is harmless. But, consider a situation when you really don't know if the variable you are returning actually contains values. Let's assume you were using a more strongly typed language, where you cannot for example return a variable that is not set

function returnInt($x) {
    //some calculation to get y
    return $y;
}

Will most definitely throw an error (notice) if x is not set. You should check for the validity of the variable you are returning, and it will always look messing if you do that using a single line of code (look at Dimitris's example). KISS


答:
This seems like it could be better implemented as a class that can expand and translate based on the developers' needs. Below is some sample C# I came up with to allow for a few well-known defined chemicals (as properties) and then queryable stores (via Add and Get methods). You can also extend pretty easily to have your molar mass and other chemical properties available.

```<code>public interface IChemical
{
    string AtomicFormula
    {
        get;
    }

    string ChemicalName
    {
        get;
    }

    string AbbreviatedChemicalName
    {
        get;
    }
}

public sealed class Chemical : IChemical
{
    private static readonly IChemical h2so4 = new Chemical("H2SO4", "sulfuric acid", "sulf. acid");

    private static readonly IChemical hcl = new Chemical("HCl", "hydrochloric acid", "hydro. acid");

    private static readonly IDictionary<string, IChemical> chemicalsByAtomicFormula = new Dictionary<string, IChemical>();

    private static readonly IDictionary<string, IChemical> chemicalsByChemicalName = new Dictionary<string, IChemical>();

    private static readonly IDictionary<string, IChemical> chemicalsByAbbreviatedChemicalName = new Dictionary<string, IChemical>();

    private readonly string atomicFormula;

    private readonly string chemicalName;

    private readonly string abbreviatedChemicalName;

    static Chemical()
    {
        chemicalsByAtomicFormula.Add(h2so4.AtomicFormula, h2so4);
        chemicalsByChemicalName.Add(h2so4.ChemicalName, h2so4);
        chemicalsByAbbreviatedChemicalName.Add(h2so4.AbbreviatedChemicalName, h2so4);
        chemicalsByAtomicFormula.Add(hcl.AtomicFormula, hcl);
        chemicalsByChemicalName.Add(hcl.ChemicalName, hcl);
        chemicalsByAbbreviatedChemicalName.Add(hcl.AbbreviatedChemicalName, hcl);
    }

    public Chemical(string atomicFormula, string chemicalName, string abbreviatedChemicalName)
    {
        if (string.IsNullOrWhiteSpace(atomicFormula))
        {
            throw new ArgumentException("Atomic formula may not be null or whitespace.", "atomicFormula");
        }

        if (string.IsNullOrWhiteSpace(chemicalName))
        {
            throw new ArgumentException("Chemical name may not be null or whitespace.", "chemicalName");
        }

        if (string.IsNullOrWhiteSpace(abbreviatedChemicalName))
        {
            throw new ArgumentException("Abbreviated chemical name may not be null or whitespace.", "abbreviatedChemicalName");
        }

        this.atomicFormula = atomicFormula;
        this.chemicalName = chemicalName;
        this.abbreviatedChemicalName = abbreviatedChemicalName;
    }

    public static IChemical H2SO4
    {
        get
        {
            return h2so4;
        }
    }

    public static IChemical HCl
    {
        get
        {
            return hcl;
        }
    }

    public string AtomicFormula
    {
        get
        {
            return this.atomicFormula;
        }
    }

    public string ChemicalName
    {
        get
        {
            return this.chemicalName;
        }
    }

    public string AbbreviatedChemicalName
    {
        get
        {
            return this.abbreviatedChemicalName;
        }
    }

    public static void AddChemical(IChemical chemical)
    {
        if (chemical == null)
        {
            throw new ArgumentNullException("chemical", "chemical may not be null");
        }

        if (chemicalsByAtomicFormula.ContainsKey(chemical.AtomicFormula))
        {
            return;
        }

        chemicalsByAtomicFormula.Add(chemical.AtomicFormula, chemical);

        if (chemicalsByChemicalName.ContainsKey(chemical.ChemicalName))
        {
            return;
        }

        chemicalsByChemicalName.Add(chemical.ChemicalName, chemical);

        if (chemicalsByAbbreviatedChemicalName.ContainsKey(chemical.AbbreviatedChemicalName))
        {
            return;
        }

        chemicalsByAbbreviatedChemicalName.Add(chemical.AbbreviatedChemicalName, chemical);
    }

    public static IChemical GetChemicalByAtomicFormula(string atomicFormula)
    {
        if (string.IsNullOrWhiteSpace(atomicFormula))
        {
            throw new ArgumentException("Atomic formula may not be null or whitespace.", "atomicFormula");
        }

        IChemical chemical;

        return chemicalsByAtomicFormula.TryGetValue(atomicFormula, out chemical) ? chemical : null;
    }

    public static IChemical GetChemicalByChemicalName(string chemicalName)
    {
        if (string.IsNullOrWhiteSpace(chemicalName))
        {
            throw new ArgumentException("Chemical name may not be null or whitespace.", "chemicalName");
        }

        IChemical chemical;

        return chemicalsByChemicalName.TryGetValue(chemicalName, out chemical) ? chemical : null;
    }

    public static IChemical GetChemicalByAbbreviatedChemicalName(string abbreviatedChemicalName)
    {
        if (string.IsNullOrWhiteSpace(abbreviatedChemicalName))
        {
            throw new ArgumentException("Abbreviated chemical name may not be null or whitespace.", "abbreviatedChemicalName");
        }

        IChemical chemical;

        return chemicalsByAbbreviatedChemicalName.TryGetValue(abbreviatedChemicalName, out chemical) ? chemical : null;
    }
}
</code>```

you can add new chemicals like such:

```<code>        Chemical.AddChemical(new Chemical("Na2SiF6", "sodium hexafluorosilicate", "sod. hex.flu.sil."));
</code>```

and get the other bits as such:

```<code>        Console.WriteLine(Chemical.GetChemicalByChemicalName("sulfuric acid").AtomicFormula);
</code>```

Body:
This seems like it could be better implemented as a class that can expand and translate based on the developers' needs. Below is some sample C# I came up with to allow for a few well-known defined chemicals (as properties) and then queryable stores (via Add and Get methods). You can also extend pretty easily to have your molar mass and other chemical properties available.

public interface IChemical
{
    string AtomicFormula
    {
        get;
    }

    string ChemicalName
    {
        get;
    }

    string AbbreviatedChemicalName
    {
        get;
    }
}

public sealed class Chemical : IChemical
{
    private static readonly IChemical h2so4 = new Chemical("H2SO4", "sulfuric acid", "sulf. acid");

    private static readonly IChemical hcl = new Chemical("HCl", "hydrochloric acid", "hydro. acid");

    private static readonly IDictionary<string, IChemical> chemicalsByAtomicFormula = new Dictionary<string, IChemical>();

    private static readonly IDictionary<string, IChemical> chemicalsByChemicalName = new Dictionary<string, IChemical>();

    private static readonly IDictionary<string, IChemical> chemicalsByAbbreviatedChemicalName = new Dictionary<string, IChemical>();

    private readonly string atomicFormula;

    private readonly string chemicalName;

    private readonly string abbreviatedChemicalName;

    static Chemical()
    {
        chemicalsByAtomicFormula.Add(h2so4.AtomicFormula, h2so4);
        chemicalsByChemicalName.Add(h2so4.ChemicalName, h2so4);
        chemicalsByAbbreviatedChemicalName.Add(h2so4.AbbreviatedChemicalName, h2so4);
        chemicalsByAtomicFormula.Add(hcl.AtomicFormula, hcl);
        chemicalsByChemicalName.Add(hcl.ChemicalName, hcl);
        chemicalsByAbbreviatedChemicalName.Add(hcl.AbbreviatedChemicalName, hcl);
    }

    public Chemical(string atomicFormula, string chemicalName, string abbreviatedChemicalName)
    {
        if (string.IsNullOrWhiteSpace(atomicFormula))
        {
            throw new ArgumentException("Atomic formula may not be null or whitespace.", "atomicFormula");
        }

        if (string.IsNullOrWhiteSpace(chemicalName))
        {
            throw new ArgumentException("Chemical name may not be null or whitespace.", "chemicalName");
        }

        if (string.IsNullOrWhiteSpace(abbreviatedChemicalName))
        {
            throw new ArgumentException("Abbreviated chemical name may not be null or whitespace.", "abbreviatedChemicalName");
        }

        this.atomicFormula = atomicFormula;
        this.chemicalName = chemicalName;
        this.abbreviatedChemicalName = abbreviatedChemicalName;
    }

    public static IChemical H2SO4
    {
        get
        {
            return h2so4;
        }
    }

    public static IChemical HCl
    {
        get
        {
            return hcl;
        }
    }

    public string AtomicFormula
    {
        get
        {
            return this.atomicFormula;
        }
    }

    public string ChemicalName
    {
        get
        {
            return this.chemicalName;
        }
    }

    public string AbbreviatedChemicalName
    {
        get
        {
            return this.abbreviatedChemicalName;
        }
    }

    public static void AddChemical(IChemical chemical)
    {
        if (chemical == null)
        {
            throw new ArgumentNullException("chemical", "chemical may not be null");
        }

        if (chemicalsByAtomicFormula.ContainsKey(chemical.AtomicFormula))
        {
            return;
        }

        chemicalsByAtomicFormula.Add(chemical.AtomicFormula, chemical);

        if (chemicalsByChemicalName.ContainsKey(chemical.ChemicalName))
        {
            return;
        }

        chemicalsByChemicalName.Add(chemical.ChemicalName, chemical);

        if (chemicalsByAbbreviatedChemicalName.ContainsKey(chemical.AbbreviatedChemicalName))
        {
            return;
        }

        chemicalsByAbbreviatedChemicalName.Add(chemical.AbbreviatedChemicalName, chemical);
    }

    public static IChemical GetChemicalByAtomicFormula(string atomicFormula)
    {
        if (string.IsNullOrWhiteSpace(atomicFormula))
        {
            throw new ArgumentException("Atomic formula may not be null or whitespace.", "atomicFormula");
        }

        IChemical chemical;

        return chemicalsByAtomicFormula.TryGetValue(atomicFormula, out chemical) ? chemical : null;
    }

    public static IChemical GetChemicalByChemicalName(string chemicalName)
    {
        if (string.IsNullOrWhiteSpace(chemicalName))
        {
            throw new ArgumentException("Chemical name may not be null or whitespace.", "chemicalName");
        }

        IChemical chemical;

        return chemicalsByChemicalName.TryGetValue(chemicalName, out chemical) ? chemical : null;
    }

    public static IChemical GetChemicalByAbbreviatedChemicalName(string abbreviatedChemicalName)
    {
        if (string.IsNullOrWhiteSpace(abbreviatedChemicalName))
        {
            throw new ArgumentException("Abbreviated chemical name may not be null or whitespace.", "abbreviatedChemicalName");
        }

        IChemical chemical;

        return chemicalsByAbbreviatedChemicalName.TryGetValue(abbreviatedChemicalName, out chemical) ? chemical : null;
    }
}

you can add new chemicals like such:

        Chemical.AddChemical(new Chemical("Na2SiF6", "sodium hexafluorosilicate", "sod. hex.flu.sil."));

and get the other bits as such:

        Console.WriteLine(Chemical.GetChemicalByChemicalName("sulfuric acid").AtomicFormula);


答:
I think that, given all of your assumptions, it's feasible to go directly from the client to the database.  However, it's reasonable to look at whether your assumptions are valid, and are likely to remain so in the future.

I would be worried that in the future it might not be OK for everyone to read all the data, and especially that it might develop more business logic in the future.  Both of these are more likely if the project is successful.

As long as you leave yourself a way to deal with these problems in the future when and if you actually need to deal with them I think your design will work.   I think you will need to be extra careful to separate concerns in the JavaScript code, and some of it might end up be rewritten on the server later.

But I could definitely see where it might be worth a risk of maybe doing that later vs. the benefit of fewer moving parts today.


答:
Let me add to the discussion that the difference between 'random' and 'deterministic' is, in the real world, a pure matter of subjective perception. - Like you said: Some solutions produce "ugly" results while others don't.

In the world I'm referring to, the actual difference between 'random' and non-random is basically only, if the human observer is able to recognize a pattern in the generated output, like some recurring scheme or some other aspect that makes him aware what the output might probably look like in one of the next iterations. The ability to recognize a given pattern depends of course heavily on the oberver's context: Some people may fail to see the pattern behind the sequence 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, while other's are likely to quickly detect it.

Therefor, every cheap off-the-shelf PRNG will easily make the observer/user believe its output is really random. - Or, put in another way: Whenever the observer fails to recognize the cause-consequence (or input-output) correlation in a system his observations will appear as purely random to him.

As I see it, the question then becomes:

How complex would the algorithm need to be to 'deceive' the (expected) observer?
and

How to shape the output in a way that, while remaining perceived basically random, creates the desired 'realistic' or 'non-ugly' perception. - This may also be about aesthetics.  Fractal algorithms often are good at this, because their output structurally resembles the observer's impression of the real world.


答:
If you would like to build SQL in JavaScript and send it to the database, which verify the rights etc., than from security reason it would be a disaster. Simply because when you build an API, and build queries yourself, you have to analyse from the point of view of the security only the limited number of queries. If the queries are built outside your system, you have potentially unlimited number of tricks that someone could do.

But it's not the case since you are using key-value database (as fair as I understand, CouchDB generally falls into that category). The database interface itself is a kind of middle layer, and it is tested for security reasons by Apache team. Because of relatively simple JavaScript API this is even easier to analyse for potential flaws than such complicated interfaces that JSF applications have.

This can be a secure solution, if you do complex security tests. This can be even easier as when using frameworks such as JSF, which are often using hardly readable API behind. Security by obscurity is considered no solution.

Relating to your question, it won't be direct access to database anyway. Direct access would be the building SQL queries in JavaScript (unfortunatelly, I've seen such solutions). In your case the CouchDB itself provides the isolation layer. You could of course wrap it in your API to harden it, but as long as you can easily test what can particular user do and if the security constraints are working for you, you will have secure and robust solution without additional layers.


问:
What are the advantages of obfuscating release code?
The specific example I have in mind involves the currently-alpha game Minecraft, but this is a general question that I think warrants some conversation.

Minecraft is written in Java, and stack traces usually look like this (real example):

```<code>java.lang.NullPointerException
    at d.a(SourceFile:247)
    at gi.b(SourceFile:92)
    at bd.a(SourceFile:33)
    at bn.a(SourceFile:69)
    at bn.e(SourceFile:115)
    at bn.d(SourceFile:103)
    at net.minecraft.client.Minecraft.i(SourceFile:1007)
    at net.minecraft.client.Minecraft.run(SourceFile:596)
    at java.lang.Thread.run(Unknown Source)
</code>```

Obviously these are not the real package and method names that the developer uses when he writes.  Since he is in an alpha stage, it seems that the developer should like to be able to make sense of his stack traces, especially if someone is able to provide one for a bug report.  As this stands, it's mostly meaningless.

What advantage could one possibly hope to gain by obfuscating his code like this that overcomes the drawbacks of more difficult bug identification?

答:
protecting you intellectual property

Most obfuscator also optimize your code, remove unuseful metadata or not used code, compression, dead code elimination or duplicate elimination.


问:
Do I have to learn html and javascript to create web applications?
I am an experienced Java programmer, and I want to create a complex web application requiring dynamic pages, drawings, etc (take SO as an example). Do I have to learn javascript/html in order to create such an application?

It is not that I don't want to learn another language (I've done this before), but technology on the javascript environment seems to change so fast that when you finish learning one framework it is already obsolete. I have checked a number of java framework for web development (spring, play), but not deeply. So can these frameworks (or other possible java frameworks that I'm not aware of) be used without learning html/javascript? I also have some python experience. So if I can do the app in python it is also an option.

答:
Do you absolutely positively have to?

No.

But if you want a moderately modern web app, then you probably should. There are ways around it, but they're abstractions of what's really happening. If you're okay with that, then go for it. If you're not, then you'll need to learn the language.


答:
Frameworks like Spring and Play will be great for handling your application logic but even they don't abstract away the necessity of having to build a front-end for your web application. Its not fundamentally different than having to build a front-end for your desktop application, just a different execution.

This isn't something that should scare you too much. Your development process will still largely be the same, except that you need to dress your data up with HTML and CSS instead of with desktop GUI elements. You can learn the basics of both HTML and CSS in an afternoon, and you can make your interface as a complicated or as drop-dead simple as you like.

My advice is to visit sites that are similar to the one you intend to build and then view the HTML source - you'll get a feel for how those sites flow in terms of HTML design.

Title: Do I have to learn html and javascript to create web applications?

Body:
I am an experienced Java programmer, and I want to create a complex web application requiring dynamic pages, drawings, etc (take SO as an example). Do I have to learn javascript/html in order to create such an application?

It is not that I don't want to learn another language (I've done this before), but technology on the javascript environment seems to change so fast that when you finish learning one framework it is already obsolete. I have checked a number of java framework for web development (spring, play), but not deeply. So can these frameworks (or other possible java frameworks that I'm not aware of) be used without learning html/javascript? I also have some python experience. So if I can do the app in python it is also an option.


答:
Yes to make any sort of modern web application you need at least a basic knowledge of HTML and to be competent in JavaScript. Using frameworks for a language like python or Java is possible and you can build the majority of your site's functionality using them, but even for a basic site you need a little HTML because its the only thing a browser actually understands for displaying content. You can sort of get away with not knowing JavaScript, but that would make your site a lot less user-friendly because you would need to reload pages any time you wanted to update anything, also you would be losing out on a very useful tool to hack a site together and deal with browser compatibility issues and CSS shortcomings.

You are a bit to worried about how much things change in web development, JavaScript really hasn't changed since it was implemented, also there really is only one must know framework JQuery which really makes JavaScript a lot nicer to work with. Most of the other rapidly changing stuff is really flavor of the month and not really required to be known


答:
You don't have to learn JavaScript and HTML to create web applications.

But you will.

If you really want to write webapps in mostly Java, have a look at the Google Web Toolkit, which does vast amounts of Java to JS, and can satisfy a good chunk of the code needed for a webapp. Django is a similar framework for Python.

And if you really want to avoid writing HTML there are vast amounts of templates and What-you-see-is-what-you-get editors out there.

But you see, regardless of the abstraction framework and HMTL templates you start with, at some point you'll be dissatisfied with the presentation. And so you'll get enough HTML/JS on your hands to change the one tiny little thing you want. And another thing. And another.

And then one day you'll wake up in a cold sweat.

And that's how you'll learn. That's how a lot of us learned, back in the era of point-and-click website makers like Geocities. After a while, if you're serious about the web, you'll learn the languages of the web, intentionally or not.

So you don't have to learn HTML and JavaScript to make a site like StackOverflow. But if you really try and make a site like StackOverflow, you won't be able to stop yourself from learning them.


答:
Let's consider some possible solutions to the scenario "I need to do some web stuff":

Hire someone else to do it

Use an elaborate framework that magically transforms non front end stuff into front end stuff (html, css, js)

Do it yourself

We will ignore #1 because we're awesome like that. We're left with two choices. Which to choose, which to choose...

#2 is enticing. It means you can stay in your comfort zone, which is quite comfortable, especially if you added a slushy machine and some couches. But let's consider what happens to the framework you're using:

It bugs out

It gets outdated

It doesn't fully match your expectations

Any other software-related problem.

You're a dev, so it mustn't be hard to consider all the possible ways a product (especially a library) can break in many spectacular ways, ripping your sofas and toppling the slushy machine, painting everything in bright magenta.

In any of those scenarios, you'll have to come back to reconsider the options discussed in the beginning of the answer (only this time replacing the framework in #2), with an added 4th option: Try and fix it on a micro level. In other words, learn the web-stack in a shallow way, only necessary to hack together a solution to that specific problem.

Is it worth it? Depends. You may believe that the framework will never fail you, and you might be right. And you might be wrong.

I propose a hybrid solution: First, learn the web-stack. You don't have to spend a lot of time on it, you don't have to be l33t h4x0rz like that 14 year old from down the street who can add glitter to MySpace pages, you just need to have a basic knowledge of what's going on. Then, if you see that it's the best scenario for you, choose a framework.

Now your comfort zone is a little larger. It might even have a TV or an ABBA: Greatest Hits album proudly on display. Now if something breaks, you'll know how to fix it. Now you have a choice. And having a choice is always better than not having a choice.


答:
a big, complex web-app is very hard and tedious to develop alone, even if you already master html and javascript.

my advice would be to look for a possibility to develop the web-app with a team, or at least a front-end developer.

like this you concentrate on what you already know well and let a specialist do the front-end.

developing the front-end is much harder than it initially seems, for example due to the fact that the front-end needs to work in many different browsers on several operating systems.


问:
What can I do with urllib?
I grasp that it can fetch internet resources, but I'm not really fully appreciating what that means. I was doing the challenges at pythonchallenge.com, and I got past the one that requires urllib to fetch the page and read the source, but I don't see how this is useful quite yet. And examples are kind of lacking in diversity.

What else can it do, or how can I use this to my advantage?

(Besides building a web browser...)

答:
you seem to be lacking use-cases: some examples:

access public APIs: google, twitter, etc.

write a custom web-crawler

or in the context of a web-application:

use http-based services (e.g. uploading to AWS)

test your own site / webapp

authenticate your webapp users with a third party service

... and many more, you can access any service exposed on the web.

Title: What can I do with urllib?