问:
Does Changing Author info in git repo affect other contributors?
After contributing some weeks I noticed that the author name in my commits were incorrect. Does changing the git history with author info in the commits create any problems for my fellow contributors?</p>

答:
Yes it does affect other contributers. Changing author name will result in a rewrite of the history. This is because the author name is used while calculating the SHA-1 hash for your commit.
For further you can see this page from github

Regarding  Bart van Ingen Schenau comment how to change the username for furture commits you can do the following(thanks for your comment):

1. Reconfigure the username global:

```<code>git config --global user.name "prefered Username"
</code>```

2. Reconfigure the username per single repository:

```<code>git config user.name "prefered username"
</code>```

This will change the user name for future commit and will keep the username for previous commits. This will also NOT interfere other contributers.

Body:
Yes it does affect other contributers. Changing author name will result in a rewrite of the history. This is because the author name is used while calculating the SHA-1 hash for your commit.
For further you can see this page from github

Regarding  Bart van Ingen Schenau comment how to change the username for furture commits you can do the following(thanks for your comment):

1. Reconfigure the username global:

git config --global user.name "prefered Username"

2. Reconfigure the username per single repository:

git config user.name "prefered username"

This will change the user name for future commit and will keep the username for previous commits. This will also NOT interfere other contributers.


问:
What is the advantage of global functions when writing functional code
I am a Swift developer and am trying to adopt a functional / reactive style in my code. I have been using ReactiveCocoa in all my projects and I have started giving RAC 3.0 a try. One thing I have seen is that in project, there is heavy use of curried functions that have a global scope (i.e. not tied to an instance).

What I am keen to understand is why global functions is a good idea?

Is this something that is unique to curried functions or is it a general functional programming attribute?

答:
my knowledge about functional programming is very limited

In functional programing, calling a function only affect the instance calling it so you let the allow the function to be call from everywhere can't cause bug except in the module calling the function (which is the one having a buggy behaviour).

ContentLicense: CC BY-SA 3.0


问:
Why is the Jacobi method a good candidate algorithm to implement on a GPU?
I understand that GPU's has hundreds of cores that can handle thousands of threads all at once and that with the Jacobi iteration you're essentially using the same numbers over and over again to update a vector. Is this why implementing the Jacobi method on a GPU is a good idea especially if we have a really large system because we have so many redundant calculations?

I guess I don't really see why the Jacobi method is suitable for a GPU

答:
According to Margars, et. al.

The Jacobi iterative algorithms are very good candidates for parallelization …due to being very computationally intensive and inherently divisible into parallel tasks.

A problem that can benefit from parallel programming like that is inherently well suited to implementation on GPUs.


答:
The Jacobi Iterative algorithm calculates every row (hence, every component of the new guess) independently.

And exactly this is the magic trick that is being performed on a GPU. A GPU can make computations highly parallel.

In the Gauss-Seidel Algorithm (which usually converges a lot faster) for example, every row depends on the result of the calculation of the previous row. Thus making it very badly parallelizable and perform terribly on a GPU.

Title: Why is the Jacobi method a good candidate algorithm to implement on a GPU?

Body:
I understand that GPU's has hundreds of cores that can handle thousands of threads all at once and that with the Jacobi iteration you're essentially using the same numbers over and over again to update a vector. Is this why implementing the Jacobi method on a GPU is a good idea especially if we have a really large system because we have so many redundant calculations?

I guess I don't really see why the Jacobi method is suitable for a GPU


问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答:
I think the answer is in multiple parts: skills, certifications and self-promotion/branding.

Skills:
It does not sound like you know which part of the 'web' you are interested in. So pick something not too many people work with yet (because it just came out) and start playing with it using C# stack. For example, razor engine just out in MVC3 beta. Or something around Deep Zoom technology, though that is mostly tied to Silverlight :-( This will give you all the baseline skills, but also all the latest thinking and opportunities.

Self-promotion/branding:
Learning newest (beta) technology is not always easy. Bugs, misunderstood features and other fun will happen along the way. Create a blog (on your own domain) to document those adventures and especially your solutions. Write little tutorial or walk through, maybe little sample projects to download for other newbies. This shows to others that you are working with latest technologies, that you are learning and that - hopefully - you can even teach something to others. If you can, create little demo portfolios to show off your work

Certifications:
Look into things from acm.org or O'Reilly. The memberships there offer access to multiple learning courses and in some cases certifications. I don't know too much about these, but that would be my direction to investigate.

The specific project in a way does not matter, but try not to reinvent the wheel (yet another CMS or Tetris clone). Either pick a simple new thing around your other hobbies to do or try helping an existing open source project. Or just redo an existing .Net demo project from Microsoft (or from a popular .Net book) using the newest technology and HTML5/jQuery approaches. Notice that redoing an existing specifically demo project is different from 'yet another XYZ' as you are constrained by the original demo's feature requirements and therefore can actually be compared to the original implementation as apples to apples. Also gives you a chance to point out where something is now more/less efficient/clear/readable.

With open source projects, you don't have to earn commit rights to be useful, you could just pick a scenario and create sample project demonstrating a particular setup/configuration/etc. Just trying to explain it to others will teach yourself a lot too. And probably discover lots of missing information in that open source project's documentation which will teach you a lot about reading others' code to get answers.

Basically, start thinking beyond just code and more on how you can be a useful member of community even at your level of knowledge and how to make that ongoing contribution to the community more visible. The employers are looking for people who are already useful and if you start these skills early they will pay keep paying back throughout your career.

Cheers mate.

ContentLicense: CC BY-SA 2.5


问:
Can I distribute a GPL executable (not a library) in a closed-source application?
I want to write a closed-source desktop application that uses a piece of GPL software in the background.

I know that I can't link to a GPL library (libgit.a).  But if I embed a GPL application (git.exe) into a closed source application, unzip the GPL app to a temporary location, and then make calls to it using some form of IPC (e.g. command line arguments), is that legal?

non-GPL application calls a GPL application at the command line -> definitely legal

non-GPL application links to a GPL application using function calls -> definitely illegal

non-GPL application bundles, distributes, and calls a GPL application at the command line -> ?

Distributing a GPL application and making silent IPC calls is functionally identical to linking, as far as the end-user is concerned.  Does GPL care about whether I'm linking inside of one process, or using IPC to do the linking?  It seems like closed source applications like GitHub's desktop clients do this, but maybe I'm misunderstanding how they work.

NOTE: This is different than the other GPL questions on this site, because it asks about embedding a GPL application, not linking to a library in the traditional sense.  The answers have been specific to this case and very helpful to me.

NOTE2: Mods found a new duplicate, and this time they are right - it is actually asking the same question as this (although the details are a little more jumbled).  The best answer has been modded into oblivion though.  Key points are copied here:

VMWare Server's example shows that it's okay to include the object code into your distribution and

install it alongside your program

pack it into a compound file within its footage if it's clearly a compound file and can be taken apart with widely available tools (an ISO image)

答:
Short answer: you're not forced to release your software under GPL; you can do it because you're making interoperability with GPL software and this doesn't make your software a derivative work (but if you want to feel more safe then don't distribute Git inside your application package, a dependency is OK).

Dirty workaround to avoid licensing headaches: note that if you make your package independent from Git and you have a separated Source Control Integration Layer then you may want to release under GPL (with source code on GitHub?!) only your Git integration module (not whole software which, in theory, is abstracted and compatible with any SCM).

Note that this question has been asked before: Can I use GPL software in a commercial application? but I completely disagree with given accepted answer and I'll try to explain why. GPL needs to overprotect itself to avoid abuses and misuses but its bounds are set by law and it can't prevaricate them.

Long answer: it's a common debate about GPL, you'll find both point of views (it's derivative work or it's not). I'm not a lawyer (and this issue has been disccused in a court too few times to have a well-known universally accepted answer) but let's try to summarize.

GPL ties you to distribute your source code if you deploy any derivative work based on GPL. First of all check if Git has a GPL linking exception (in that case you can freely use it). Main point is then to define derivative work. What they say about this (quotation from FAQ)?

If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, which must be treated as an extension of both the main program and the plug-ins. This means the plug-ins must be released under the GPL or a GPL-compatible free software license, and that the terms of the GPL must be followed when those plug-ins are distributed.

For US law derivative work is:

“derivative work” is a work based upon one or more pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which a work may be recast, transformed, or adapted.

How you define transformed and adapted from copyright point of view (in US law)?

This previously published material makes the work a derivative work under the copyright law. To be copyrightable, a derivative work must be different enough from the original to be regarded as a “new work” or must contain a substantial amount of new material. Making minor changes or additions of little substance to a preexisting work will not qualify the work as a new version for copyright purposes.

You have to incorporate GPL material in your own application. To use it is not enough to define your work as derivative. If you think about it then this is pretty obvious (and important!) because if you use Git to manage your source code you don't need to release your application under GPL!

Moreover they also says that:

Titles, short phrases, and format, for example, are not copyrightable

Then now you also know that you have to include enough GPL material in your own work. A code snippet copied & pasted in your own code doesn't make it tied to GPL.

It seems that US law and GPL agree about derivative work but note that GPL is much more specific: they explicitly say they make functions calls [...] and share data structures. If you include git.exe in your program then you're not making any function call. It's (in theory) perfectly allowed by GPL license.

In fact they later explicitly says that:

If the program dynamically links plug-ins, but the communication between them is limited to invoking the ‘main’ function of the plug-in with some options and waiting for it to return, that is a borderline case.

Also note that they generically speak about plugin so it may be applied also to dynamic linked libraries where you invoke just one function (although IMO it should also be the only exported function).

Dependent code is not derivative code, interoperability doesn't make your code a derivative work. There is even sentence from an US court for a similar issue: Lewis Galoob Toys, Inc. v. Nintendo of America, Inc..

Note that they also say:

If the program uses fork and exec to invoke plug-ins, then the plug-ins are separate programs, so the license for the main program makes no requirements for them.

There is no mention about deployment method (one single package or a dependency).

According to GPL license you're in doubt but according to US law you have to incorporate GPL material to be tied to GPL license. You can do it without any problem but if you want to feel more safe then make it a dependency (installed together with your package or a mandatory prerequisite),

Given all these hard reasoning then:

non-GPL application calls a GPL application at the command line -> definitely legal

Yes, if connection between your code and Git takes place at user's computer then you're not restricted by GPL in any way.

non-GPL application links to a GPL application using function calls -> definitely illegal

Maybe not. If you invoke just one main plugin function then it may be a borderline case which IMO should be avoided because contrary to GPL spirit. If you don't like just don't use it.

non-GPL application bundles, distributes, and calls a GPL application at the command line -> ?

Legal, dependent code is not derivative code and interoperability doesn't make your code a derivative work. Moreover they explicitly states that if you use fork/exec then it's not derivative or combined work (no mention about deployment).

From Scott's link a lawyer explains this issue with much deeper knowledge and better wording, I'd like to highlight one passage from that article (emphasis is mine):

The phrase, "This General Public License does not permit incorporating your program into proprietary programs", comes after the "END OF TERMS AND CONDITIONS" statement.  It is not part of the license itself.  In any case, the statement is not supported by the text of the license.  The GPL does not prohibit incorporating proprietary programs; at best, it requires that proprietary programs be subject to the GPL's inheritance obligations.

Also re-read dirty workaround I suggested at beginning if you want to feel safe.


问:
One table for all transaction VS. Table for each user
I'm making a website which has to do with money transactions. Everything was okay untill I came across the dilemma

Should I have one table to store all transaction history or I should have a seperated table for every user?

I tried to logicaly think the best solution and this is what I thought:

One table for all

Pretty much when every other dev would do

However what if i have 100.000 transactions inside?

That would slow down analytis for each user

MariaDB would have to do much more work

One table for each user

Every user is isolated

MariaDB can query faster

Easy data analysis

However what if 10.000 users have a table?

That would flood the database (not big deal if it can handle it)

I dont find anything wrong with using a table for each user but is it a common tachnique to design a database like that?

I found this post over here: What are the advantages/disadvantages of creating a new set of tables for each user?

which pretty much tells that is a terrible idea to have multiple table but does it really matter since in my case

I will never change the structure

I will never edit the data inside, only add new rows

I will enhance the security (principle of least privilege)

答:
Pretty much what every other dev would do

Because it's the right thing to do.

what if i have 100.000 transactions

With proper indexing, that's not a lot.

MariaDB would have to do much more work

Databases are not spreadsheets.
They do not hold the entire table in memory and scan sequentially through it [often].

Most of your 100.000 rows will never be loaded into the server's memory at all; they will sit on disk until they are accessed, via your indexes.
Proper indexing strategies will take care of your [perceived] performance problems.

MariaDB can query faster

Yes, it can query an individual table faster, but it first has to locate that table, which means reading through system catalog tables.
Also, you still need to index each and every table, which means clogging the system up with at least one (probably more) index on all 100.000 tables.

what if 10.000 users have a table?

Then it's going to take longer to find each table in the system catalogs.

And you're ignoring the thorny issue of those cases where you actually do want to scan across every user's' data (say, finding who's got an overdrawn account).

Splitting your data in this way makes queries like this far more difficult that they need to be.

I will never change the structure

Yes you will.

It might not be for some time, but you will.

I will enhance the security

Users should not be accessing this data directly; only through the application that you provide them, which will take care of ensuring that users are only allowed to see what they're supposed to see.


答:
The answer by Andriano Repetti is perhaps correct but you should ask a lawyer (and I am not a lawyer neither), or perhaps the FSF or the copyright owners of the gitsoftware.

Be aware that some people think (and I believe that) if you adapt some GPL software (even if you publish your adapted source code under GPL!) to communicate with your own proprietary product by using a specific, ad-hoc, protocol (e.g. your JSONRPC on pipes) it is not legal (AFAIU) since your code is in that case a derivative work. Things are often different if the same protocol is used by several applications, including a free software one.

The point is that linking or derivative work  has a different meaning to lawyers and judges that for developers. In some countries, the intent you have also matters!

But I am not a lawyer, and you really should ask one. You could also as a courtesy ask the authors of the free software, or even ask the FSF (or the FSFE in Europe, or APRIL or AFUL in France).

BTW, embedding in a compressed file the executable of git inside your application is certainly against the spirit of GPL, since your user is not able to easily replace your git by his own updated or improved version of git. However, you could package git.exe (probably with the source tar ball of that git) and tell your user that he/she needs to install it (and where, and how). If he wanted to upgrade git he should be able to do that easily (so please tell him how to do that). Even if such an executable embedding is legal (and I wish it is not), doing that is certainly user unfriendly. If using git you should at least explain your users which version ranges of git you want, and how to upgrade the git binary.

(Explanations around GCC plugins such as MELT
and GCC runtime license exception and discussions around it might be relevant)

You might consider publishing your software with a free software license. It might be wiser and costs less to you. And you could then get external contributions and feedback.

Title: Can I distribute a GPL executable (not a library) in a closed-source application?

Body:
I want to write a closed-source desktop application that uses a piece of GPL software in the background.

I know that I can't link to a GPL library (libgit.a).  But if I embed a GPL application (git.exe) into a closed source application, unzip the GPL app to a temporary location, and then make calls to it using some form of IPC (e.g. command line arguments), is that legal?

non-GPL application calls a GPL application at the command line -> definitely legal

non-GPL application links to a GPL application using function calls -> definitely illegal

non-GPL application bundles, distributes, and calls a GPL application at the command line -> ?

Distributing a GPL application and making silent IPC calls is functionally identical to linking, as far as the end-user is concerned.  Does GPL care about whether I'm linking inside of one process, or using IPC to do the linking?  It seems like closed source applications like GitHub's desktop clients do this, but maybe I'm misunderstanding how they work.

NOTE: This is different than the other GPL questions on this site, because it asks about embedding a GPL application, not linking to a library in the traditional sense.  The answers have been specific to this case and very helpful to me.

NOTE2: Mods found a new duplicate, and this time they are right - it is actually asking the same question as this (although the details are a little more jumbled).  The best answer has been modded into oblivion though.  Key points are copied here:

VMWare Server's example shows that it's okay to include the object code into your distribution and

install it alongside your program

pack it into a compound file within its footage if it's clearly a compound file and can be taken apart with widely available tools (an ISO image)


问:
Is modifying the User Agent potentially dangerous?
I'm working on an hybrid mobile application, and I'd really benefit of having the app version, OS build and screen sizes of the users that issue our API, just to know if issues come up due to a poorly developed feature or a bugfix that can't fulfill everyone's problems. That way, in a semi transparent procedure I'd be able to track this. I've been testing it with some users, and it works like a charm in ones, but others complain about strange errors that occur upon downloading files from our CDNs.

Could modifying the User Agent affect the download requests for a server, and only affect specific users?

PS: I decided to change the user agent, since some of the info I want is "native code related", and setting that in the user agent would mean no change in the current API calls.

答:
The easiest way to find out is to disable the User-Agent customization and see if the problem goes away :) .

In general, User-Agent is not guaranteed to be what you set.  For example, a corporate firewall might use deep packet inspection to rewrite User-Agent and reduce browser entropy.

Philosophically, I think modifying User-Agent to include additional logging information is a bad idea because it violates the single responsibility principle  (as applied to data - hear me out).  Assume everyone's browser is standards-compliant.  (Your hybrid app is compliant, right? :) )  On mobile devices, User-Agent has a well-defined responsibility: to indicate the user's preference for mobile or desktop rendering.  Google says:

HTTP redirection is a commonly used to redirect clients to device-specific URLs. Usually, the redirection is done based on the user-agent in the HTTP request headers.

Is it ridiculous that a 109-byte (for me) string serves to convey a single bit of information?  Sure, but that's the world we live in.

Rewriting User-Agent to add logging information gives that string a second responsibility.  That means your servers, CDN, logging tools, and everything else have to know about (or at least tolerate) both the logging information and the mobile/desktop intent information.  Whenever you want to change the logging info, you have to make sure you're not breaking anything related to rendering intent, and vice versa.

Even though it may be a pain now, do yourself and those who maintain your code a favor: don't overload User-Agent.  Splitting responsibilities to keep your code simple and loosely coupled will pay for itself many times over by saving time, reducing stress, and preventing hair loss.


问:
Missing super class from dependencies could throw NullPointerException java
Can someone explain if creating an object of a class that have in constructor the super call and the super class are missing from dependencies jar could throw a null pointer exception?

e.g. a class that ApplicationFrame extends javax.xml.ws.Service and as construct let say it's:

```<code>ApplicationFrame(String wsdlLocation, QName namespace){
  super(wsdlLocation, namespace);
 }
</code>```

When doing this I receive a NPE. It's possible?

答:
No.  rachet's gut feeling is spot on.  Unless the classloader is overridden, the classloader loads the parent before it loads a class and if that parent isn't there, you would receive a ClassNotFoundException, and not a NullPointerException.

However, you should consider the possibility that some code in a static block is being run in the parent class that does throw a NullPointerException.  This happens before you even enter the constructor, so you should probably put a breakpoint in your constructor to see if that is the case.

The same can be said for a static block in your own class if you have one, so in that case, I would double-check that your own static block isn't causing the problem.

Hope that helps!


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
I don't like to use a puzzle or a design question as a whiteboard question. I prefer straightforward, simple, questions, that test the candidate's ability to write some code. My favourites are:

1) Write a function to reverse a singly linked list.
(It takes a while before they realise they need 3 pointers.)

2) Given a binary tree, find the depth of the binary tree.
(This question tests their ability to write recursive code. Lets me check if they have their base case intact.)

3) Write a procedure for binary searching an array of integers.
(Like Jon Bentley says (in Programming Pearls), many people tend to make mistakes writing binary search. One can then follow up with finding bugs, writing test cases, running through the code, etc..)


问:
How to integrate Google Cloud Messaging with Cloud Endpoints and Google App Engine
I am trying to build a simple chat messaging app with Android.

I have an Android Studio project with a Cloud Endpoints module. I use this Cloud Endpoints API which is published on my Google App Engine project to communicate with my Cloud SQL database. I can do things like insert rows or delete them. The Cloud SQL database has a table in it called "message" and it is very simple with

```<code>message
-------
id
sender
receiver
datetime
</code>```

Now I want to integrate push notifications using Google Cloud Messaging.

I saw some tutorials such as this one and it explained sort of how it works.

What I do not get is how I can I should set things up with my Cloud Endpoints and my Cloud SQL database so that whenever I write a new row to "message", a push notification is now sent to whatever user it is being sent to.

I know you can use Parse.com for this but how would I do it/set it up using Android Studio + Cloud Endpoints + Google Cloud Messaging, all of which are published on Google App Engine. i.e. how does Snapchat do it (who use Google App Engine)?

答:
there are a several ways you could implement this, of the top of my head:

you can include a call after you insert messages on your DB to dispatch a message via GCM

You can add a "dispatched" field to messages on your DB and have a GAE cron task to pick up un dispatched tasks and send them on a regular basis, marking them as dispatched when the push message goes out.

It really depends on your app context and requirements.


问:
get set method naming conventions
In OOP coding, there is a long standing naming convention to name accessor/mutator methods getThing and setThing. These directly manipulate the properties, which are often private.

Should these naming conventions be 'reserved' solely for manipulating the object properties? or can they be used in other methods - getFileContents ?

I think readFileContents is much clearer as it implies the objects property in this case isn't being accessed, but rather a files contents are being read. However, it is a little ambiguous in that it doesn't imply the results are being returned like getFileContents would.

答:
Naming conventions are simply suggestions. There are no set rules for anything.

The only guideline you need to follow is to name your function according to what it does. If your function readFileContents both reads and returns parts of the file, consider splitting it up into two functions, readFileContents and getFileContents, for example. readFileContents can peruse the file for interesting data and then send it to getFileContents when it wishes to return something. This will separate the concerns so that each function is only doing one thing.

Title: get set method naming conventions


问:
Behaviour of Thread sleep in a single core processor machine?
I'm trying to understand how threading works when using a single core, not hyper-threaded processor.

I have two identical console applications running on a machine that has one core CPU and 1 GB of memory.

In this console application, I have a method that starts a new Thread(). I know that when we Start() a new thread, and Join() the same thread, it blocks the main thread that calls it.

My question is, if I have two console applications doing this, will one block the other?

If so, and in the case that I have a Thread.Sleep(10000) on this console app, in this time, if this sleep is running on one console, will the other freeze?

答:
Starting a new thread, by itself, does not cause the current thread to sleep or freeze. The OS schedules these threads (alongside many other threads) to take turn executing.

If the first application starts the second application as a process, via System.Diagnostics.Process, this also does not cause the current process or thread to sleep or freeze. The threads that run in these two applications (processes) will also take turn executing.

In other words, if anything ever sleeps or freezes, it is either due to your code, or is due to "blocking I/O" in which some input/output operations were performed in a way that doesn't resume execution until that operation is completed. Blocking I/O will only block the thread on which it is performed.

If an application is given OS administrative privilege, it is possible to issue some special OS command to forcibly freeze another process or thread. This is an advanced topic and is typically not encountered in typical software development.

To get a view of processes and threads, you can try the "SysInternals Process Explorer" utility. However, I must warn you that if you misuse this utility, (e.g. randomly terminating applications or threads) it can cause abnormal software operations, data corruptions, or even make your computer stop working, requiring a repair.


问:
What to do when TDD tests reveal new functionality that is needed that also needs tests?
What do you do when you are writing a test and you get to the point where you need to make the test pass and you realize that you need an additional piece of functionality that should be separated into its own function?  That new function needs to be tested as well, but the TDD cycle says to Make a test fail, make it pass then refactor.  If I am on the step where I am trying to make my test pass I'm not supposed to go off and start another failing test to test the new functionality that I need to implement.

For example, I am writing a point class that has a function WillCollideWith(LineSegment):

```<code>public class Point {
    // Point data and constructor ...

    public bool CollidesWithLine(LineSegment lineSegment) {
        Vector PointEndOfMovement = new Vector(Position.X + Velocity.X,
                                               Position.Y + Velocity.Y);
        LineSegment pointPath = new LineSegment(Position, PointEndOfMovement);
        if (lineSegment.Intersects(pointPath)) return true;
        return false;
    }
}
</code>```

I was writing a test for CollidesWithLine when I realized that I would need a LineSegment.Intersects(LineSegment) function.  But, should I just stop what I am doing on my test cycle to go create this new functionality?  That seems to break the "Red, Green, Refactor" principle.

Should I just write the code that detects that lineSegments Intersect inside of the CollidesWithLine function and refactor it after it is working?  That would work in this case since I can access the data from LineSegment, but what about in cases where that kind of data is private?

答:
With jUnit4 you can use the @Ignore annotation for the tests you want to postpone.

Add the Annotation to each method you want to postpone, and continue writing tests for the required functionality. Circle back to refactor the older test cases later.


答: As opposite examples, in Objective-C or Swift you won't see any setThing anymore, and there never was a getThing. In modern use, you have properties in Objective-C and variables in Swift, which are used exactly as if they were plain old member variables that you can read and write. What's going on behind the scenes is then something entirely different. Your getter and setter may just read or write a value, it might do lazy evaluation, it can get notifications just before and just after a setter is called, it can implement getter, setter or both in code. The user of a class sees nothing but a variable. </p>

Title: get set method naming conventions

Body:
In OOP coding, there is a long standing naming convention to name accessor/mutator methods getThing and setThing. These directly manipulate the properties, which are often private.

Should these naming conventions be 'reserved' solely for manipulating the object properties? or can they be used in other methods - getFileContents ?

I think readFileContents is much clearer as it implies the objects property in this case isn't being accessed, but rather a files contents are being read. However, it is a little ambiguous in that it doesn't imply the results are being returned like getFileContents would.


问:
Private setters and getters
I am learning OOP - I have read this answer a number of times and now slowly start to understand some of the practical uses of public interfaces (getters and setters). I understand there is no need to provide public accessors/mutators to every single object property as that breaks encapsulation.

However, in the answer, it is implied that any properties to be manipulated only within that object (i.e. those that don't have a public interface) don't require setters at all. Following this thought, that would imply the same about getters too.

When following S in SOLID, classes become quite small. As such I still use getters and setters for all my properties since adding validation to setters is easy. However, any property that shouldn't be accessed from outside the object I simply designate those setters / getters as protected.

This allows me to keep the validation for use within private methods while still restricting public access. I understand that getters and setters are used to stop other objects directly manipulating another objects properties, but as for 'private' setters / getters - is this necessary (validation aside) or even general practice?

The only other place I see reference to 'private' setters / getters is this answer which touches on inheritance and using private setters / getters to access the parent properties, which makes sense from an encapsulation perspective.

答:
Private getters and setters wouldn't even make that much sense, really. You would be encapsulating the encapsulation and bloat your class, making it hard to read.

The reason people create getters and setters is to restrict the client from doing something stupid with the class data, and for hiding what the class does to the data from the client.

Title: Private setters and getters


问:
How do we control which features get released?
I'm working in an environment where we regularly start working on a feature and then are directed not to release it. We then create other features that we do want to release.

My typical workflow is write feature -> commit to default.

This workflow has worked well historically but in this environment breaks because we need to remove features from the branch.

My thinking for fixing this would be to have a dev branch, where we copy over specific commits related to a given feature.

We use both git and mercurial. Our issue tracker is ALM (which is incidentally the worst piece of software I've ever worked with).

Is there a "standard" way to handle this kind of development? Is there tooling that helps support this workflow? Do these VCS systems have some lesser-known means of supporting it?

答:
I think that your workflow of writing a feature (or a bug fix) and then committing it to the "default" (which appears to be a main or trunk branch) is the problem. Instead, consider using an alternative branching strategy.

I'm typically only focusing on one release at a time, so there's an "integration" branch off of the trunk and then there are development branches for bug fixes or features (and sometimes, they are grouped if it makes sense to group them and force the acceptance of one to drive the acceptance of other bug fixes or features). When a feature is accepted for release, we move it from a development branch into an integration branch, where it will be part of a nightly build and go through a test cycle. When we release, we move from the integration branch to the trunk.

There are other branching strategies as well. If you search for some combination of the phrase "branching strategy" and your version control system, you'll probably come up with several articles and blog posts that may be more relevant.


答:
Each branch has a role.  Branching for a feature is a good one as it allows the feature branch to specifically identify that role.

Always merging back to default implies that default is the roles of mainline, accumulation, and packaging - and this is where you are having trouble.

You should instead consider making a branch for the role of 'accumulation for the release' and then merging your features into the appropriate accumulation branch.

There is nothing saying you can't have multiple simultaneous accumulation branches. One branch for 'next target release' which also has the name '2.0' (multiple names on a branch can make understanding the intent of each easier - though it may also make it trickier to do all the name updates) and then another branch for '3.0'.

If your feature isn't intended to be in 2.0, but is intended to be in 3.0, merge it into 3.0.

Once you are complete with the 2.0 / next release branch, merge that back into default and release it. Then you branch again for the next release branch from default and merge 3.0 into the next release branch and continue from there.

This has the advantage that you can cleanly build the 3.0 branch at any time to see if there are troubles on the horizon - before 2.0 is even released. It also separates the roles and build policies for each branch allowing them be understandable.

Further reading (a favorite of mine when it comes to branching and source control): Advanced SCM Branching Strategies.  In particular, it explains what each role is and how they work together. While its focus is perforce, it can be cleanly applied to git and other distributed version control systems.  Once you read it, give git flow a read and see how those concepts are applied in that model.

Title: How do we control which features get released?

Body:
I'm working in an environment where we regularly start working on a feature and then are directed not to release it. We then create other features that we do want to release.

My typical workflow is write feature -> commit to default.

This workflow has worked well historically but in this environment breaks because we need to remove features from the branch.

My thinking for fixing this would be to have a dev branch, where we copy over specific commits related to a given feature.

We use both git and mercurial. Our issue tracker is ALM (which is incidentally the worst piece of software I've ever worked with).

Is there a "standard" way to handle this kind of development? Is there tooling that helps support this workflow? Do these VCS systems have some lesser-known means of supporting it?


答:
Consider these points:

The "S" in solid does not mean "do one thing."  It means "have one responsibility."  If you find that your classes are proliferating, they may be too small.  There's nothing wrong with a class doing many things, so long as those things all pertain to a single responsibility.  Consider the case of a repository, which has several methods for accessing data, but only one responsibility (that of accessing data).

You can validate information inside a class using ordinary methods.  Getters and setters are intended to be consumed by a client.  All other things being equal, you will confuse the fellow programmer who has to read your code after you write it, for no good reason.

Title: Private setters and getters

Body:
I am learning OOP - I have read this answer a number of times and now slowly start to understand some of the practical uses of public interfaces (getters and setters). I understand there is no need to provide public accessors/mutators to every single object property as that breaks encapsulation.

However, in the answer, it is implied that any properties to be manipulated only within that object (i.e. those that don't have a public interface) don't require setters at all. Following this thought, that would imply the same about getters too.

When following S in SOLID, classes become quite small. As such I still use getters and setters for all my properties since adding validation to setters is easy. However, any property that shouldn't be accessed from outside the object I simply designate those setters / getters as protected.

This allows me to keep the validation for use within private methods while still restricting public access. I understand that getters and setters are used to stop other objects directly manipulating another objects properties, but as for 'private' setters / getters - is this necessary (validation aside) or even general practice?

The only other place I see reference to 'private' setters / getters is this answer which touches on inheritance and using private setters / getters to access the parent properties, which makes sense from an encapsulation perspective.


问:
How to reduce a switch in a switch statement?
So I'm making a method to create a salutation line based on two people from a database.

There are four parameters: the two names (name1 and name2) and the two genders (gender and gender2).

For every gender combination, I have a kind of different output.

For example: if gender 1 is M (man) and gender 2 is also M, the output should be something like:

```<code>Dear Sir name1 and Sir name2,
</code>```

At this time, my switch looks like this:

switch(gender1){
    case 'M':
        switch(gender2){
            case 'M': printf("Dear Sir %s and Sir %s", name1, name2); break;
            case 'W': printf("Dear Sir %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case 'W':
        switch(gender2){
            case 'M': printf("Dear Madame %s and Sir %s", name1, name2); break
            case 'W': printf("Dear Madame %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case ...etc.
}
```

Note that I have multiple gender options, like 'R' for "Dear Relation" and some more that I do not have the time to translate.

How can I reduce this double switch statement?

Putting the second switch in a method is not an option because there is also a case where both of the names are the same and then the output should be combined like: "Dear Sir and Madame name1,"

答:
You would typically want UI strings like this to be pulled in from a string table instead of being hard-coded in the source code, for localization and ease of updating.  So the approach I would take would be to use the inputs to build a lookup key, so something like:

```<code>var lookupKey = "SALUTATION_" + gender1 + "_" + gender2;
var format = GetLocalizedString(lookupKey);
printf(format, name1, name2);
</code>```

The other suggestions about letting users select their own titles is valid, if you have the opportunity to get that information.  I would still use a string table lookup in the solution.

Body:
You would typically want UI strings like this to be pulled in from a string table instead of being hard-coded in the source code, for localization and ease of updating.  So the approach I would take would be to use the inputs to build a lookup key, so something like:

var lookupKey = "SALUTATION_" + gender1 + "_" + gender2;
var format = GetLocalizedString(lookupKey);
printf(format, name1, name2);

The other suggestions about letting users select their own titles is valid, if you have the opportunity to get that information.  I would still use a string table lookup in the solution.


问:
Reading using non-blocking IO on a fd asynchronously in C++ (moving from Node.js)
I'm trying to switch my brain from Node.js/Objective-C iOS programming to C++ programming, and it's a little bit taxing. Node.js and Objective-C with iOS do not have a run loop that I am supposed to manage. So please also help bend my mind to the different concepts.

I am setting up an EAGI program for Asterisk (http://www.voip-info.org/wiki/view/Asterisk+EAGI) that gets fed commands from Asterisk STDIN, sends commands back with STDOUT, and at the same time receives raw PCM audio data on FD 3 (STDERR+1).

At first, the program will be discarding all data it receives from FD 3, until it's ready for the recording. When it's ready to receive the raw audio, it will start taking the data received on FD 3, encoding it, and sending that out on a data socket.

In Node.js we could just pipe all data from fd 3 to something and that would happen "asynchronously" and not interfere with the processing of STDIN data at the same time.

When moving to C++, what is the method I should be using to read from FD 3 while being able to process STDIN and is this all done on the main run loop? And will non-blocking IO code cause the system processor to spike for the duration of the program's runtime, and should I try to use threads instead then?

答:
You (and node.js) cannot read from 2 streams simultaneously on a single thread. You'll have to either interleave reads as data is received, or read from both on different threads.

You could use beginthread() to start a function in a thread, and read from there. Use setbuf() to redirect the FD to a buffer in your program that you can use to read using the standard file IO routines.

... or you can just use Boost::IOStreams or Boost::asio and let the library do all the hard work for you.


问:
MVVM: Strictness of Views Referencing Models
A coworker and I have differing views on how strictly we should adhere to the MVVM concepts. I try to follow it as closely as possible where he takes shortcuts almost every chance he gets. One of my biggest annoyances is when he has views binding to models. His justification is that a viewmodel would just be a reimplementation of the model but with the added complexity of having to catch and rethrow events (most of our models and viewmodels both implement INotifyPropertyChanged).

For example, in one case, there is TheViewModel which exposes TheModel as a property. TheView's datacontext is set to the TheViewModel. TheView contains a TreeView who's ItemSource is a collection on the TheModel. Each child item in the TreeView is some type of model which contains properties that are directly bound to by the TreeView.

```<code>Public Class TheViewModel
  Public Property TheModel as ModelObjectA
End Class
</code>```

```<code>Public Class ModelObjectA
  Inherits ModelBase
  Public Property ModelItems as ObservableCollection(Of ModelObjectB)
End Class
</code>```

```<code>Public Class ModelObjectB
  Inherits ModelBase
  Public Property Items as ObservableCollection(Of ModelBase)
  Public Property IsValid as Boolean
  Public Property Is as Boolean
End Class
</code>```

```<code>Public Class ModelBase
  Public Property Name as String
  Public Property Type as String
End Class
</code>```

```<code><UserControl x:Class="TheView" DataContext="{StaticResource TheViewModel}">
  <TreeView x:Name="ModelTree" ItemsSource="{Binding Path=TheViewModel.ModelItems}" >
    <TreeView.ItemContainerStyle>
      <Style TargetType="TreeViewItem">
        <Style.Triggers>
          <DataTrigger Binding="{Binding IsValid}" Value="False">
            <Setter Property="Background" Value="Red" />
          </DataTrigger>
          <DataTrigger Binding="{Binding IsModified}" Value="True">
            <Setter Property="Foreground" Value="Magenta" />
          </DataTrigger>
        </Style.Triggers>
      </Style>
    </TreeView.ItemContainerStyle>

    <TreeView.Resources>

      <!--ModelObjectB-->
      <HierarchicalDataTemplate DataType="{x:Type mdl:ModelObjectC}" ItemsSource="{Binding Items}">
        <StackPanel>
          <TextBlock Text="{Binding Name}" />
          <TextBlock Text="{Binding Type}" />
        </StackPanel>
      </HierarchicalDataTemplate>

      <!--ModelObjectC-->
      <HierarchicalDataTemplate DataType="{x:Type mdl:ModelObjectC}" ItemsSource="{Binding Items}">
        <StackPanel>
          <TextBlock Text="{Binding Name}" />
          <TextBlock Text="{Binding Type}" />
        </StackPanel>
      </HierarchicalDataTemplate>

      <!--ModelObjectD-->
      <HierarchicalDataTemplate DataType="{x:Type mdl:ModelObjectD}" ItemsSource="{Binding Items}">
        <StackPanel>
          <TextBlock Text="{Binding Name}" />
          <TextBlock Text="{Binding Type}" />
        </StackPanel>
      </HierarchicalDataTemplate>

      <!--Model Base-->
      <DataTemplate DataType="{x:Type mdl:ModelBase}">
        <StackPanel>
          <TextBlock Text="{Binding Name}" />
          <TextBlock Text="{Binding Type}" />
        </StackPanel>
      </DataTemplate>

    </TreeView.Resources>
  </TreeView>

  <ContentPresenter Content="{Binding Path=SelectedItem, ElementName=ModelTree, Converter={StaticResource ModelToViewModelConverter}}" />
</UserControl>
</code>```

Note: This is a simplified version of our real program, and I may have ommited some of the trivial details (such as the UserControl having two child elements and property setter/getters).

I do not believe the above is correct. I think the collections should be exposed to the view as collections of viewmodels (rather than collections of models). Especially when considering that each of the models has a corresponding viewmodel, and in the end, the selected item is transformed into a viewmodel (via a converter).

What does everyone think? Is it ok to have the view binding to models in cases like this, or should the collections be viewmodels? I need some good arguments to either convince my coworker that it should be changed, or to convince myself that the current implementation is the right approach.

答:
You're both right.

In a theoretical perfect world, Views would only know about ViewModels and ViewModels would wrap Models 100%.

The problem is that here in the practical real world, doing that requires writing a bunch of code that:

Provides no tangible benefit

Consumes time that could be used to do other things

Is a potential source of bugs

We have a large MVVM app and I can tell you from experience that keeping ViewModel collections in sync with Model collections is one of more error prone areas of implementing MVVM.

Most of our models support INotifyPropertyChanged and expose ObservableCollections because they can be changed from multiple locations in the application and all of the consumers of the models need to be notified of changes.

At that point, Views can bind to them just fine.  Wrapping that stuff with ViewModels just becomes a bunch of tedious plumbing that's a source of bugs.  In these situations, it's common for us to expose the model instance as a property on the ViewModel.

Another approach I've used that works quite nicely in certain scenarios is to have the ViewModel inherit from the Model.  When you think about it, the ViewModel is quite often simply the Model + some UI logic.  By using inheritance instead of composition, you avoid the odd situation of sometimes binding your view to ViewModel.Foo and other times binding to ViewModel.Model.Bar.


答:
You would use some async IO library (or use the nitty gritty posix or win32 api yourself if you are masochistic) and use it to create a dispatcher loop.

For example in Boost's asio library you would create a boost::asio::io_service open the streams and start the async_read with a handler that will do what you want and call run on the io_service which will start the dispatcher loop.

Title: Reading using non-blocking IO on a fd asynchronously in C++ (moving from Node.js)

Body:
I'm trying to switch my brain from Node.js/Objective-C iOS programming to C++ programming, and it's a little bit taxing. Node.js and Objective-C with iOS do not have a run loop that I am supposed to manage. So please also help bend my mind to the different concepts.

I am setting up an EAGI program for Asterisk (http://www.voip-info.org/wiki/view/Asterisk+EAGI) that gets fed commands from Asterisk STDIN, sends commands back with STDOUT, and at the same time receives raw PCM audio data on FD 3 (STDERR+1).

At first, the program will be discarding all data it receives from FD 3, until it's ready for the recording. When it's ready to receive the raw audio, it will start taking the data received on FD 3, encoding it, and sending that out on a data socket.

In Node.js we could just pipe all data from fd 3 to something and that would happen "asynchronously" and not interfere with the processing of STDIN data at the same time.

When moving to C++, what is the method I should be using to read from FD 3 while being able to process STDIN and is this all done on the main run loop? And will non-blocking IO code cause the system processor to spike for the duration of the program's runtime, and should I try to use threads instead then?


问:
Why use a unique hashkey for form submissions?
I have multiple forms and use AJAX to submit them. I asked my boss if he needed any specific format for the form ID and he told me to generate a unique hash and keep it in session; check it whenever the form comes back to make sure it's a valid form submission and not someone just hitting an endpoint.

What does that mean and why is it useful? How does it help me security wise?

I have read a couple of articles like The 3 things you should know about hashCode() but I'm still not sure...

答:
Why should I do it?

So we create a form, and we'll have an endpoint where that data can get submitted.

Which means anyone can submit data there and see what happens.

So we need to validate on two things:

that it's being submitted by a user (which .NET will handle for us), and

that they're submitting data via a requested form and not just willy-nilly

So the submit button needs a validation hash that gets passed back with the form, then we compare that to the value we stored in the user's session (on the server) when we created the form.

If they match, we process the data, otherwise we throw an error.

Way to do it:

Write a function which converts genrated id and creates hash for it.

Get the form, decrypt the hash to get the original ID, compare them with the id stored in session, and voila.


问:
How to make 100k lines of orphan code work
I've recently started to work on an old project, that was originally written by two professors with no programming experience. Those professors left the project before they have finished it. Meaning there are many files that no one knows what their purpose, or if they are working at all. In general the code is written badly, got many bugs and many unfinished features, though some of it is actually working good. The new incoming programmers (including myself) are quite experienced in programming, but lack the understanding of what's going on in the project.

I've been assigned to make this project reliable and maintainable in the future, and I'm not sure where to begin. I've thought of going over the documentation and code, and listing the things that I think should be changed. I yet to come up with a better idea.

What would you do to handle this project in the most effective way, while bringing him to industry-standard quality?

答:
I would start writing unit tests -- start with the sections of code that work, write characterization tests that demonstrate (and will help preserve) their correct behavior.

Write additional tests that model how the code should work. Get them to pass, without breaking the tests that are already working.

Once you have a nice suite of passing tests in place, you can start experimenting with removing code you think may not be needed, and see if everthing still works.


问:
How do you keep up with 'requiring new methods in an interface' (Following LSP and adding new methods to interface seems to violate ISP)

I have a game that deals with opening and closing doors and the Door Engine

deals with IDoor interface which has Open() and Close() contracts

So far so good. the game is tested and works fine.

Now a new feature is required, doors can be automatically closed with a
timer, i.e a new contract- SetTimer() is needed.
Only parts of my Door Engine need to deal with setting the timer, the rest

of code need not deal with setting timer, i.e the old IDoor interface is enough.

How would you do it?

Add the SetTimer() to IDoor interface? and implement the method in the derived classes approp'ly, the existing Door classes can have a dummy method
and our special TimedDoor can have approp implemention.
Moreover, you could have a 'DoesSupportTimedClosing' contract to make it
perfect LSP compliant.

Respect ISP (I know that ISP is for letting clients create their  implementations without having to implement the entire interface, but can we consider my internal code as a client too, or am I having a wrong understanding) and create a new interface - ITimedDoor : IDoor (ITimedDoor will have the SetTimer contract) you can create timeddoors that implement ITimedDoor, but, is this violation of LSP? If I want some arbitrary piece of existing code to set a timer on a door - I would need to do type checks and type casts to call the ITimedDoor.SetTimer() on the IDoor object it has.

In a nut shell, if you have an Interface - IInterface1 and existing code thats already tested and works fine, how would you handle the requirement of adding new methods to it?

Some references on related topics:

Aren't decorators easily breaking the ISP?

Interview Question - Adding Method to interface that has been implemented by thousands of class

Is this a violation of the Liskov Substitution Principle?

答:
My understanding of the Liskov Substitution Principle differs from yours, i.e.
any implementation of IDoor should behave as a door – do what one expects when Open() or Close() is called – this includes objects implementing ITimedDoor (with ITimedDoor a subclass of IDoor).  It does not imply that any arbitrary piece of code should be able to call SetTimer() on any IDoor with most doors not doing anything useful on a call to SetTimer().

The Interface Segregation Principle – i.e. no client should depend on methods it does not use – combines very well with my understanding of the Liskov Substitution Principle:

Any interface should be minimal: code code should depend on methods it does not use.

Every class that implements an interface should adhere to the same semantics and every object of a class that implements the interface should be exchangeable with every other object of any other class that implements the interface: classes should not implement methods that behave differently (including no-op) than other implementations of that interface's method.

In general, having a collection of IInterface1-objects and then execute a different action depending on the type (or sub interface) will be unavoidable (or at least difficult to avoid).  Using the visitor pattern can be an alternative to run time type checking.

However, in this specific situation – of a game with doors some of which are timed doors – you might be better of with a level builder which build a level containing doors, some of them timed, and sets the timers of the timed doors (or connects the timers to some other events in the level).


答:
One (common) way of solving your problem is with the use of branches, as described by the other answers. However, there is another solution:
feature toggles (aka. feature flags).

The basic idea is that your program maintains a list of flags (the feature flags) that can be switched on and off, and the code that implements the feature checks its corresponding feature flag before doing its work.
So you'd have feature toggles like 'ENABLE_NEW_LOGIN_FORM', 'USE_NEW_TAX_ALGORITHM', 'SHOW_TEASER_FOR_NEW_USER'.
There are many ways to implement this, and many libraries that do it for you, but that is the basic idea.

Advantages (compared to to using branches):

You can merge to main/master as soon as a feature is done; this avoids maintaining branches for a long time, which can mean a lot of work (i.e. merge conflicts) if for example there are refactorings in the main branch.

You have one list of all the features that are completed (the list of feature toggles), instead of many feature branches, whose features may or may not be completed.

You can postpone the decision whether to release a feature or not, and change your mind anytime (as stakeholders are wont to). In contrast, once a branch is merged removing the code is tricky.

You can toggle features after installation or even at runtime, if you want (though this may add some complexity).

Disadvantages

You need some extra code and infrastructure for maintaining the feature toggles.

You will need some ugly (?) if/else checks in the code of each feature that can be toggled (though some languages/frameworks have nice alternatives).

You must test with both features switched off and on, so more testing.

Sometimes, you will have to maintain two codepaths in parallel for the two toggle states, instead of being able to remove the old code.

You must eventually take out feature switches to avoid them cumulating, which means some extra work.

I have used feature toggles when maintaining branches became too painful because of merge conflicts, and found them a very good solution, for the reasons outlined above.

The implementation is usually not difficult; it helps to have a good feature toggle library that plays nicely with the language/framework/runtime you use, and has the features you need (think about things like storage of feature toggles, easy administration, support for switching at runtime...).
We used Togglz (for Java), but there are many options.

Also see: Feature Toggles vs Feature Branches


问:
Analysis project structure in Python
I am about to embark on a large analysis/data extraction project, which I intend to do with Python.

My data to analyse consists of tier 1 files that include some details. and each file points to several tier 2 files. Each of these tier 2 files includes more details and references to PDF files (tier 3) that might need to be analysed. And of course there are lots of cross-references, conflicting details, etc., that will need to be manually curated later in a trackable manner.

To add insult to injury, the extraction has to be repeated on multiple datasets that differ substantially (so most of the extraction code will need to be rewritten). The data is therefore destined to enter a suitable database where it should be structured across all dataset for easy presentation.

I am looking for some advice on how to structure and run all this. I was intending to have e.g. a script for each step (i.e. a script for extracting data from tier 1, populating the database. Script for tier 2 would use database as basis for which files to further analyse, etc.).

My thoughts on file structure are as follows:

```<code>/rawdata  # this is where all input data is located.
    /2009  # and the different datasets, collected by different teams
    /2010  # in different formats, in several different years. *sigh*
/docs  # probably needed for different documentations...
/XX  # for lack of a better name, where the extraction takes place.
    database.db  # common database for depositing extracted data.
    /2009
        step1.py
        step2.py
/manual_curation  # something to track how manual curation was performed.
/output  # contains code for generating the end product in a presentable manner (e.g. pdf-files, web-site, etc.).
</code>```

All of this is naturally contained within a git or SVN repository.

Regarding the database, it is my impression that there are many relations, which is why I am looking at an SQLite database. I have previously used SQLite in several projects. I am also experienced in programming in Python, however, structuring files and running the analyses in a consistent manner is not something I can boast about.

Any advice and experiences in this kind of setup would be very welcome!

(PS. This is a duplicate of my https://stackoverflow.com/questions/31427538/analysis-project-structure-in-python because I've just found this community and thought it might be a more suited place to ask.)

答:
I see this kind of project as a data pipeline. I usually tend to write individual scripts to handle single steps (e.g. normalize 2009 format, normalize 2010 format, process normalized data, etc ...), and then coordinate these steps with a build system.

I have used GNU Make in the past, but I recently have been using Doit and really like it.

If data is really large, you might want to look into processing it on AWS, possibly with the datapipeline product

Title: Analysis project structure in Python


问:
What is the name of the pattern for passing an incomplete object to a constructor?
Several times in javascript I've seen a constructor function take in one parameter. The constructor will initialize all the fields for the object to default values and then use the parameter to overwrite a select few properties. This way you can create a mostly default object save for a field or two with all the remaining properties being present on the object.

What would you name this argument? What is this pattern called?

For example, in Angular, here's a simplified example of how we create our models from our API responses:

```<code>angular.module('app')
  .factory('Person', function() {
    function Person(apiPayload) {
      function defaults() {
        return {
          id: null,
          name: null,
          age: null,
          address: null,
          phone: null,
          email: null
        };
      }

      angular.extend(this, defaults(), apiPayload);
    }

    return Person;
  });
</code>```

It could be used like this:

```<code>var person = new Person({ name: 'Corey' });
</code>```

And person would have all their fields present on the object filled with null except for the name field which would properly have 'Corey'. We name it apiPayload because the only thing we feed to this particular constructor is the data received from our API. I'm looking for a more general name.

答:
configuration object or config object are the terms often used to describe this construct.

It allows to rearrange the parameters in any order, because the properties of the generic object have no ordering. And you don't need a long list of optional parameters.


问:
What does comma signify in a function definition?
From PHP manual:

```<code>array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )
</code>```

What does comma signify in a function definition?

答:
Comma is a separator between parameters in the parameter list.

Comma is part of the parameter lists. Optional parameters are usually specified inside square brackets in documentation like so: [, int $case = CASE_LOWER]. Comma is added to specify that if you were to use the second optional parameter, you must have a comma separator as well.

The fact that comma is inside square brackets, means it's only required when you have more than one parameter.

Another example with more optional parameters:

```<code>array array_change_key_case ( array $array [, int $case = CASE_LOWER [, string $myValue = '' ]] )
</code>```

Body:
Comma is a separator between parameters in the parameter list.

Comma is part of the parameter lists. Optional parameters are usually specified inside square brackets in documentation like so: [, int $case = CASE_LOWER]. Comma is added to specify that if you were to use the second optional parameter, you must have a comma separator as well.

The fact that comma is inside square brackets, means it's only required when you have more than one parameter.

Another example with more optional parameters:

array array_change_key_case ( array $array [, int $case = CASE_LOWER [, string $myValue = '' ]] )


问:
COM - with great power comes great responsibility, but at what cost? (looking for advice on coding practices when working with COM)
What is best (or commonly accepted) practice for where to declare COM object variables (scope) and how to handle cleaning them up when using structured error handling?

I just spend a whole load of time learning about Garbage Collection and Reference Counting and dealing with releasing COM objects in .NET.

Working with COM is annoying...

The Dilemma

I realize it's important to release referenced COM objects after finishing with them.  I also realize it's also important to anticipate and handle errors.

These two things together seem to be at odds with what keeps getting beaten into my head as best practice:  declaring your variables where they are used.

Now, in order to ensure the references are released when done with them, it seems to make the most sense to do this cleanup within the Finally portion of a Try/Catch block.

However, doing so means that I cannot declare these variables within the Try or Catch portions of the block because they will not be accessible to the Finally portion.

SO....

Where does that leave me with regards to following best practices?

Should I continue to declare variables at the beginning of each routine in order to clean them up using Finally?

Is there some other method of accessing COM references at the end of a procedure?

Am I just picking pepper out of fly shit with regards to best practices?

Example Code

In Example 1, I've declared all my variables before entering the Try/Catch block.  This way I can ensure they get cleaned up, regardless of any errors.

In Example 2, I've declared my variables where they are used, but this causes a problem with potential non-release of COM objects.

```<code>Imports System.Runtime.InteropServices

Module COMexamples

    Sub Example1()
        Dim Com1 As SomeCOM
        Dim Com2 As AnotherCOM
        Try
            Com1 = New SomeCOM
            Com1.DoSomeStuff()
        Catch ex As Exception
            Com2 = New AnotherCOM
            Com2.CleanupTheMess()
        Finally
            If Not Com1 Is Nothing Then
                Com1.Close()
                Marshal.FinalReleaseComObject(Com1)
            End If
            If Not Com2 Is Nothing Then
                Com2.Quit()
                Marshal.FinalReleaseComObject(Com2)
            End If
        End Try
    End Sub

    Sub Example2()
        Try
            Dim Com1 As New SomeCOM
            Com1.DoSomeStuff()
            'If an exception is thrown, the object won't get released!
            Com1.Close()
            Marshal.FinalReleaseComObject(Com1)
        Catch ex As Exception
            Dim Com2 As New AnotherCOM
            Com2.CleanupTheMess()
            'Another exception here means we miss releasing this COM reference too!
            Com2.Quit()
            Marshal.FinalReleaseComObject(Com2)
        Finally
            'This is pretty much useless now as Com1 and Com2 are out of scope here
        End Try
    End Sub
End Module
</code>```

答:
Your example 1 is the right way to go because it is logically correct, which is far more important than a minor issue like limiting scope.  Your scope is limited to this procedure, so that is good enough.  If it really bothered you, you could break it up into three procedures, but I only would bother with this if it seemed like the procedure was getting too long anyway.</p>

```<code>Imports System.Runtime.InteropServices

Module COMexamples

Sub Example1()
    Try
        Example1A
    Catch
        Example1B
    End Try
 End Sub

Sub Example1A()
    Dim Com1 As SomeCOM
    Try
        Com1 = New SomeCOM
        Com1.DoSomeStuff()
    Finally
        If Not Com1 Is Nothing Then
            Com1.Close()
            Marshal.FinalReleaseComObject(Com1)
        End If
    End Try
End Sub

Sub Example1B()
    Dim Com2 As AnotherCOM
    Try
        Com2 = New AnotherCOM
        Com2.CleanupTheMess()
    Finally
        If Not Com2 Is Nothing Then
            Com2.Quit()
            Marshal.FinalReleaseComObject(Com2)
        End If
    End Try
End Sub
End Module
</code>```

Body:
Your example 1 is the right way to go because it is logically correct, which is far more important than a minor issue like limiting scope.  Your scope is limited to this procedure, so that is good enough.  If it really bothered you, you could break it up into three procedures, but I only would bother with this if it seemed like the procedure was getting too long anyway.

Imports System.Runtime.InteropServices

Module COMexamples

Sub Example1()
    Try
        Example1A
    Catch
        Example1B
    End Try
 End Sub

Sub Example1A()
    Dim Com1 As SomeCOM
    Try
        Com1 = New SomeCOM
        Com1.DoSomeStuff()
    Finally
        If Not Com1 Is Nothing Then
            Com1.Close()
            Marshal.FinalReleaseComObject(Com1)
        End If
    End Try
End Sub

Sub Example1B()
    Dim Com2 As AnotherCOM
    Try
        Com2 = New AnotherCOM
        Com2.CleanupTheMess()
    Finally
        If Not Com2 Is Nothing Then
            Com2.Quit()
            Marshal.FinalReleaseComObject(Com2)
        End If
    End Try
End Sub
End Module


问:
How to generate Generate Hash incorporating time stamp so it can be unhashed to get the timestamp when it was generated?
I want to create hash based on random id, That hash has to be valid for only 15 minutes. Is there a way to do that?

I'm using this for form submission. If some unknown submitted form or some one submitted after 15 mins I should be able to figure out when it was created?

I am storing random id in session and when user submits form I want to decrypt the value and match with original id. If it matches and it is with in 15 mins or created time then I will add that value to database, after doing some validations.

答:
Its a multipart piece of information you need to communicate.

First off, you provide the timestamp. That is what you validate against for the 'was submitted within 15 minutes'.  Secondly, you have a hash of the timestamp with some additional salt.  The salt is known only to you (on the server).

If the time stamp was altered, the hash of the altered time stamp + salt would not match the hashed unaltered time stamp + salt and you would reject the form submission.

This would look something like:

```<code><form ...>
<input type="hidden" name="timestamp" value="2015.07.15.22:17" />
<input type="hidden" name="timehash" value="9BC54D13B43D456D9167DA13F2E8351B" />
...
</form>
</code>```

Now, you validate against the timestamp. If you check the md5 hash of the string 2015.07.15.22:17somesalt  you will find it to match the md5 sum 9BC5....  And thus you know the timestamp is valid.  If the timestamp doesn't match the hash (with the known salt), then it has been tampered with.

I must point out that somesalt not need be a constant for all pages generated. It could be a random number generated for each user session (and thus persists). Just that it is secret information that you hold and consistent for this user session.

Body:
Its a multipart piece of information you need to communicate.

First off, you provide the timestamp. That is what you validate against for the 'was submitted within 15 minutes'.  Secondly, you have a hash of the timestamp with some additional salt.  The salt is known only to you (on the server).

If the time stamp was altered, the hash of the altered time stamp + salt would not match the hashed unaltered time stamp + salt and you would reject the form submission.

This would look something like:

<form ...>
<input type="hidden" name="timestamp" value="2015.07.15.22:17" />
<input type="hidden" name="timehash" value="9BC54D13B43D456D9167DA13F2E8351B" />
...
</form>

Now, you validate against the timestamp. If you check the md5 hash of the string 2015.07.15.22:17somesalt  you will find it to match the md5 sum 9BC5....  And thus you know the timestamp is valid.  If the timestamp doesn't match the hash (with the known salt), then it has been tampered with.

I must point out that somesalt not need be a constant for all pages generated. It could be a random number generated for each user session (and thus persists). Just that it is secret information that you hold and consistent for this user session.


问:
Finding the optimal root
I am trying to solve a quora hackathon challenge question. The question descrpition is as follows :

For the purposes of this problem, suppose Quora has N questions, and
  question i (1≤i≤N) takes Ti time to read. There exists exactly one
  path from any question to another, and related questions form
  undirected pairs between themselves. In other words, the graph of
  related questions is a tree.

Each time Steve reads a question, he will see a list of related
  questions and navigate to one that he hasn't read yet at random. Steve
  will stop reading once there are no unread related questions.

Which question should we show first to Steve so that we minimize his
  total expected reading time? It is guaranteed that there is one unique
  question that is optimal.

I figured out that the question simply boils down to finding the root from which the average of root to leaves cost is minimum. I originally thought of finding the average cost by taking every node in the tree as a root and then calcualting the average cost for each root. But this would take O(n^2). Since n=10^5, I don't think this will cut it. Any suggestion/hints on solving this in O(n).

The question can be foudn here : https://www.hackerrank.com/contests/quora-haqathon/challenges/relatedquestions

答:
Your solution seems to try to tackle average reading time of nodes and all paths from them. This will, of course, work, provided it's properly implemented.

The problem with this approach is that the quantities you calculate are not reusable. The average reading time of a node depends on how you got to it. Hence the quadratic behaviour of your naive solution. The first step to try to optimize it is to try and find reusable results of calculations.

One such potential result is the cost of taking a link or what's the expected reading time after having gone from question A to question B? . What's the difference between a 'node' and a 'link'? A 'link' has a both a destination and an origin. Since there is exactly 1 path between any 2 nodes and you cannot repeat nodes in your reading, once you take a link, any node that's reachable through the origin is now inaccessible. Hence it does not matter what path you took before the link. Hence this quantity is reusable.

Next we need to answer 2 questions:

Does it help?

How quickly can we calculate this quantity?

First question is easy - if we have the costs of taking links, then it's extremely easy to find the average reading times when given a start node - it's just that node time + average of outgoing links. Hence given these we can get the answer in a single linear lookup.

Second question is slightly more difficult - how do we calculate the costs of taking links in a (relatively) efficient manner?

It's fairly simple if you think about it.

The cost of taking a leaf node is just the expected read time of the leaf.

The cost of taking a link to a node is the node reading time plus the average across all outgoing links from that node except the reverse link.

That's a method. How good is it? It's actually linear! If we take the given tree (and take any node as root), we can work out the costs of taking downward links in a simple linear sweep (since we cannot take an upward link after taking a downward one). After we have all costs of downward links, we can make a second linear sweep from top to bottom to calculate upward links.

Hence given that you can get connections of a node in constant time, the entire thing is just 3 linear sweeps!

Since there is apparently some confusion as to how this works, a step by step of the example input on the website:

We have 5 nodes connected in a chain with weights 2, 2, 1, 2, 2:

```<code>O - O - O - O - O
2   2   1   2   2
</code>```

Take, say, the second node as the root for the procedure. A second variant on the right will have the third node as the root for comparison:

```<code>  O            O
 / \          / \
O   O        O   O
    |        |   |
    O        O   O
    |
    O
</code>```

Compute the cost of taking downward links (on the right of the link):

```<code>   O              O
 /2  \5         /4  \4
O     O        O     O
      |4       |2    |2
      O        O     O
      |2
      O
</code>```

Now compute upward links (left of link):

```<code>   O              O
7/2 4\5        5/4 5\4
O     O        O     O
     5|4      7|2   7|2
      O        O     O
     7|2
      O
</code>```

Note that the results are the same! (As in link costs, not the trees).

Now generate average reading time from this data (node time + left link + right link):

```<code>Node 1: 2 + 0   + 7   = 9
Node 2: 2 + 2/2 + 5/2 = 5.5
Node 3: 1 + 4/2 + 4/2 = 5
Node 4: 2 + 5/2 + 2/2 = 5.5
Node 5: 2 + 7   + 0   = 9
</code>```

Hence the node with minimum expected reading time is Node 3!

Title: Finding the optimal root

Body:
Your solution seems to try to tackle average reading time of nodes and all paths from them. This will, of course, work, provided it's properly implemented.

The problem with this approach is that the quantities you calculate are not reusable. The average reading time of a node depends on how you got to it. Hence the quadratic behaviour of your naive solution. The first step to try to optimize it is to try and find reusable results of calculations.

One such potential result is the cost of taking a link or what's the expected reading time after having gone from question A to question B? . What's the difference between a 'node' and a 'link'? A 'link' has a both a destination and an origin. Since there is exactly 1 path between any 2 nodes and you cannot repeat nodes in your reading, once you take a link, any node that's reachable through the origin is now inaccessible. Hence it does not matter what path you took before the link. Hence this quantity is reusable.

Next we need to answer 2 questions:

Does it help?

How quickly can we calculate this quantity?

First question is easy - if we have the costs of taking links, then it's extremely easy to find the average reading times when given a start node - it's just that node time + average of outgoing links. Hence given these we can get the answer in a single linear lookup.

Second question is slightly more difficult - how do we calculate the costs of taking links in a (relatively) efficient manner?

It's fairly simple if you think about it.

The cost of taking a leaf node is just the expected read time of the leaf.

The cost of taking a link to a node is the node reading time plus the average across all outgoing links from that node except the reverse link.

That's a method. How good is it? It's actually linear! If we take the given tree (and take any node as root), we can work out the costs of taking downward links in a simple linear sweep (since we cannot take an upward link after taking a downward one). After we have all costs of downward links, we can make a second linear sweep from top to bottom to calculate upward links.

Hence given that you can get connections of a node in constant time, the entire thing is just 3 linear sweeps!

Since there is apparently some confusion as to how this works, a step by step of the example input on the website:

We have 5 nodes connected in a chain with weights 2, 2, 1, 2, 2:

O - O - O - O - O
2   2   1   2   2

Take, say, the second node as the root for the procedure. A second variant on the right will have the third node as the root for comparison:

  O            O
 / \          / \
O   O        O   O
    |        |   |
    O        O   O
    |
    O

Compute the cost of taking downward links (on the right of the link):

   O              O
 /2  \5         /4  \4
O     O        O     O
      |4       |2    |2
      O        O     O
      |2
      O

Now compute upward links (left of link):

   O              O
7/2 4\5        5/4 5\4
O     O        O     O
     5|4      7|2   7|2
      O        O     O
     7|2
      O

Note that the results are the same! (As in link costs, not the trees).

Now generate average reading time from this data (node time + left link + right link):

Node 1: 2 + 0   + 7   = 9
Node 2: 2 + 2/2 + 5/2 = 5.5
Node 3: 1 + 4/2 + 4/2 = 5
Node 4: 2 + 5/2 + 2/2 = 5.5
Node 5: 2 + 7   + 0   = 9

Hence the node with minimum expected reading time is Node 3!


问:
Convert this abstract class to an interface
I have a security method I would like to be able to sprinkle into other classes throughout my program. It is currently an abstract class but I feel it would be more appropriate as an interface. Can someone help me convert it? I wasn't able to call PrincipalIdentity() the same way I could with it being abstract.</p>

```<code>public abstract class SecurityBase {

        public GenericPrincipal PrincipalIdentity() {

            WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

            string authenticationType = windowsIdentity.AuthenticationType;
            string userName = windowsIdentity.Name.Split('\\')[1];;

            GenericIdentity authenticatedGenericIdentity = new GenericIdentity(userName, authenticationType);

            string[] Roles = //generate array;
            GenericPrincipal pr = new GenericPrincipal(authenticatedGenericIdentity, Roles);

            return pr;
        }
    }
</code>```

答:
I agree with Alexus.  Below is the interface that would go with your abstract above.  You cannot put logic into an interface so this is all you get.</p>

```<code>public interface ISecurity{
    GenericPrincipal PrincipalIdentity();
}
</code>```

Body:
I agree with Alexus.  Below is the interface that would go with your abstract above.  You cannot put logic into an interface so this is all you get.

public interface ISecurity{
    GenericPrincipal PrincipalIdentity();
}


问:
Is using up 'too much' storage space a practical concern when storing only text in a database in 2015?
I originally started writing a question on StackOverflow about a clever way to optimise keeping a version history of large text fields in a relational database table, possibly by using deltas instead of incurring the storage cost of a full copy of the changed text in an audit table on each update, which is regularly suggested as the simplest way to keep version history in a database.

As I was writing it, I began to wonder, what exactly do I mean by incur the storage cost, really?

I've read in a few places on the internet that the complete works of Shakespeare uncompressed comes to around 5Mb, so assuming that's true, 1TB could hold roughly 200,000 copies.

That is a big book, with a lot of text in it. 200,000 is a lot of copies of that book. A 1TB spinning disk will not exactly break the bank these days, either.

When we're talking about text in a database in 2015, is it wasted effort to think about compression, optimisation, or even deliberately minimising inputs, or is storage cheap enough now that I'm never going to have to care about hitting an upper limit, in practice, and I should instead optimise for app code and schema simplicity?

答:
Calculate your storage costs. Add the cost of high(er) availability, backups, version control. Look what S3 or Backblaze or whatever else would charge for this amount and traffic; compare to having your own servers / NAS / SAN / datacenter (I don't know your volumes).

Then compare that to the cost of hiring a qualified developer / sysadmin to create and keep up your solutions: highly optimized and straightforward. A few ballpark figures would be enough.


答:
Is there a reason you need this method in your business classes at all? I can't see any reference to this or to other member fields, meaning it's a disconnected utility method that can happily sit in a UserProvider sort of class, a service that is probably orthogonal to your actual business domain.

If you do want to have it as part of your objects, you can simulate implementation inheritance with interfaces using extension methods:

```<code>public interface ISecurityEnabled
{
     // empty marker interface.
}

public static class SecurityExtensions
{
    public static GenericPrincipal GetPrincipalIdentity
           (this ISecurityEnabled securityEnabledObject)
    {
         // your code here.
    }
}
</code>```

This will allow you to call GetPrincipalIdentity on every object that's marked with the ISecurityEnabled interface. If the method actually needs any properties from that object, add them to the ISecurityEnabled interface to have them available in the extension method.

Title: Convert this abstract class to an interface

Body:
I have a security method I would like to be able to sprinkle into other classes throughout my program. It is currently an abstract class but I feel it would be more appropriate as an interface. Can someone help me convert it? I wasn't able to call PrincipalIdentity() the same way I could with it being abstract.</p>

```<code>public abstract class SecurityBase {

        public GenericPrincipal PrincipalIdentity() {

            WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

            string authenticationType = windowsIdentity.AuthenticationType;
            string userName = windowsIdentity.Name.Split('\\')[1];;

            GenericIdentity authenticatedGenericIdentity = new GenericIdentity(userName, authenticationType);

            string[] Roles = //generate array;
            GenericPrincipal pr = new GenericPrincipal(authenticatedGenericIdentity, Roles);

            return pr;
        }
    }
</code>```

Body:
Is there a reason you need this method in your business classes at all? I can't see any reference to this or to other member fields, meaning it's a disconnected utility method that can happily sit in a UserProvider sort of class, a service that is probably orthogonal to your actual business domain.

If you do want to have it as part of your objects, you can simulate implementation inheritance with interfaces using extension methods:

public interface ISecurityEnabled
{
     // empty marker interface.
}

public static class SecurityExtensions
{
    public static GenericPrincipal GetPrincipalIdentity
           (this ISecurityEnabled securityEnabledObject)
    {
         // your code here.
    }
}

This will allow you to call GetPrincipalIdentity on every object that's marked with the ISecurityEnabled interface. If the method actually needs any properties from that object, add them to the ISecurityEnabled interface to have them available in the extension method.


问:
How did JavaScript become popular?
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?

答:
Right time, right place. And it didn't entirely suck. </p>

<p>It's the same reason facebook is winning.    </p>

Title: How did JavaScript become popular?

Body:
Right time, right place. And it didn't entirely suck.

It's the same reason facebook is winning.


问:
An Introductory Tutorial for Neural Net Backpropagation with Simplified Math
I built a neural net, and planned on optimizing the weights using a genetic algorithm. I was informed  though, that this isn't a good idea, and to look into backpropagation.

I searched around, and found either very superficial overviews of the algorithm (which conceptually isn't that difficult), or very in-depth guides of the math. All the math I've seen appears to be calculus (although I wouldn't know, as I don't yet know calculus), so it's difficult for me to see what's going on.

I looked up the concept in
Artificial Intelligence: A Modern Approach, but as with everything else in the book, the math looks arcane.

I understand the process is basically:

Propagate the input towards the output.

Once it reaches the output, compare the result to what you expected it to be.

The error (expected - actual) is calculated.

Starting at the output, the error is propagated back through the network, and the weights are adjusted accordingly.

My issue is point 4. How can you know a hidden node's effect on the output?

Can anybody explain backpropagation of a neural net, with math that can be understood at a sub-calculus level?

答:
"Hidden" nodes aren't really hidden like a black box - it is just a layer in between your input and output nodes. You program will have the values of all weights and the signal values propagated through the neural network.

Once you have the output error, you can use all that information with the "archaic" (do you mean arcane?) mathematics.

I found this PDF through wikipedia which has more accessible examples: https://www4.rgu.ac.uk/files/chapter3%20-%20bp.pdf

So, the hidden layer node errors are calculated from the output error multiplied by the weight of the connection between the hidden node and output node - and then the weights from input to hidden node can be modified from this error. In the simple case of a single output node:

```<code>δα = outα (1 - outα) (Targetα - outα)
output error = actual output * (1 - actual output) * (output we want - actual output)

δA = outA (1 – outA) (δαWAα)
hidden node error = output of node * (1 - output of node) * (output error * weight between hidden and output node)
</code>```

Programmatically, you want to calculate all the node error values before adjusting any weights.

Body:
"Hidden" nodes aren't really hidden like a black box - it is just a layer in between your input and output nodes. You program will have the values of all weights and the signal values propagated through the neural network.

Once you have the output error, you can use all that information with the "archaic" (do you mean arcane?) mathematics.

I found this PDF through wikipedia which has more accessible examples: https://www4.rgu.ac.uk/files/chapter3%20-%20bp.pdf

So, the hidden layer node errors are calculated from the output error multiplied by the weight of the connection between the hidden node and output node - and then the weights from input to hidden node can be modified from this error. In the simple case of a single output node:

δα = outα (1 - outα) (Targetα - outα)
output error = actual output * (1 - actual output) * (output we want - actual output)

δA = outA (1 – outA) (δαWAα)
hidden node error = output of node * (1 - output of node) * (output error * weight between hidden and output node)

Programmatically, you want to calculate all the node error values before adjusting any weights.