问:
Try/Catch or test parameters

Possible Duplicate:

  Arguments for or against using Try/Catch as logical operators

  Efficient try / catch block usage?

I was recently on a job interview and I was given a task to write simple method in C# to calculate when the trains meet.  The code was simple mathematical equation.
What I did was that I checked all the parameters on the beginning of the method to make sure, that the code will not fail.

My question is: Is it better to check the parameters, or use try/catch?

Here are my thoughts:

Try/catch is shorter

Try/catch will work always even if you forget about some condition

Catch is slow in .NET

Testing parameters is probably cleaner code (Exceptions should be exceptional)

Testing parameters gives you more control over return values

I would prefer testing parameters in methods longer than +/- 10 lines, but what do you think about using try/catch in simple methods just like this – i.e. return (a*b)/(c+d);

There are many similar questions on stackexchnage, but I am interested in this particular scenario.

答:
It depends on how specific you want to be about the cause of the problem.  If you test up front, you can raise an exception indicating precisely which inputs is in error.  However, if you are performing floating-point computations,  es careful examination of the method body is needed to determine which inputs are valid.  This may not always be feasible.  Your post does not fully express the complexity of your simple example:

```<code>(a * b) / (c + d)
</code>```

It is not enough to simply test that c + d != 0.  If these are floating-point numbers, you also have a possibility for overflow when a * b is much larger than c + d.

In numeric computations, it is often impossible to tell whether the inputs can produce a result without performing the computation.

Generally I prefer to write straight-line code and either allow exceptions to propagate, or else catch them and convert them to something meaningful to the caller.

I seldom worry about the slowness of language feature until there is a known performance problem.

Title: Try/Catch or test parameters

Body:
It depends on how specific you want to be about the cause of the problem.  If you test up front, you can raise an exception indicating precisely which inputs is in error.  However, if you are performing floating-point computations,  es careful examination of the method body is needed to determine which inputs are valid.  This may not always be feasible.  Your post does not fully express the complexity of your simple example:

(a * b) / (c + d)

It is not enough to simply test that c + d != 0.  If these are floating-point numbers, you also have a possibility for overflow when a * b is much larger than c + d.

In numeric computations, it is often impossible to tell whether the inputs can produce a result without performing the computation.

Generally I prefer to write straight-line code and either allow exceptions to propagate, or else catch them and convert them to something meaningful to the caller.

I seldom worry about the slowness of language feature until there is a known performance problem.


问:
Should I leave href empty when implementing click events via jQuery?
Is it preferable to have # in a link's href attribute when I am implementing the click event via jQuery, or is it ok to leave href empty?

i.e.

```<code>id="myLink" href="#" />
</code>```

vs

```<code>id="myLink" href="" />
</code>```

When I'm doing

```<code>$("#myLink").on('click', function() {
   // do ajaxy stuff
});
</code>```

Although I understand the click event could be on a span or other such element I'm interested in this case for particular best practices when using an a tag.

答:
Yannis' answer is a good one, but I still don't know why anyone would need to use href...> tags for events at all. You can use pretty much any tag you can throw an id into for events, thereby removing the whole 'href="" is legal' discussion or employing code to prevent the link being followed.

On the other hand, if it's a link then use href="...">

ContentLicense: CC BY-SA 3.0

Body:
Is it preferable to have # in a link's href attribute when I am implementing the click event via jQuery, or is it ok to leave href empty?

i.e.

```<code><a id="myLink" href="#" />
</code>```

vs

```<code><a id="myLink" href="" />
</code>```

When I'm doing

```<code>$("#myLink").on('click', function() {
   // do ajaxy stuff
});
</code>```

Although I understand the click event could be on a span or other such element I'm interested in this case for particular best practices when using an a tag.

Body:
Yannis' answer is a good one, but I still don't know why anyone would need to use <a href...> tags for events at all. You can use pretty much any tag you can throw an id into for events, thereby removing the whole 'href="" is legal' discussion or employing code to prevent the link being followed.

On the other hand, if it's a link then use <a href="...">


问:
Is there a quick and practical (hands on) way to learn another programming language?
Due to rather strange circumstances, I only have until Monday to learn (at least) the basics of PHP and .NET programming. I'm already fairly competent (though there is a lot of room for improvement) in C++ so I feel I have some of the concepts nailed already, but I need to get into the two languages in a bit more depth in a very short time frame.

Unfortunately I won't have time to get any books so will need to exclusively use online resources, I'm more of a 'do-er' so any way to test my skills in a practical way would be a huge bonus :-)

答:
Well, the good news is that you already know how to program. The vast majority of that knowledge transferrs between languages.

Read the wiki articles on both. It would tell you the basic things you might be missing. Like how .NET isn't a language.

I won't have time to get any books

Yes you do. You have a full weekend. Stop everything else. Swing by a store. Buy two. Read like you mean it.

And this is the most important part: CODE SOME PHP (with .NET). Hit the tutorials, make some small projects, hit some walls, log some bugs, solve those bugs, and overcome your ignorance. Port some of your C++ programs into PHP. You've ALREADY solved how to do the problem, this is just translating. If you want to learn how to program in PHP, the best advice I can give you is to go program in PHP.

Will you "know" PHP by Monday? No, of course not. Who are you kidding? And don't lie to anyone by claiming otherwise. But you WILL have more knowledge then you had Friday. And you WILL have learned a lot.


问:
Why do we sign a .JAR ? or a tag on github?
I have a question :

Why do I need to sign a .JAR using jarsigner?

is there a specific reason or use of that ?

Same question when I tag a version on github ?

答:
If you sign a JAR with your private key, you can guarantee that it comes form you -- same with a commit tag.  The way this works is that you have a pair of keys: public and private.  These keys decrypt each other.  If you sign your jar with your private keys, others can decrypt the signature with your public key and since, presumably, no one has your private key, they can be pretty sure it comes from you.

Now, there is an ever cooler layer which you may or may not be interested in.  Say you want to guarantee that your jar can only be used by the person you intend it for.  You can first sign the jar with your private key, so that they know it's from you, then encrypt (different form signing) the jar (or message -- the more common use case for this is an email) with their public key.  Now, only the person you intend the message for can decrypt it since only they have access to their private key.

This is how public/private key encryption works.

Why is this important?  Some services, take the Android Play Store for example, require you to sign your jar (apk) before submitting it to add a layer of security.  In the case of jars and commit messages, the code you are signing is not actually encrypted as would be the case if you're trying to send a private email or packaging an iOS app.  You are simply adding a virtual signature to your work generated by hashing the input jar or commit message/digest and encrypting that with your private key.  Thus, no one else can generate the same signature as you (save in the extremely unlikely event of a collision).

By attaching your signature to the code, you are saying that you are responsible for it.  If I somehow got a hold of the Facebook developer account for the Play Store, I can't just upload a new Facebook app update that sends me 100s of millions of users' information because I would be unable forge Facebook's signature without their heavily protected private key.  It's the same idea for commit messages.  You are keeping a record of who does what.  You can hold people responsible and on top of that prevent unauthorized people from committing code.


问:
Does a mobile app need more access than the public API of a site?
I have a site with a public API, and some mobile app developers have been brought in to produce an iPhone app for the site. They insist they need to see the database schema, but as I understand it, they should only need access to the documented public API.

Am I right? Is there something I've missed? I've told them that if there's a feature missing or data they require I can extend the API so that they can access it. I thought a web service API held to much the same principles as OOP object API's, in that the implementation details should be hidden as much as possible.

I'm not a mobile app developer so if there is something I don't quite see then please let me know. Any insight or help will be much appreciated.

Update: The mobile team are part of a government funded advisory service for start ups. I've since found out that the project manager, who was the one pushing so hard to see the database and other internals, also works for a web development agency. I can't say for sure what his reasons were for wanting to see this stuff, but considering he didn't once give a valid technical reason I find this even more concerning than I did at the time.

答:
They might want to see the schema so that they can replicate it on the mobile device.  That will save them some work.  Additionally, seeing the schema might prevent them from making wrong assumptions about how their data should be structured based on potentially-incomplete information about the database.

However, they should really come up with their own schema designed around the structure of the API data that's designed to work within the constraints of the device.  A SQL server typically has magnitudes more processing power and storage space than a phone, so why replicate the backend structure when the client device simply doesn't have the capacity to cope with it?  If they're working on iOS and using CoreData, trying to think in a SQL-like way is potentially counter-productive as they'll be dealing with a graph of hierarchical objects, not a collection of tables.

I'd argue that the developers should have no more knowledge of the backend than they can get from looking at the API and browsing its documentation.  I agree with you entirely: the API hides implementation details that the mobile developers shouldn't need to worry about.  As a bonus, forcing them to work with the API will very quickly highlight any design problems and bugs.

(I'm a former backend/web frontend developer who switched to mobile work.)


答:
Frankly, if you know C++ then you know C, and so you practically know PHP. You need to learn the very basics of the language that are different - like scoping and types, and you need to know the environment PHP runs in - like POST variables, and you need to know libraries - like regex and soap.

You should also need to know how to get it going, so install xampp and write some code to do hello world at the very least.

You don't need books for all this - php.net has most of it ready for you as reference material. The rest can be learned from any site that google returns from "PHP tutorial"

Edit:
The OP's question isn't "how do I become proficient in PHP", its "how do I learn just enough to blag my way to a job"... PHP syntax is a lot like C, no-one can deny that. He doesn't need to know OO techniques or MVC frameworks or anything like that - just the absolute basics, and those are procedural, just like C (not that I meant that, I meant the syntax is like C)

Title: Is there a quick and practical (hands on) way to learn another programming language?

Body:
Due to rather strange circumstances, I only have until Monday to learn (at least) the basics of PHP and .NET programming. I'm already fairly competent (though there is a lot of room for improvement) in C++ so I feel I have some of the concepts nailed already, but I need to get into the two languages in a bit more depth in a very short time frame.

Unfortunately I won't have time to get any books so will need to exclusively use online resources, I'm more of a 'do-er' so any way to test my skills in a practical way would be a huge bonus :-)


答:
I suggest the project learning method.  Find a small project that you know you can do (Do create a simple blog system, don't create an in-depth framework, etc):

Create the basics.

Add something new to the project scope that you don't know how to do.

Learn and implement it.

Repeat.


答:
Am I right? Is there something I've missed?

You're right. There may or may not be something you've missed in the API, but there's nothing peculiar about writing a mobile app that would require the developers to know what your database schema looks like. On the contrary, the more they rely on your public API and the less they rely on private implementation details like your database schema, the better. Ideally, they shouldn't need to know anything about how your service works. The whole point of having a public Application Program Interface is to avoid apps needing to rely on private information.

All that said, it's possible that your API doesn't provide everything that's necessary to implement whatever features the mobile app guys have in mind. Unless they're really unreasonable, they should be able to appreciate the benefit (to them as well as to you) of writing to a public interface, so they should be willing to a) read and work with your API, and b) work with you to fix any holes in the API.

Title: Does a mobile app need more access than the public API of a site?

Body:
I have a site with a public API, and some mobile app developers have been brought in to produce an iPhone app for the site. They insist they need to see the database schema, but as I understand it, they should only need access to the documented public API.

Am I right? Is there something I've missed? I've told them that if there's a feature missing or data they require I can extend the API so that they can access it. I thought a web service API held to much the same principles as OOP object API's, in that the implementation details should be hidden as much as possible.

I'm not a mobile app developer so if there is something I don't quite see then please let me know. Any insight or help will be much appreciated.

Update: The mobile team are part of a government funded advisory service for start ups. I've since found out that the project manager, who was the one pushing so hard to see the database and other internals, also works for a web development agency. I can't say for sure what his reasons were for wanting to see this stuff, but considering he didn't once give a valid technical reason I find this even more concerning than I did at the time.


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
Processing Time

My user's time is not cheap.  What comes around goes around.

I just upgraded an application I use this last year.  They had completely rewritten the app, and boy was it slow.  I finally had to buy a new computer to run it quickly.  I guarantee you that wasn't cheap, but my time is more valuable.

ContentLicense: CC BY-SA 2.5

Title: What do you optimize for?


答:
I think reading computer books page by page is mostly a waste of time.  Most specific technology books I have seen, if not all, are stuffed with fluff and unnecessary fat to make it sell at a higher price as there is a corellation between the price and number of pages (IMO, the relationship should be reverse to encourage brevity).

My advice to you is to find a nice online hands-on tutorial, which I am sure are plentiful for PHP, kick back and learn the basics while building a pilot app, not read theory.  What I do find to currently be lacking online (or perhaps an opportunity from a different perspective) is an online tutorial boutique, where you can choose from many options and technologies.  And where users could create and publish their own tutorials.  I think that would be pretty cool but I don't know of any existing ones.

But if you are good with other languages, I am sure the learning curve will be gentle for you.  Best of luck.


问:
OOD: All classes at bottom of hierarchy contain the same field
I am creating a class diagram for what I thought was a fairly simple problem. However, when I get to the bottom of the hierarchy, all of the classes only contain one field and it is the same one.

This to me looks very wrong, but this field does not belong in any of the parent classes. I was wondering if there are any suggested design patterns in a situation like this?

A simplified version of the class diagram can be found below.

Note, fields named differently cannot belong to any other class

```<code>                        +------------------+
                        |   NoteMapping    |
                        |------------------|
                        | String noteId    |
                        | String content   |
                        |                  |
                        +---------+--------+
                                  |
                  +---------------+----------------+
                  |                                |
         +--------|--------+              +--------|--------+
         |     UserNote    |              |    AdminNote    |
         |-----------------|              |-----------------|
         | String userId   |              | String adminId  |
         |                 |              |                 |
         +--------+--------+              +--------+--------+
                  |                                |
                  |                                |
         +--------|--------+              +--------|--------+
         |  UserBookNote   |              |  AdminBookNote  |
         |-----------------|              |-----------------|
         | String bookId   |              | String bookId   |
         |                 |              |                 |
         +-----------------+              +-----------------+
</code>```

ASCII tables drawn using http://www.asciiflow.com/

Edit

I have added some class and field names to the class diagram above.

The reason bookId cannot exist in any of the parent classes is because it is used to create a OneToOne relationship with another class - which is not something that we always want to do.

答:
Sometimes code duplication is a good practical approach.

Did I really write that? Don't shot me now, listen first.

As stated several times: without a concrete case it's hard to tell, but sometimes it is easier to live with the consequences of a little duplication. When it comes to a special case, C++ developer shout: multiple inheritence, while Java enthusiasts hum Generics. I say KIS - keep it simple. Not too simple, i.e. not simpler as the problem itself, but neither more complex! IMO you gain more benefit of clear structures than of a generic system that may cover everything (at the costs of readability).


问:
Is testable code actually more stable?
A google scholar search turns up numerous papers on testability, including models for computing testability, recommendations for how ones code can be more testable, etc.

They all come with the assertion that more testable code is more stable, however I can't find any studies which actually demonstrate this.

I tried looking for studies evaluating the effect of testable code vs. quality, however the closest I can find is Improving the Testability of Object Oriented Systems, which discusses the relationship between design flaws and testability.

Is testable code is actually more stable? And more importantly, how strong is this relationship?

Please back up your answers with references or evidence to back up your claim.

For example, there is a lot of study regarding the relationship of cyclomatic complexity and defect rate. Troster finds a correlation of r = .48

There are metrics for "testability", such as code coupling. I'm looking for research conclusions relating these to defect rate. Ideally I would love a graph plotting some measure of testability vs. defect rate.

答:
In the revised 1995 edition of "The Mythical Man-Month", by Fredericks Brooks, JR., Brooks says that in the following book:

```<code>Jones, C., Assessment and Control of Software Risks. Engle-
wood Cliffs, N.J.: Prentice-Hall, 1994. p. 619.
</code>```

... Casper Jones "offers data that show a strong correlation between lack of systematic quality controls and schedule disasters."

Maybe in that Jones' book you will find the research conclusions you are looking for since "schedules disasters" are in part, Brooks dixit, caused by lack of productivity influenced by an inefficient proccess of defect detection and correction.

Hope it helps.

Title: Is testable code actually more stable?

Body:
In the revised 1995 edition of "The Mythical Man-Month", by Fredericks Brooks, JR., Brooks says that in the following book:

Jones, C., Assessment and Control of Software Risks. Engle-
wood Cliffs, N.J.: Prentice-Hall, 1994. p. 619.

... Casper Jones "offers data that show a strong correlation between lack of systematic quality controls and schedule disasters."

Maybe in that Jones' book you will find the research conclusions you are looking for since "schedules disasters" are in part, Brooks dixit, caused by lack of productivity influenced by an inefficient proccess of defect detection and correction.

Hope it helps.


答:
It sounds as if they just want to understand the domain model.

Perhaps if you provide them an entity relationship diagram in UML with all domain classes and their relationships then they will have a thorough understanding of everything they need to know.  That is in fact all that they do need to know and an argument can be made about protecting sensitive trade secrets here as well.

I have seen such things requested through internal departments where clients of a web service API in another department demanded all of their project documentation before they started, and their reasoning was that this particular group of developers in charge of these web services had a notorious reputation for developing awful untested software.  When other teams encountered problems with their poorly documented web services, they needed to understand as much about their system as possible so that the client group would be able to self diagnose and point the web service group into what they are doing wrong.

This mobile team probably isn't satisfied with mocking your web services because they may have been burned in the past by previous web service developer groups that did a poor job.  When their integration tests start failing against your environment, they won't be able to tell their superiors that they have completed their tasks, so instead they probably want a full featured web service environment that they control so that they can run their integration tests successfully without needing your involvement.


问:
Which is more maintainable -- boolean assignment via if/else or boolean expression?
Which would be considered more maintainable?

```<code>if (a == b) c = true; else c = false;
</code>```

or

```<code> c = (a == b);
</code>```

I've tried looking in Code Complete, but can't find an answer.

I think the first is more readable (you can literally read it out loud), which I also think makes it more maintainable. The second one certainly makes more sense and reduces code, but I'm not sure it's as maintainable for C# developers (I'd expect to see this idiom more in, for example, Python).

答:
First, realize that your two forms are not equivalent.

```<code>if (a == b) c = true;
</code>```

c will be set to true if a is equal to b, and if not, its value will remain whatever it already is.

```<code>c = (a == b);
</code>```

c will be set to true if a is equal to b, and if not, it will be set to false.

If you want the equivalent of the second form, in the style of the first form, you need to write it like this:

```<code>if (a == b) {
  c = true;
} else c = false;
</code>```

Now it's clear which of the two is more readable, more maintainable, and less likely to introduce bugs if something is changed.  Stick with the second form.

Body:
First, realize that your two forms are not equivalent.

if (a == b) c = true;

c will be set to true if a is equal to b, and if not, its value will remain whatever it already is.

c = (a == b);

c will be set to true if a is equal to b, and if not, it will be set to false.

If you want the equivalent of the second form, in the style of the first form, you need to write it like this:

if (a == b) {
  c = true;
} else c = false;

Now it's clear which of the two is more readable, more maintainable, and less likely to introduce bugs if something is changed.  Stick with the second form.


问:
Is having sensitive data in a PHP script secure?
I've heard that PHP is somewhat secure because Apache won't allow the download of raw PHP. Is this reliable, though? For example, if you wanted to password protect something, but didn't want to create a database, would something like $pass = "123454321"; be safe?

Bottom line, is it safe to assume that nobody has access to the actual .php file?

答:
You're correct that Apache will send PHP scripts to the PHP interpreter, if correctly configured, but what you're describing is not secure.

Neither the language nor the webserver is relevant here, your configuration values should not be in a publicly accessible directory to begin with, there's absolutely no reason at all to have your configuration file under DocumentRoot.

Lastly, if anyone other than you have access to the server, you can never assume that nobody has access to your files.


答:
"more maintainable" could be very subjective.

I usually prefer readability and intent over code reduction. I think you save 8 typed characters by using the reduced form.

Taking the language and culture around the language is a characteristic of 'readability' in my opinion.

There are times when performance may be cause for reducing the code to optimize the resulting byte code, but that should be done carefully after some profiling.

Title: Which is more maintainable -- boolean assignment via if/else or boolean expression?

Body:
Which would be considered more maintainable?

```<code>if (a == b) c = true; else c = false;
</code>```

or

```<code> c = (a == b);
</code>```

I've tried looking in Code Complete, but can't find an answer.

I think the first is more readable (you can literally read it out loud), which I also think makes it more maintainable. The second one certainly makes more sense and reduces code, but I'm not sure it's as maintainable for C# developers (I'd expect to see this idiom more in, for example, Python).


答:
Code Complete has a good chapter (8) on this.

The first question I'd ask is where is the input coming from. Is it coming from within the application (probably considered "sterile"), or is it coming from somewhere else (e.g. user input)?

I think you need to know the answer to that question in order to determine whether the inputs should be checked and how to handle what happens when they're invalid.

Title: Try/Catch or test parameters

Body:
Possible Duplicate:

  Arguments for or against using Try/Catch as logical operators

  Efficient try / catch block usage?

I was recently on a job interview and I was given a task to write simple method in C# to calculate when the trains meet.  The code was simple mathematical equation.
What I did was that I checked all the parameters on the beginning of the method to make sure, that the code will not fail.

My question is: Is it better to check the parameters, or use try/catch?

Here are my thoughts:

Try/catch is shorter

Try/catch will work always even if you forget about some condition

Catch is slow in .NET

Testing parameters is probably cleaner code (Exceptions should be exceptional)

Testing parameters gives you more control over return values

I would prefer testing parameters in methods longer than +/- 10 lines, but what do you think about using try/catch in simple methods just like this – i.e. return (a*b)/(c+d);

There are many similar questions on stackexchnage, but I am interested in this particular scenario.


答:
Down-voters, please elaborate what is wrong with my revised answer.

Yes, c = (a == b); can be hard to read (worse yet, StyleCop complains about the unnecessary parenthesis), but I still like the simplicity of a == b. Therefore, here is what I like to use when both a and b are the same:

```<code>private static bool NoPeriod
{
    get
    {
        return this.MyWaveLength == this.HerWaveLength;
    }
}
</code>```

And then you can do: this.c = this.NoPeriod instead of:

```<code>this.c = this.MyWavelength == this.HerWaveLength;
</code>```

Body:
Down-voters, please elaborate what is wrong with my revised answer.

Yes, c = (a == b); can be hard to read (worse yet, StyleCop complains about the unnecessary parenthesis), but I still like the simplicity of a == b. Therefore, here is what I like to use when both a and b are the same:

private static bool NoPeriod
{
    get
    {
        return this.MyWaveLength == this.HerWaveLength;
    }
}

And then you can do: this.c = this.NoPeriod instead of:

this.c = this.MyWavelength == this.HerWaveLength;


答:
I'd disagree that your first form is more readable - it's certainly not idiomatic C# to have two statements on a single line, and it's not recommended to have an if statement without using braces.

Secondly, I don't see how the second form is less maintainable - there's nothing to maintain. It's a simple statement of the relationship between a and b and it couldn't be expressed any more simply.

Another reason to prefer the second form is that you can declare c and assign it in a single statement i.e.

```<code>bool c = (a == b);
</code>```

Modifying variables can easily lead to errors, so I would avoid it. Using an if statement requires the variable to be declared before the conditional and then modified.

Body:
I'd disagree that your first form is more readable - it's certainly not idiomatic C# to have two statements on a single line, and it's not recommended to have an if statement without using braces.

Secondly, I don't see how the second form is less maintainable - there's nothing to maintain. It's a simple statement of the relationship between a and b and it couldn't be expressed any more simply.

Another reason to prefer the second form is that you can declare c and assign it in a single statement i.e.

bool c = (a == b);

Modifying variables can easily lead to errors, so I would avoid it. Using an if statement requires the variable to be declared before the conditional and then modified.


答:
The second option is better.

There's definite reason to be wary of clever programming shortcuts that hurt maintainability by obscuring the intent of the code. So, I don't blame you for asking the question.

However, I don't consider c = (a == b); to be an example of a clever trick. It's a straightforward representation of a simple concept. As straight-forward as you can get.

A proper, "maintainable" formatting of your first example (without the missing braces and one-line construct, which I do consider a clever shortcut) would yield this code:

```<code>if (a == b)
{
    c = true;
}
else
{
    c = false;
}
</code>```

In my experience, writing simple boolean logic in such a verbose, error-prone way is a sign of "iffy" code. It would make me wonder how more complex logic is being handled in this code-base.

Body:
The second option is better.

There's definite reason to be wary of clever programming shortcuts that hurt maintainability by obscuring the intent of the code. So, I don't blame you for asking the question.

However, I don't consider c = (a == b); to be an example of a clever trick. It's a straightforward representation of a simple concept. As straight-forward as you can get.

A proper, "maintainable" formatting of your first example (without the missing braces and one-line construct, which I do consider a clever shortcut) would yield this code:

if (a == b)
{
    c = true;
}
else
{
    c = false;
}

In my experience, writing simple boolean logic in such a verbose, error-prone way is a sign of "iffy" code. It would make me wonder how more complex logic is being handled in this code-base.


答:
Maintenance

Then profiling if necessary and optimize for speed.  Rarely have I ever had a need for storage - at least not in the past 10 years.  Prior to that I did.

Title: What do you optimize for?

Body:
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.


问:
Why does this static field always get initialized over-eagerly?
I am looking at this excellent article from Jon Skeet.

While executing the demo code, Jon Skeet says that we can expect three different kinds of behaviours. To quote that article:

The runtime could decide to run the type initializer on loading the
  assembly to start with... Or perhaps it will run it when the static
  method is first run... Or even wait until the field is first
  accessed...

When I try this out (on framework 4), I always get the first result. That is, the static method is initialized before the assembly is loaded. I have tried running this multiple times and get the same result. (I tried both the debug and release versions)

Why is this so? Am I missing something?

答: When he says that "The results of running the above are quite varied.", he means that their potential results are varied.  The act of running the exact same combination of compiler and runtime will almost certainly produce the same results every time.  But other combinations (e.g., the Mono Project's C# compiler and runtime) would be perfectly within their rights to do one of the other things.


答:
If you don't make any mistakes, your PHP sources cannot be read from the outside: as long as apache is configured to handle .php files through mod_php, they will always be executed, never served raw.

However, mistakes are easy to make, and are frequently found in production code. Typical mistakes include:

Path traversal vulnerabilities. The typical pattern is that you construct a filename based on some user input (e.g. a $_GET parameter), and then serve this file through, say, readfile. For example, if you have readfile("/home/me/pages/{$_GET['pageid']}.html"), an attacker can easily plant something like "../../../../../../../../../../../etc/shadow".

PHP files with nonstandard extensions. Apache uses the extension to determine a file's MIME type, and then decides how to handle it based on that. config.php will be interpreted, but config.php.inc will not; since .inc is not a known extensions in most setups, Apache defaults to plain text, which means the source code can be requested over the net.

Code upload. Typically, such a vulnerability arises when you have file uploads that are handled improperly, e.g. allowing arbitrary directories in the uploaded filename, or uploading to a location under the document root. When an attacker can plant .php files in a location where they get executed, it is possible to run arbitrary PHP code on your server, including code that reads other scripts and extracts passwords.

Remote code execution vulnerabilities. Similar to code upload; if you have any eval, include, system, exec or similar calls in your code, and their arguments are partially user-supplied, you may be in trouble - improperly sanitized inputs to any of these constructs can allow attackers to run arbitrary PHP code or shell commands.

Displaying errors in the page output. Many errors and exception contain sensitive data, at least portions of the source code, but sometimes (e.g. PDOExceptions) even usernames and passwords.

Apache configuration mistakes. Apache is a powerful thing, full of obscure features, and some of them have security implications.

In addition to avoiding these pitfalls, you should put only those files under the document root that are intended to be called directly; any includes, data files, configuration files, libraries, etc., go into directories outside the document root.

Title: Is having sensitive data in a PHP script secure?

Body:
I've heard that PHP is somewhat secure because Apache won't allow the download of raw PHP. Is this reliable, though? For example, if you wanted to password protect something, but didn't want to create a database, would something like $pass = "123454321"; be safe?

Bottom line, is it safe to assume that nobody has access to the actual .php file?


问:
algorithm for project euler problem no 18
Problem number 18 from Project Euler's site is as follows:

```<code>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
</code>```

The formulation of this problems does not make clear if

the "Traversor" is greedy, meaning that he always choosed the child with be higher value

the maximum of every single walkthrough is asked

The NOTE says, that it is possible to solve this problem by trying every route. This means to me, that is is also possible without!

This leads to my actual question: Assumed that not the greedy one is the max, is there any algorithm that finds the max walkthrough value without trying every route and that doesn't act like the greedy algorithm?

I implemented an algorithm in Java, putting the values first in a node structure, then applying the greedy algorithm. The result, however, is cosidered as wrong by Project Euler.

```<code>sum = 0;

void findWay(Node node){
    sum += node.value;
    if(node.nodeLeft != null && node.nodeRight != null){
            if(node.nodeLeft.value > node.nodeRight.value){
                findWay(node.nodeLeft);
            }else{
                findWay(node.nodeRight);
            }
        }
}
</code>```

答:
As somebody who has solved the problem I can tell you that the greedy algorithm is NOT what they are looking.

It is looking for the maximum value of all possible routes.

example

```<code>   3
  7 4
 2 4 6
8 5 1 3
</code>```

3+7+4+5 = 19 <- greedy

3+7+2+8 = 20 <- not greedy

So the answer should be 20

Body:
As somebody who has solved the problem I can tell you that the greedy algorithm is NOT what they are looking.

It is looking for the maximum value of all possible routes.

example

   3
  7 4
 2 4 6
8 5 1 3

3+7+4+5 = 19 <- greedy

3+7+2+8 = 20 <- not greedy

So the answer should be 20


答:
Your only hope is downloading the SAMS Teach Yourself C# in 24 Hours and SAMS Teach Yourself PHP in 24 Hours e-books and reading about 1,200 pages in the next 60 or so hours.  You'll have about 3 minutes to skim and understand each page, assuming you don't eat or sleep.

Seriously, this is an impossible task.  You can learn language syntax that fast and even try out some simple examples, but PHP is complicated by the fact that nobody just writes bare PHP anymore, and .NET (typically in C#) is useless without understanding the gigantic library of standard classes.  When I was a development manager, I usually figured a good-to-great Java programmer could pick up C# enough to be useful in about 4 weeks.


答:
Spoiler alert: This answer leads you to a solution, but does not implement it

Using WuHoUnited's example, modified for uniqueness:

```<code>   9
  7 0
 2 4 6
8 5 1 3
</code>```

Ask yourself this: If you found yourself at 2, would you ever take 8 instead of 5, knowing they are the leaf nodes of the tree? Similarly, If you found yourself at 6, would you ever take 3 instead of 1, knowing those are the leaf nodes of the tree?

Certainly not. We can now reduce the tree, knowing what decision we'd take at the penultimate branch (regardless of how we got there):

```<code>   9
  7 0
10 9 9
</code>```

I think you see where this is going.

Title: algorithm for project euler problem no 18

Body:
Problem number 18 from Project Euler's site is as follows:

```<code>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
</code>```

The formulation of this problems does not make clear if

the "Traversor" is greedy, meaning that he always choosed the child with be higher value

the maximum of every single walkthrough is asked

The NOTE says, that it is possible to solve this problem by trying every route. This means to me, that is is also possible without!

This leads to my actual question: Assumed that not the greedy one is the max, is there any algorithm that finds the max walkthrough value without trying every route and that doesn't act like the greedy algorithm?

I implemented an algorithm in Java, putting the values first in a node structure, then applying the greedy algorithm. The result, however, is cosidered as wrong by Project Euler.

```<code>sum = 0;

void findWay(Node node){
    sum += node.value;
    if(node.nodeLeft != null && node.nodeRight != null){
            if(node.nodeLeft.value > node.nodeRight.value){
                findWay(node.nodeLeft);
            }else{
                findWay(node.nodeRight);
            }
        }
}
</code>```

Body:
Spoiler alert: This answer leads you to a solution, but does not implement it

Using WuHoUnited's example, modified for uniqueness:

   9
  7 0
 2 4 6
8 5 1 3

Ask yourself this: If you found yourself at 2, would you ever take 8 instead of 5, knowing they are the leaf nodes of the tree? Similarly, If you found yourself at 6, would you ever take 3 instead of 1, knowing those are the leaf nodes of the tree?

Certainly not. We can now reduce the tree, knowing what decision we'd take at the penultimate branch (regardless of how we got there):

   9
  7 0
10 9 9

I think you see where this is going.


问:
Is there a rule of thumb for what a bing map's zoom setting should be based on how many miles you want to display?
If a map contains pushpins/waypoints that span only a couple of miles, the map should be zoomed way in and show a lot of detail. If the pushpins/waypoints instead cover vast areas, such as hundreds or even thousands of miles, it should be zoomed way out.

That's clear. My question is: is there a general guideline for mapping (no pun intended) Bing Maps zoom levels to a particular number of miles that separate the furthest apart points? e.g., is there some chart that has something like:

Zoom level N shows 2 square miles
Zoom level N shows 5 square miles
etc.?

答: ViewOptions lets you specify the view using the bounds, rather than a center and a zoom.  That's probably the way to go.  Find the westernmost, southernmost, northernmost and easternmost pushpins and use their coordinates to construct a bounding rectangle.  </p>


问:
What are some things to be aware of when getting ready to hand a project off?
I'm current the sole developer/architect of a fairly large web application (ASP.NET MVC stack, roughly 150K+ lines of code) and the end of development is on the horizon. As such, I'm starting to think about what needs to be done for the hand off of the project and I want to make sure I do the right thing for anyone that has to maintain the project in the future.

What are some things to be aware of when getting ready to hand a project off to another developer or team of developers of maintenance?

答:
IMHO, if you could only do one thing before handing off your project (either directly or indirectly), I would recommend that you double and tripple check that it compiles as-is from source control.

No laughing, but I cannot tell you how many times I've gotten "latest" from a source control and it failed to compile, only to find out later that I wasn't "on Fred's old box" because apparently the code "only compiles on Fred's old box". I even had a former employer promptly remove my desktop from my cube, and replace it with "Fred's old box" so I could work on the project I was suppose to.

As an extension of the above recommendation, because sometimes getting latest isn't all that is necessary to compile an application, I recommend that you create a README.txt and place it in the root directory of your application and put that in source control. This README document should contain a list of external dependencies that could not be checked into source control (if any exist), how to setup the database, and any other oddities about the compilation, execution or deployment cycles of the application.

Anything above and beyond the above two suggestions would just be gravy, but IMHO the above two are almost required on any project larger than "Hello World".

EDIT:

On the topic of documentation...

Over the years I've both written and read my fair share of software documentation for the purpose of easing a developer's transition. I'd say that such documents are rarely worth the paper they are printed on. Developers (myself included) rarely think of the important parts of the application while writing such documents, we only tend to think about the most recent fires we've battled. Above and beyond the fact that these documents tend to not cover all the important aspects of the software, they also get outdated VERY quickly. Once the document is out of date a future developer is more than likely going to completely disregard it instead of bringing it back up to match reality (think changing requirements).

Instead of documentation per se, I recommend unit tests. I know it probably sounds old at this point, but let the code do the documenting for you. Broken unit tests are hard to ignore (and easier to spot) than a Word document. Additionally, the English language is horribly imprecise for articulating the finner points of software design. There are simply too many ways to interpret the meaning of even the simplest of English sentences, and this just leads to confusion and/or bugs.


问:
Why is the sudden increase in number of Git submitters on Debian popcon graph in 2010-01?
Almost every article I've read 1 comparing Git and Mercurial it seems like Mercurial has a better command line UX with each command being limited to one idea only (unlike say git checkout).

But at some point Git suddenly became looking super popular and number of Git submitters on Debian popcon graph (see graph image below) literally exploded.

Source: Debian

What happened in 2010-01 that things suddenly changed. Looks like GitHub was founded earlier than that - 2008.

答:
I am surprised no one has mentioned Github as one of the biggest reason for Git to gain popularity. They pushed git mainstream.

Github launched in April 2008 and within 1-2yrs, they gained popularity. And then when you see a sudden explosion of git/git-core usage is primarily due to the 2Million github users and their 3.7million repositories. Github made git easy to use. Bitbucket was there, but github made it effortless. I am sure if github guys picked Hg in place of git, we should have seen a same surge in usage of Hg.

Analogy can be: Canonical:Linux::Github:Git

OwnerDisplayName: Jungle Hunter


问:
How to create Button/Switch-Like Tile where you can step on it and change its value?
If the player steps on a Button-Tile when its true, it becomes false. If the player steps on a Button-Tile when it is false, it becomes true.

The problem is, when the player stands on (intersects) the Button-Tile, it will keep updating the condition. So, from true, it becomes false. Because its false and the player intersects it, it becomes true again. True-false-true-false and so on.

I use ElapsedGameTime to make the updating process slower, and the player can have a chance to change the Button to true or false.

However, it's not the solution I was looking for. Is there any other way to make it keep in False/True condition while the Player is standing on the Button tile?

答: The condition is wrong: do not update the state when the player stands on the tile, update the state when the player enters the tile. This way they can stand on a tile as long as they want with no change.


答: Dijkstra's algorithm for shortest paths (turn all edges negative).</p>


问:
My father is a doctor. He is insisting on writing a database to store non-critical patient information, with no programming background
So, my father is currently in the process of "hacking" together a database using FileMaker Pro, a GUI based databasing tool for his small (4 doctor) practice. The database will be used to help ease the burden on reporting from medical machines, streamlining quite a clumsy process.

He's got no programming background, and seems to be doing everything in his power to not learn things correctly. He's got duplicate data types, no database-enforced relationships (foreign/primary key constraints) and a dozen other issues. He's doing it all by hand via GUI tool using Youtube videos.

My issue is, that whilst I want him to succeed 100%, I don't think it's appropriate for him to be handling these types of decisions. How do I convince him that without some sort of education in these topics, a hacked together solution is a bad idea? He's can be quite stubborn and I think he sees these types of jobs as "childs play"

How should I approach this? Is it even that bad an idea - or am I correct in thinking he should hire a proper DBA/developer to handle this so that it doesn't become a maintenance nightmare?

NB: I am a developer consultant of 4 years and I've seen my share of painful customer implementations.

Update:

So it's a few years later now, and I've had time to reflect on this question. My dad ended up implementing a solution using Google Docs, FileMaker Pro and some email hooks. He set the whole thing up himself, and he says he is getting immense value from it.

If you are an experienced developer, you are perhaps reading that description and cringing. But I learnt a pretty good lesson from the whole thing actually - that people only care about the results, and not the implementation. All my dad cares about is the fact he doesn't need to enter patient information down on paper manually, and can instead quickly fill out a Google docs form. What's great is he's looking to hire a junior dev/ops person to focus solely on automation within his practice.

答:
You should let him try. However, you should make him aware of the fact, that when he reaches an impasse, it's his problem and any developer he decides to hire at that point, will have to start from scratch.

I like to hack together things a lot, like furniture and even plumbing. I enjoy it and I see nothing wrong with it. I just never would even dare to ask a skilled craftsman to jump in for me when I get stuck, simply because I think they'd throw up at the mere sight of my creations.

So let your father do what he likes, but try to let him understand the risks. Just explain to him, that when he at some point hires a trained developer to "just add one little feature", it's like asking experienced craftsmen to "just fix a couple of things" in a house where most the wiring and plumbing has been done with duct-tape, aluminium foil, Plasticine and good faith.


问:
How do you keep track of a requirements document on an agile team?
I understand that User Stories dominate the agile world, but how are these artifacts stored, so that new developers who join the team can come up to speed with the requirements?

What if the User Story changes later, how is it updated and kept as an artifact? I've seen many teams just open a new ticket/feature request/bug report instead of keeping track of the original story.

答:
What if the User Story changes later, how is it updated and kept as an artifact? I've seen many teams just open a new ticket/feature request/bug report instead of keeping track of the original story.

Managing any documentation can be difficult regardless of whether you are using agile stories or a big up front document, and in order to reduce the burden, the documentation should be minimal and updated incrementally to match the efforts being made on the tests and implementation. As the OP has alluded to however, simply updating the documentation risks losing the history of how the software has evolved over time.

Is this really important?  Sometimes it can be. For the most part you simply wish to view the stories/UML/whatever along with the tests and the code itself at the present time, however when questions are raised as to why a feature has been implemented in a particular way, it can often be useful to look at the history in order to see how the feature has changed over time, to paint a clearer picture as to why implementation option X was chosen instead of option Y.

There are a couple of ways that you can keep track of such artifacts.  One of the better options can be to keep your stories in a tool that allows you to have your story text versioned in a similar way to the versioning of your source code. Wiki's tend to be very good at this, and so too are some of the project/issue management tools, such as Trac or Redmine which keep histories of changes to the issues themselves, as well as the wiki pages within these systems. This can be taken a little further though, to improve the ability to trace changes from issue to feature, by ensuring that new stories or issues are linked in some way to older related issues and stories.  This could be as simple as adding an older issue/story id to the text of a newer issue/story, but can be improved greatly by including any issue or story id's to the check in comment whenever you commit a change to your version control system.  This method is of the greatest value however if your commits are frequent and limited to a single story or issue.

The biggest difficulty of course is that this type of approach requires careful attention and a commitment by every team member to be consistent, and to keep their commits small and frequent, and for those managing the stories and/or issue/project tracking systems to keep on top of the artifacts which provide links between the present state of your implementation, and all of the changes which have previously occurred.


问:
Why are interfaces useful?
I have been studying and coding in C# for some time now. But still, I can't figure the usefulness of Interfaces. They bring too little to the table. Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them. They are there just to make sure that the said functions(in the interface) are implemented in the inheriting class.

C# is a great language, but sometimes it gives you the feeling that first Microsoft creates the problem (not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

That's my understanding which is based on limited coding experience. What's your take on interfaces? How often you make uses of them and what makes you do so?

答:
I can say I relate to that. When I first started learning about OO and C# I too didn't get Interfaces. That's ok. We just need to come accross something that will make you appreciate the conveniences of interfaces.

Let me try two approaches. And pardon me for the generalizations.

Try 1

Say you're a native English speaker. You go to another country where English is not the native language. You need help. You need someone who can help you.

Do you ask: "Hey, were you born in the United States?"
This is inheritance.

Or do you ask: "Hey, do you speak English"?
This is interface.

If you care about what it does, you can rely in interfaces.
If you care about what is is, you rely on inheritance.

It's ok to rely on inheritance. If you need someone who speaks English, likes tea and likes soccer, you're better served asking for a Brit. :)

Try 2

Ok, let's try another example.

You use different databases and you need to implement abstract classes to work with them. You'll pass your class to some class from the DB vendor.

```<code>public abstract class SuperDatabaseHelper
{
   void Connect (string User, string Password)
}

public abstract class HiperDatabaseHelper
{
   void Connect (string Password, string User)
}
</code>```

Multiple inheritance, you say? Try that with the above case. You can't. The compiler won't know which Connect method you're trying to call.

```<code>interface ISuperDatabaseHelper
{
  void Connect (string User, string Password)
}

interface IHiperDatabaseHelper
{
   void Connect (string Password, string User)
}
</code>```

Now, there's something we can work with - at least in C# - where we can implement interfaces explicitly.

```<code>public class MyDatabaseHelper : ISuperDatabaseHelper, IHiperDatabaseHelper
{
   IHiperDataBaseHelper.Connect(string Password, string User)
   {
      //
   }

   ISuperDataBaseHelper.Connect(string User, string Password)
   {
      //
   }

}
</code>```

Conclusion

The examples are not the best, but I think it gets the point accross.

You'll only "get" interfaces when you feel the need of them. Until them you'll think they're not for you.

Title: Why are interfaces useful?

Body:
I can say I relate to that. When I first started learning about OO and C# I too didn't get Interfaces. That's ok. We just need to come accross something that will make you appreciate the conveniences of interfaces.

Let me try two approaches. And pardon me for the generalizations.

Try 1

Say you're a native English speaker. You go to another country where English is not the native language. You need help. You need someone who can help you.

Do you ask: "Hey, were you born in the United States?"
This is inheritance.

Or do you ask: "Hey, do you speak English"?
This is interface.

If you care about what it does, you can rely in interfaces.
If you care about what is is, you rely on inheritance.

It's ok to rely on inheritance. If you need someone who speaks English, likes tea and likes soccer, you're better served asking for a Brit. :)

Try 2

Ok, let's try another example.

You use different databases and you need to implement abstract classes to work with them. You'll pass your class to some class from the DB vendor.

public abstract class SuperDatabaseHelper
{
   void Connect (string User, string Password)
}

public abstract class HiperDatabaseHelper
{
   void Connect (string Password, string User)
}

Multiple inheritance, you say? Try that with the above case. You can't. The compiler won't know which Connect method you're trying to call.

interface ISuperDatabaseHelper
{
  void Connect (string User, string Password)
}

interface IHiperDatabaseHelper
{
   void Connect (string Password, string User)
}

Now, there's something we can work with - at least in C# - where we can implement interfaces explicitly.

public class MyDatabaseHelper : ISuperDatabaseHelper, IHiperDatabaseHelper
{
   IHiperDataBaseHelper.Connect(string Password, string User)
   {
      //
   }

   ISuperDataBaseHelper.Connect(string User, string Password)
   {
      //
   }

}

Conclusion

The examples are not the best, but I think it gets the point accross.

You'll only "get" interfaces when you feel the need of them. Until them you'll think they're not for you.


问:
PHP file_put_contents File Locking
The Senario:

You have a file with a string (average sentence worth) on each line. For arguments sake lets say this file is 1Mb in size (thousands of lines).

You have a script that reads the file, changes some of the strings within the document (not just appending but also removing and modifying some lines) and then overwrites all the data with the new data.

The Questions:

Does 'the server' PHP, OS or httpd etc. already have systems in place to stop issues like this (reading/writing half way through a write)?

If it does, please explain how it works and give examples or links to relevant documentation.

If not, are there things I can enable or set-up, such as locking a file until a write is completed and making all other reads and/or writes fail until the previous script has finished writing?

My Assumptions and Other Information:

The server in question is running PHP and Apache or Lighttpd.

If the script is called by one user and is halfway through writing to the file and another user reads the file at that exact moment. The user who reads it will not get the full document, as it hasn't been written yet. (If this assumption is wrong please correct me)

I'm only concerned with PHP writing and reading to a text file, and in particular, the functions "fopen"/"fwrite" and mainly "file_put_contents". I have looked at the "file_put_contents" documentation but have not found the level of detail or a good explanation of what the "LOCK_EX" flag is or does.

The scenario is an example of a worst case scenario where I would assume these issues are more likely to occur, due to the large size of the file and the way the data is edited. I want to learn more about these issues and don't want or need answers or comments such as "use mysql" or "why are you doing that" because I'm not doing that, I just want to learn about file read/writing with PHP and don't seem to be looking in the right places/documentation and yes I understand PHP is not the perfect language for working with files in this way.

答:
1) No
3) No

There are several issues with the original suggested approach:

Firstly, some UNIX-like systems such as Linux may not have locking support implemented. The OS does not lock files by default. I have seen the syscalls being NOP (no-operation), but that's a few years back, so you need to verify whether a lock set by your instance of the application is respected by another instance. (i.e. 2 concurrent visitors). If the locking is still unimplemented [very likely it is], the OS lets you overwrite that file.

Reading large files line-by-line is not feasible for performance reasons. I suggest using file_get_contents() to load the whole file into memory and then explode() it to get the lines. Alternatively, use fread() to read the file in blocks. The aim is to minimize the number of read calls.

In regards to file locking:

LOCK_EX means an exclusive lock (typically for writing). Only one process may hold an exclusive lock for a given file at a given time.
LOCK_SH is a shared lock (typically for reading), More than one process may hold a shared lock for a given file at a given time.
LOCK_UN unlocks the file. Unlocking is done automatically in case you use file_get_contents()
http://en.wikipedia.org/wiki/File_locking#In_Unix-like_systems

Elegant solution

PHP supports data stream filters which are intended for processing data in files or from other inputs. You may want to create one such a filter properly using the standard API.
http://php.net/manual/en/function.stream-filter-register.php
http://php.net/manual/en/filters.php

Alternative solution (in 3 steps):

Create a queue. Instead of processing one filename, use the database or other mechanism to store unique filenames somewhere in pending/ and processed in /processed. This way nothing gets overwritten. The database will be also useful for storing additional information, such as metadata, reliable timestamps, processing results, and other.

For files up to a few MB, read the whole file into memory and then process it (file_get_contents() + explode() + foreach())

For larger files read the file in blocks (i.e. 1024 Bytes) and process + write in real-time each block as reading (careful about the last line which doesn't end with \n. It needs to be processed in the next batch)

Title: PHP file_put_contents File Locking


答:
It has been said before but I think the gist of it is this:

requirements may cover many facets and typically result in more than one story.

a story organizes a team's work in chunks that are small enough to fit within the time boundaries of a sprint.

often there are many details that need to be defined for some particular function to work correctly. This is when it starts to become useful to keep these definitions in a seperate requirements document - for clarity, common understanding and later reference.

Consider the legendary online pet shop example:

The story may say "As a user, I want to see the VAT printed on my receipt, …". Now, calculation of VAT (value added tax) can be a complicated matter and likely needs more work than this story suggests.

There may be an additional story that asks for the VAT calculation to be done (say multiply the total sales amount by the VAT rate), but it is likely not to include all variations of that calculation.

At first, the team would focus on providing the basic module, say taking a list of goods and their sales price, and returning the VAT amount. That's something that a team can accomplish within a sprint's amount of time.

It is likely there will be many more stories to cover all the possible cases for VAT calculation.

To keep the many different VAT calculation rules visible across and beyond single sprints, it makes sense to keep a separate requirements document that lists all the various ways to calculate VAT. This document may evolve over time. In fact, adding a new section to it could be part of a story's task to complete.

Title: How do you keep track of a requirements document on an agile team?

Body:
I understand that User Stories dominate the agile world, but how are these artifacts stored, so that new developers who join the team can come up to speed with the requirements?

What if the User Story changes later, how is it updated and kept as an artifact? I've seen many teams just open a new ticket/feature request/bug report instead of keeping track of the original story.


问:
Single statement non-braced ifs and code merges
I've seen code merges being used as an argument for bracing even single statement ifs. For example:

```<code>if (condition) {
    do something;
}
</code>```

Unfortunately I can't think of a change that would break a non-braced version during an automatic code merge. Could someone post an example?

答:
The only thing that immediately comes to my mind, is the typical problem of a developer believing that their statement is still part of the condition when it is outside the condition therefore their conditional statement gets run. I have seen this over and over.

Example

```<code>if (condition)
    do something in condition;
    do something else in condition; // Outside the condition always gets run
</code>```

I know it is not directly related to your question but if you are doing automatic code merges this is the type of thing that might sneak in more often than not. doubly so if you are not properly testing for breaks before the merge.

For this reason I feel it is good policy to be more explicit with your conditional bracing and more so if you are doing automatic merges. I also hope that with each merge there are a suite of test being run to help ensure that the merges were successful and your application still works as expected.

Body:
The only thing that immediately comes to my mind, is the typical problem of a developer believing that their statement is still part of the condition when it is outside the condition therefore their conditional statement gets run. I have seen this over and over.

Example

if (condition)
    do something in condition;
    do something else in condition; // Outside the condition always gets run

I know it is not directly related to your question but if you are doing automatic code merges this is the type of thing that might sneak in more often than not. doubly so if you are not properly testing for breaks before the merge.

For this reason I feel it is good policy to be more explicit with your conditional bracing and more so if you are doing automatic merges. I also hope that with each merge there are a suite of test being run to help ensure that the merges were successful and your application still works as expected.


答:
You're right, and it won't break in the way described.  Unless you're using a really, really bad merging tool, the scenario you describe shouldn't happen.  Merge tools don't magically insert code that doesn't exist in either the new or old version of the file.

The real issue is that programmers are much more apt to extend the logic within a conditional and forget to add the braces.  It's not a merge tool issue, it's a people issue.  And I count myself in that camp having made that mistake before.

Whether all single line conditionals should be within braces is a sub-theme within the holy wars of code style.  What is right can only be decided by your team for your team.

Your team needs to make a decision on what they want and put it in your coding style guidelines.

Title: Single statement non-braced ifs and code merges

Body:
I've seen code merges being used as an argument for bracing even single statement ifs. For example:

```<code>if (condition) {
    do something;
}
</code>```

Unfortunately I can't think of a change that would break a non-braced version during an automatic code merge. Could someone post an example?


问:
Is there a quick and practical (hands on) way to learn another programming language?
Due to rather strange circumstances, I only have until Monday to learn (at least) the basics of PHP and .NET programming. I'm already fairly competent (though there is a lot of room for improvement) in C++ so I feel I have some of the concepts nailed already, but I need to get into the two languages in a bit more depth in a very short time frame.

Unfortunately I won't have time to get any books so will need to exclusively use online resources, I'm more of a 'do-er' so any way to test my skills in a practical way would be a huge bonus :-)

答:
It's hard to answer without knowing what the basics are.

In more of a C# guy, so this is oriented to C#, ok?

Not to rain on your parade, but there's a lot of stuff to know.

Are you talking about only the language? Or are talking about how to code agaisnt a DB? How about threading? Or the differente UI approaches - WPF vs WinForm?

Assuming you also asked about PHP, I assume C# as a part of a web app. In this case, is WebForms or MVC? If MVC, which one?

Anyway:

C# Fundamentals - Part 1

C# Fundamentals - Part 2

There's more on PluralSight and they have a free trial.

There's also Tekpub with some free content (ASP.Net and MVC if I'm not mistaken). And also LearnVisualStudio.Net - but LVS.Net will probably too basic for you.

For C#, I suggest you at least knowing the syntax and what the VS snippets do.

If I were you, I'try focus on how much you've learned on the given timeframe instead on the actual knowledge.


答:
To good news is that many languages share the same conceptual background. This is particularily true if you look at procedural or object oriented languages - luckily, PHP and many of the .NET languages (C#, VBA) are examples of these groups. However, you will want to distinguish language (e.g. C#) and platform (e.g. .NET) - those are not the same. The platform is a collection of libraries (functions) that can typically be used from many languages. Knowing a platform at heart generally takes more time than to do the same for a language.

Having said this, and considering your original question, let me propose the following quick and practical approach to learning a new programming language is this:

Learn/read about the static structures of the language (e.g. data types, functions, procedures, classes, interfaces etc.).

Look at the control constructs (if/then, case/switch, while/until etc.)

Familiarize yourself with the typical style of how the language is expressed (by browsing through tutorials or actual code).

Try to map each of the constructs to the language(s) you know already. This will give you a pretty good grasp on where you should focus, e.g. concepts that are particular to the new language you are trying to learn.

Most important, however, is the next step:

Try to solve a problem in the new language. This can be any problem of your choice that you know the solution to from a conceptual point of view - e.g. implement an algorithm, build a web application, write a web service etc. The imporant part here is to learn to actually use the language and its associated tools and run-time environments.

Keep in mind that all of this merely will get you started, and does not replace actual experience. It is through experience that you will learn how to best make use of a programming language's feature, which of course takes more time...

Body:
Due to rather strange circumstances, I only have until Monday to learn (at least) the basics of PHP and .NET programming. I'm already fairly competent (though there is a lot of room for improvement) in C++ so I feel I have some of the concepts nailed already, but I need to get into the two languages in a bit more depth in a very short time frame.

Unfortunately I won't have time to get any books so will need to exclusively use online resources, I'm more of a 'do-er' so any way to test my skills in a practical way would be a huge bonus :-)


问:
What is the difference between debugging and testing?
Introduction To Software Testing (Ammann & Offutt) mentions on p.32 a 5-level testing maturity model:

Level 0 There’s no difference between testing and debugging.

Level 1 The purpose of testing is to show that the software works.

Level 2 The purpose of testing is to show that the software doesn’t work.

Level 3 The purpose of testing is not to prove anything specific, but to reduce
the risk of using the software.

Level 4 Testing is a mental discipline that helps all IT professionals develop
higher quality software.

Although they don't go into much further detail. What are the differences between debugging and testing?

答:
Others has mentioned what are differences between testing and debugging.

I would like to stress a common part. When a tester finds a defect, it must be isolated. Debugging is one of the techniques to isolate the issue and find a root causes by analyzing the application state and its code at runtime. In fact, debugging is defined by Oxford Dictionaries as "the process of identifying and removing errors from computer hardware or software."

Who will isolate (or debug in particular) a defect, whether it will be a tester or a developer, is a secondary question.


答:
I think the condition they're talking about is this

Change 1 (add, line 20-21):

```<code>if (condition)
    doSomeStuff();
</code>```

Change 2 (add, line 20-21):

```<code>if (condition)
    doOtherStuff();
</code>```

I would bet that some old auto-merge tool somewhere would try to be clever and say "well, you've both added the same line twice at 20, so I'll add it once; and you've added two different lines at 21, so I'll add them both." Leading to

```<code>if (condition)
    doSomeStuff();
    doOtherStuff();
</code>```

These historic arguments tend to hang around long after every merge tool on the planet has been fixed to work differently.

Any auto-merge I've ever seen would refuse to merge two adds in the same place, meaning you have to use a manual-merge tool. At worst, it might add one before the other, which is still fine. But a decent merge tool will allow you to edit this in place and end up with

```<code>if (condition) {
    doSomeStuff();
    doOtherStuff();
}
</code>```

Body:
I think the condition they're talking about is this

Change 1 (add, line 20-21):

if (condition)
    doSomeStuff();

Change 2 (add, line 20-21):

if (condition)
    doOtherStuff();

I would bet that some old auto-merge tool somewhere would try to be clever and say "well, you've both added the same line twice at 20, so I'll add it once; and you've added two different lines at 21, so I'll add them both." Leading to

if (condition)
    doSomeStuff();
    doOtherStuff();

These historic arguments tend to hang around long after every merge tool on the planet has been fixed to work differently.

Any auto-merge I've ever seen would refuse to merge two adds in the same place, meaning you have to use a manual-merge tool. At worst, it might add one before the other, which is still fine. But a decent merge tool will allow you to edit this in place and end up with

if (condition) {
    doSomeStuff();
    doOtherStuff();
}


答:
That's is so easy to break in a way that you will not spot when it does break.

```<code> if (condition)
     doSomeStuff(A);

 // Code
</code>```

Based on a real change I saw a new hire do:

```<code>-    void doSomeStuff(int A)
-    {
-        Action1(A);
-        Action2(A);
-        Action3(A);
-    }
+    // I modified this function to a macro to make sure it inlines and
+    // thus we get s speed increase due to decreased functions calls.
+    #define doSomeStuff(A)        Action1(A);       \
+                                  Action2(A);       \
+                                  Action3(A);
</code>```

Yes it is a stupid situation that will not do what the comments say. But people make all sorts of assumptions and will change code based on these assumptions. And quite easily break the code.

And you will never see at the usage points it is broken until it is too late.

Thus I habitually force myself to always use braces.

Body:
That's is so easy to break in a way that you will not spot when it does break.

 if (condition)
     doSomeStuff(A);

 // Code

Based on a real change I saw a new hire do:

-    void doSomeStuff(int A)
-    {
-        Action1(A);
-        Action2(A);
-        Action3(A);
-    }
+    // I modified this function to a macro to make sure it inlines and
+    // thus we get s speed increase due to decreased functions calls.
+    #define doSomeStuff(A)        Action1(A);       \
+                                  Action2(A);       \
+                                  Action3(A);

Yes it is a stupid situation that will not do what the comments say. But people make all sorts of assumptions and will change code based on these assumptions. And quite easily break the code.

And you will never see at the usage points it is broken until it is too late.

Thus I habitually force myself to always use braces.


问:
Class Design and Structure Online Web Store
I hope I have asked this in the right forum.

Basically, we're designing an Online Store and I am designing the class structure for ordering a product and want some clarification on what I have so far:

So a customer comes, selects their product, chooses the quantity and selects 'Purchase' (I am using the Facade Pattern - So subsystems execute when this action is performed). My class structure:

```<code>   < Order >

       < Product >

          <Customer >
</code>```

There is no inheritance, more Association < Order > has < Product >, < Customer > has < Order > .

Does this structure look ok? I've noticed that I don't handle the "Quantity" separately, I was just going to add this into the "Product" class, but, do you think it should be a class of it's own?

Hope someone can help.

答: Your company has products it sells to customers. It does this through line-item records on invoices which associate a product and a quantity to the invoice. A typical schema might look something like this:


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.

— Rick Cook

LastEditorDisplayName: Roger Pate


问:
How to check if 4 points form a square?
Assume I have 4 points (they are 2-dimension), which are different from each other, and I want to know whether they form a square. How to do it? (let the process be as simple as possible.)</p>

答:
I think you can do this with simple addition and subtraction and finding min/max.  Terms (matches other people's diagram):

Point with highest y value => A

highest x => B

lowest y => C

lowest x => D

If 4 points share only 2 x values and 2 y values you have a level square.

Otherwise, you have a square if your points satisfy the following:

A.x + C.x = B.x + D.x

A.y + C.y = B.y + D.y

A.y - C.y = B.x - D.x

Explanation: The line segments A-C and B-D should meet at their midpoints.  Thus (A.x + C.x) / 2 is the midpoint of A-C and (B.x + D.x) / 2 is the midpoint of B-D.  Multiply each side of this equation by 2 to get my first equation.  The second equation is the same thing for Y-values.  Diamond-shapes (rhomboids) will satisfy these properties, so you need to check that you have equal sides - that the width is the same as the height.  That's the third equation.

Title: How to check if 4 points form a square?


问:
How to keep background requests in sequence
I'm faced with implementing interfaces for some rather archaic systems, for handling online deposits to stored value accounts (think campus card accounts for students).

Here's my dilemma: stage 1 of the process involves passing the user off to a thrid-party site for the credit card transaction, like old-school PayPal. Step two involves using a proprietary protocol for communicating with a legacy system for conducting the actual deposit.

Step two requires that each transaction have a unique sequence number, and that the requests' seqnums are in order. Since we're logging each transaction in Postgres, my first thought was to take a number from a sequence in the DB, guaranteeing uniqueness. But since we're dealing with web requests that might come in near-simultaneously, and since latency with the return from the off-ste payment processor is beyond our control, there's always the chance for a race condition in the order of requests passed back to the proprietary system, and if the seqnums are out of order, the request fails silently (brilliant, right?).

I thought about enqueuing the requests in Redis and using Resque workers to process them (single worker, single process, so they are processed in order), but we need to be able to give the user feedback as to whether the transaction was processed successfully, so this seems less feasible to me.

I've tried to make this application handle concurrency well (as much as possible for a Ruby on Rails app), but now we're in a situation where we have to interact with a system that is designed to be single process, single threaded, and sequential. If it at least gave an "out of order" error, I could just increment (or take the next value off the sequence), but it's designed to fail silently in the event of ANY error. We are handling timeouts in a way that blocks on I/O, but since the application uses multiple workers (Unicorn), that's no guarantee.

Any ideas/suggestions would be appreciated.

答:
You aren't limited to one terminal. You can set up additional terminals and have your app block each one until the transaction is complete. The additional terminals don't use up additional resources in the system you are referring to. You could easily have 100 available to your app and iterate through them with each transaction.

Each terminal maintains its own sequence numbers. This is how we handle ours and it works fine.

Also, IIRC, you can process the transactions as "offline" and send sequence numbers out of order. Though you would really want to avoid running everything as an offline transaction.


问:
How to design a scalable notification system?
I need to write a notification system manager.

Here is my requirements:

I need to be able to send a Notification on different platforms, which may be totally different (for exemple, I need to be able to send either an SMS or an E-mail).

Sometimes the notification may be the same for all recipients for a given platform, but sometimes it may be a notification per recipients (or several) per platform.

Each notification can contain platform specific payload (for exemple an MMS can contains a sound or an image).

The system need to be scalable, I need to be able to send a very large amount of notification without crashing either the application or the server.

It is a two step process, first a customer may type a message and choose a platform to send to, and the notification(s) should be created to be processed either real-time either later.

Then the system needs to send the notification to the platform provider.

For now, I end up with some though but I don't know how scalable it will be or if it is a good design.

I've though of the following objects (in a pseudo language):

a generic Notification object:

```<code>class Notification {
    String                 $message;
    Payload                $payload;
    Collection<Recipient>  $recipients;
}
</code>```

The problem with the following objects is what if I've 1.000.000 recipients ? Even if the Recipient object is very small, it'll take too much memory.

I could also create one Notification per recipient, but some platform providers requires me to send it in batch, meaning I need to define one Notification with several Recipients.

Each created notification could be stored in a persistent storage like a DB or Redis.

Would it be a good it to aggregate this later to make sure it is scalable?

On the second step, I need to process this notification.

But how could I distinguish the notification to the right platform provider?

Should I use an object like MMSNotification extending an abstract Notification? or something like Notification.setType('MMS')?

To allow to process a lot of notification at the same time, I think a messaging queue system like RabbitMQ may be the right tool. Is it?

It would allow me to queue a lot of notification and have several worker to pop notification and process them. But what if I need to batch the recipients as seen above?

Then I imagine a NotificationProcessor object for which I could I add NotificationHandler each NotificationHandler would be in charge to connect the platform provider and perform notification.

I can also use an EventManager to allow pluggable behavior.

Any feedbacks or ideas?

Thanks for giving your time.

Note: I'm used to work in PHP and it is likely the language of my choice.

Edit (according to morphunreal's answer)

How many messages per second are you sending (Define current/initial levels, define a maximum level that the system should handle before being re-designed)

What hardware constraints does the system have (memory, cpu etc available to the system)

How will hardware scale (ie, adding more servers, cloud computing etc)

What languages / systems will be generating notifications?

It is on my own, I'm in charge to create the notification programmatically but constructed from an UI.

Does the generator know the recipients of the message (?) or are they provided by some other means (ie, business rules for certain alert types go to certain recipients)

It should be possible to create a notification for a specific recipients, a group of recipients (for example using a tag system), or for a whole platform.

Are there business rules for adding CC/ BCC / Read receipts

Yes. Note that this is really platform specific and the read or cc are not available on all platforms.

Does the generator know the type of message it's sending (ie, SMS/ email) or is it based off the recipient

It is based on the recipient, however, as the recipient is platform related, and platforms have different way to handle data, the UI is likely to be platform specific to allow to set up images, a sound or something.

Does the generator require confirmation of messages being sent/received/read (async vs synchronous sending)

Well the system should be error prone but we would like to handle the error to define a set of rule, for example, if the server is unreachable, the notification should be requeued for further process, but if the notification is incorrect (or has been defined as is by the platform provider) it should not be requeued but notified.

Are there requirements to store a history of message sources / recipients (how long for?)

Yes, we likely want to make some statistics and report.
* Define Notification End Points

What services are being used to send messages?
Depends, some are classical REST webservice, other are some exotic protocol, it is really up to the provider.

What feedback / confirmation is provided (sync / async)

Depends, some are synchronous and reply with an error while some other need to be pulled afterward to check for errors.

Is it likely to add new end-points [even if so, does it even need to be abstracted]

Yes, actually, our app is growing and we likely want to be able to add new provider, but it is a ratio of something like 1 or 2 per year.

答: Have you considered the flyweight design pattern for your notification objects? I am not too sure about it, since I never implemented the pattern, but I recall it involves sharing some state among the flyweight objects. I also think, the members with more redundancy had bigger impact if shared. So it depends if you send only a few msgs to a lot of people or vice versa.</p>


问:
Asking for a code sample of the company at an interview
Asking a job seeker to show some code is a fairly common practice for a software company. However, would it be acceptable for the candidate to ask the interviewer to show him a small piece of code that he thinks is well written?</p>

答:
Haha, that's a funny question. I wouldn't be offended if somebody asked me for a code sample while they were interviewing, but I probably wouldn't show them any code, either, unless they had asked in advance and I had time to plan carefully.

I definitely understand the intent of asking such a question though. As a job-seeker, I have asked the Joel Test to an interviewer before. They didn't know what it was, but they were happy to answer.

In some places, asking those types of questions might improve your chances while it might hurt your chances elsewhere. The beauty of life is that if it improves your chances, then that's the kind of place you would want to work. If it hurts your chances, then you wouldn't have wanted that job anyway.

I see nothing to lose by asking politely and being able to explain why you want to see it.


问:
What are the advantages of the delegate pattern over the observer pattern?
In the delegate pattern, only one object can directly listen to another object's events. In the observer pattern, any number of objects can listen to a particular object's events. When designing a class that needs to notify other object(s) of events, why would you ever use the delegate pattern over the observer pattern? I see the observer pattern as more flexible. You may only have one observer now, but a future design may require multiple observers.

答: You're looking at things incorrectly. An observer sees that a particular event occurs. It does not impact it, or own it. A delegate handles a particular event, and has ownership of the handler, even if the delegator owns the interface to the event.


答:
There is no delegate pattern per se. I am going to assume you mean Delegation Pattern.

As I understand it, they're the complete reverse of each other and used for different purposes.

Generally, with an Observer Pattern, any number of observer objects will listen to an event on a second object and act on the event. The second object has no knowledge of its listeners. It just calls out to them.

A delegate object is passed to the second object which calls methods directly on the delegate. And therein lies the advantage you're looking for. Rather than sending a single message to multiple listeners, it has complete control over a single object (at a given time). See also Inversion of Control.

Title: What are the advantages of the delegate pattern over the observer pattern?

Body: In the delegate pattern, only one object can directly listen to another object's events. In the observer pattern, any number of objects can listen to a particular object's events. When designing a class that needs to notify other object(s) of events, why would you ever use the delegate pattern over the observer pattern? I see the observer pattern as more flexible. You may only have one observer now, but a future design may require multiple observers.


问:
What math skills are required to learn machine learning?
I am interested in taking this online course on machine learning. As it stands my math is very elementary, and I am basically learning math from scratch on khan academy. Programming-wise I have a decent amount of experience, and a good overall understanding. My question is, what math skills are required for me to be able to effectively understand and utilize machine learning?</p>

答:
That course is specifically designed to be accessible to folks without 'much' math background. Of course 'much' is a relative term. In this case it means 'knowledge of calculus is helpful but not required'. The course does use some results from differential calculus, but you can answer the quizzes and complete the programs without knowing calculus yourself. You just won't understand where some of the formula you have to implement are coming from. </p>

<p>You absolutely will need to be comfortable with basic linear algebra (manipulating vectors and matrices) and working with logarithmic and exponential functions. </p>

Body:
That course is specifically designed to be accessible to folks without 'much' math background. Of course 'much' is a relative term. In this case it means 'knowledge of calculus is helpful but not required'. The course does use some results from differential calculus, but you can answer the quizzes and complete the programs without knowing calculus yourself. You just won't understand where some of the formula you have to implement are coming from.

You absolutely will need to be comfortable with basic linear algebra (manipulating vectors and matrices) and working with logarithmic and exponential functions.


答:
You'll need to know Linear Algebra through Eigenvectors if you want things to be "easy". Also a good statistical background with strong emphasis on Regression, Clustering, and Baye's Theorem. Knowing something about gradients doesn't hurt either. As with any CS, graph theory is helpful as well.

Obviously the course can be taken with only the most basic prerequisites but I'd recommend a thorough understanding of the underlying material beforehand anyway.

Title: What math skills are required to learn machine learning?

Body: I am interested in taking this online course on machine learning. As it stands my math is very elementary, and I am basically learning math from scratch on khan academy. Programming-wise I have a decent amount of experience, and a good overall understanding. My question is, what math skills are required for me to be able to effectively understand and utilize machine learning?</p>


问:
Why is the sudden increase in number of Git submitters on Debian popcon graph in 2010-01?
Almost every article I've read 1 comparing Git and Mercurial it seems like Mercurial has a better command line UX with each command being limited to one idea only (unlike say git checkout).

But at some point Git suddenly became looking super popular and number of Git submitters on Debian popcon graph (see graph image below) literally exploded.

Source: Debian

What happened in 2010-01 that things suddenly changed. Looks like GitHub was founded earlier than that - 2008.

答:
I think that a lot of people are confusing correlation with causation.

The graphs presented all show correlations between measures of gits popularity and events ... and other measures.  However, a correlation is not clear evidence for causation.

Some other answers attempt to draw relationships with other things; e.g. Linus Torsvalds evangelism for DVCS, formation of Github, the rise of social networking.  While there is evidence of correlation (on a time line) is not as strong, that does not exclude causation.  Especially if you accept the "network effect" hypothesis; i.e. that there are multiple causes.

The bottom line, is that the kind of evidence that is available cannot show causation.  We are talking about collective behaviour of hundreds of thousands of people, and people make decisions for different reasons ... or no logical reason at all.  Programmers are no different from anyone else.