答:
Setting aside the issue of the practicality of this one, roll-your-own licenses are a bad idea for everyone involved.  (Apart from lawyers ...)

Unless you have legal training, you should not attempt to invent your own licenses.  You may think you know what those words mean, but when interpreted by a law court, they may mean something different to what you intend them to.  And the licensee of your software would have the same problem.  They would have to talk to their lawyers to get an opinion on what the license would mean for them and their businesses.

If you are lucky, the best that can happen is that lots of potential users / customers will just say "No ... too legally risky".  The worst that can happen is that some shyster company / lawyer will figure out how to exploit a loophole in your wording, you take them to court, and you lose big time.

The short answer to your headline questions is:  Yes, Pass, No, No, Yes, AFAIK No.

Here are some specific problems with your proposed license.

The notification clause is onerous on licensees.  They are now at legal risk if they accidentally redistribute.  That means (if they take this risk seriously) they need to set a compliance system to track their redistributions to ensure that they do send you that email.

The notification clause pretty much guarantees that no creditable open source distribution will include your software.  The burden it places on them, and on downstream redistribution is simply too great.  (And the chances that they will want to help you on this are about zero.)

You don't define terms like "notification" and "redistribution".  A smart lawyer could probably figure out how to make them mean what they want.

Notification of copyright holders is legally problematic for the licensee, considering that the licensee cannot know who all of the copyright holders actually are.

You don't mention how the notification would be made.  What about the scenario where it is sent by email and the email gets lost?  What happens if there is a problem with email at your end?  What are you going to do if a smart lawyer demands that you produce evidence that you / your email provider hasn't lost the email.

Are you going to expend your time and energy ensure that people comply with the notification requirement?  If you don't, a smart lawyer can use that against you.  (Read up on "Laches")

Finally, you wanted something that is more corporate friendly than GPL.  I'd say that this is (in some respects) LESS corporate friendly ... for corporates who are prepared to play by your rules.  For example, for corporates who want to be able to ship binary only, clause 5) means they have to grant you unconditional access to any secrets embedded in their code; i.e. no NDA.  There is nothing stopping you from exploiting that information, including (for instance) selling it to their competitors.

Title: Does this BSD-like license achieve what I want it to?

Body:
I was wondering if this license is:

self defeating

just a clone of an existing, better established license

practical

any more "corporate-friendly" than the GPL

too vague/open ended

and finally, if there is a better license that achieves a similar effect?

I wanted a license that would (in simple terms)

be as flexible/simple as the "Simplified BSD" license (which is essentially the MIT license)

allow anyone to make modifications as long as I'm attributed

require that I get a notification that such a derived work exists

require that I have access to the source code and be given license to use the code

not oblige the author of the derivative work to have to release the source code to the general public

not oblige the author of the derivative work to license the derivative work under a specific license

Here is the proposed license, which is just the simplified BSD with a couple of additional clauses (all of which are bolded).

Copyright (c) (year), (author) (email)

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

Redistributions of source code must retain the above copyright notice, this    list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice,    this list of conditions and the following disclaimer in the
documentation    and/or other materials provided with the
distribution.

The copyright holder(s) must be notified of any redistributions of source    code.

The copyright holder(s) must be notified of any redistributions in binary    form

The copyright holder(s) must be granted access to the source code and/or the    binary form of any redistribution upon the copyright
holder's request.

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


问:
What recommendations can you give in managing a team of remote software engineers?
I am a Web application developer who also is responsible for project managing some projects, I sometimes have to manage remote developers, who work for me under a contract basis. I feel that sometimes it is really difficult to manage. I am facing some strange situations. For example:

Once a developer didn't respond for two days while we had to deliver a project. (didn't attend calls or respond to emails )

Once a developer templated a CMS with static solution (this one had less expertise I think).

Once I asked a developer to complete search functionality, the next day he said done, but when I looked, it wasn't done. Upon asking I came to know that, he had done the search but not search result listing formatting :). (I guess he is unable to manage his time while working from home)

So does this mean that I don't have right people? Or there is a problem in project management that I need to cover? I understand that sometimes misunderstandings can happen, and therefore we need to communicate in writing using a tool like unfuddle or basecamp, but what we can do for instance in the above situations? The person who did has at least 2 years of experience as a developer.

So I actually want to know: where is the problem? I am a programmer and know that programmers understand these things, then what should I do in such cases?

答:
I help manage remote teams for our clients, and these are the best practices we follow (based on agile and scrum):

Daily Skype Standups - Every day the full team gets on skype for 15 minutes to coordinate and collaborate.  We discuss what we did yesterday, what we plan to do today, and if we have any obstacles.

Maintain consistent teams - We keep the same people on the project so that they can develop a relationship with the customer and truly understand their needs.  We don't sub-contract out different parts to different people and then try to manage them separately.  They need to operate as a single team.

Weekly Demos - We follow 1 week Scrum sprints.  That's shorter than many Scrum teams like to do, but for us it's important to do weekly demo's with customers.  Demoing that frequently is really critical on remote projects because it makes sure we don't go too long without customer feedback.  The example you gave where they implemented search but not search styling is something that would have been caught in one of those regular demos.

Lightweight weekly planning sessions over detailed contracts.  Someone else mentioned contracts, but in my experience they don't help with defining clearly what the freelancer needs to get done.  You likely can't predict with certainty what they need to do weeks or months in advance, so instead have a contract that makes it very clear how much you are willing to pay per hour and a maximum amount of time you are willing to bill for.  Then adjust the scope every week and give them clear instructions what the most important priorities are for the next week, and your definition of "done" for those priorities.  This allows you to manage the scope as you go, give clear direction to the team, and stay within your budget.

I know this reply is well after you original post, so hopefully you've long since solved your particular project's challenges.  But I wanted to reply anyways in case it's helpful to others who may come across this article.  Good luck!

ContentLicense: CC BY-SA 3.0


问:
Is it bad to learn multiple programming languages?
I started learning PHP and I was able to get myself familiar with it. Now, I want to explore other programming languages like PERL so that I can compare it myself to PHP. Will I be confused to learn two language? Or are there any disadvantages?</p>

答:
Short Answer: If you’re just starting your programming career, then I would advise you to focus on learning just one programming language at a time.

This is because there’s little to be gained by listing many programming languages on your resume without really being good or highly skilled in any of them!

As a general rule, it’s far better to learn one programming language and master it well before learning other programming languages.


答:
I would spend some time getting decent at your first language, but once you have done that start exploring. There are a lot of languages out there and a lot of them are nicer then PHP or do something better. </p>

<p>I would take a look at the book "Seven Languages in Seven Weeks" which will walk you threw Ruby, IO, Scala, Prolog, Erlang, Clojure and Haskell which will make you  learn a whole bunch of new ways to code.  </p>

Title: Is it bad to learn multiple programming languages?

Body: I started learning PHP and I was able to get myself familiar with it. Now, I want to explore other programming languages like PERL so that I can compare it myself to PHP. Will I be confused to learn two language? Or are there any disadvantages?</p>

Body:
I would spend some time getting decent at your first language, but once you have done that start exploring. There are a lot of languages out there and a lot of them are nicer then PHP or do something better.

I would take a look at the book "Seven Languages in Seven Weeks" which will walk you threw Ruby, IO, Scala, Prolog, Erlang, Clojure and Haskell which will make you  learn a whole bunch of new ways to code.


答:
I too started out with PHP. It's a good first choice as there is a pretty large community, and there is a good chance you can pick up a job writing it. </p>

<p>I wouldn't recommend picking up another similar language (such as PERL, Python, etc), as ultimately, you won't probably learn much other than more syntax. However, you might take some time and brush up on your javascript. jQuery is great, but that choice is yours. The best part? You can use both at the same time, so you can continue to grow professionally in both directions. </p>

Body:
I too started out with PHP. It's a good first choice as there is a pretty large community, and there is a good chance you can pick up a job writing it.

I wouldn't recommend picking up another similar language (such as PERL, Python, etc), as ultimately, you won't probably learn much other than more syntax. However, you might take some time and brush up on your javascript. jQuery is great, but that choice is yours. The best part? You can use both at the same time, so you can continue to grow professionally in both directions.


答: Learn anything that interests you.  If you want to learn Perl instead of studying PHP go ahead.  The most important thing is to be learning something.  In my opinion, knowing multiple languages at some level makes a better programmer than knowing only one in depth.  </p>


问:
How should I implement permissions?
I am using cppcms to create a blog like application and I'm trying to write a permission system, although I'm confused as to what would be the most efficient and manageable method.

At the moment, I have a table with permission id, user id, permission type (int) and permission value (an optional parameter, of sorts). For each separate permission, a row must be added.

Which method would you recommend?

If you want any clarification or extra information, feel free to ask.

答:
In general, I think it's best to break out data into logical chunks. For example, you should probably make a user table, a permission table (for specific one off permissions) and then a group table.

From there, users should belong to groups, and groups should have permissions.

After you store the base information, you need to add a relation table. This will basically hold a record for each relation i.e.: record 1 would be user id 1, group id 1. record 2 could be group id 1, permission id 2. etc.

Title: How should I implement permissions?


问:
Should we use python 2.6 or 2.7 or 3.x?
The version of python which I am using is 2.6, and there is a 2.7 and 3.x. Usually I use python for some trivial program/snippet. I realize there are some major difference between 2.x and 3.x. I would really like to know, if I am going to make a bigger project with python, which version of python should I use?

Should I upgrade to 2.7, or go to 3.x or stay with 2.6?

The decision should be based on these terms:

Number of user in the internet as a community. More users mean more open-source package and help from them.

Functionality.

Support from official development team.

Compatibility for existing module/package.

Thanks!

答:
It doesn't really matter whether you use Python 2.7 or Python 3
If you do not use old features in Python 2.7, you can just 2to3 your code to make it run on Python 3.</p>

Title: Should we use python 2.6 or 2.7 or 3.x?


问:
How does learning assembly aid in programming?
I have been programming in higher level languages (Python, C#, VBA, VB.NET) for around 10 years and I have completely zero understanding on what's going on, "under the hood."

I am wondering what are the benefits of learning assembly, and how will it aid me as a programmer? Can you please provide me with a resource that will show me exactly the connection between what I write in higher level code to what happens in assembly?

答: Normally it's VERY important for debugging purposes.  What do you do when the system breaks in the middle of an instruction and the error makes no sense?  It's much less of an issue with .NET languages so long as you're only using safe code--the system will almost always shield you from what's going on under the hood.

OwnerDisplayName: Артём Царионов


问:
PHP function __autoload($class_name) how to Load two class path directories
I am using following function to autoload classes, it works fine if i am using only one directory called 'classes' however when i try to use Smarty lib also it fails and give me the error

```<code>Fatal error: Class 'Database' not found in /home/...
</code>```

for ex:

```<code>require_once(DOC_ROOT."/libs/Smarty.class.php");
function __autoload($class_name) {
    require_once( CLASS_LIB."/".$class_name . '.class.php');
}
$db = new Database();
$session=new Session();
$smarty = new Smarty();
</code>```

but if i do this it give me the error unable to load the smarty class..

```<code>function __autoload($class_name) {
    require_once( CLASS_LIB."/".$class_name . '.class.php');
    require_once(DOC_ROOT."/libs/Smarty.class.php");
}

$db = new Database();
$session=new Session();
$smarty = new Smarty();

Warning: require_once(/home/.../classes/Smarty_Internal_TemplateCompilerBase.class.php) [function.require-once]: failed to open stream: No such file or directory in /home/.../includes/init.php
</code>```

Any idea what i am i doing wrong here ? i need to be able to load classes directory automatically but needs to make sure i dont loose smarty path too..

答:
Several solutions come to mind.

Use include_once instead of require_once to avoid the error.

Check for the existence of the file before doing the require_once.

Put in an if statement detects Smarty and special cases the code.

Just include the Smarty classes manually.

(Best) Use spl_autoload_register twice, once for your classes and once for the Smarty classes. __autoload is deprecated. Spl_autoload_register should handle the problem.  http://php.net/manual/en/language.oop5.autoload.php


问:
Were method cascades ever considered for C#?
Smalltalk supports a syntax feature called "message cascades". Cascades are being adopted by the Dart Programming language.

As far as I know, C# doesn't support this. Were they ever considered during the design of the language? Is it conceivable that they could appear in a future version of the language?

答:
Fluent interfaces are easily supported in C# by using return this.

In Linq, extension methods are used to accomplish the same thing.  Extension methods over IQueryable or IEnumerable are easily chained together.

Cascades, as described by the page at the link you provided, seem to be merely a subtle refinement of an ordinary Fluent Interface where return this is not required to make it work, as all method calls beginning with .. refer to the first returned result:

```<code>query('#my-form').query('button')
    ..classes.add('toggle')
    ..text = 'Click Me!'
    ..labels.add(toggleLabel);
</code>```

Does C# support this?  No, not exactly.  But you can still write the following equivalent code:

```<code>var result = query('#my-form').query('button')
result.classes.add('toggle')
result.text = 'Click Me!'
result.labels.add(toggleLabel);
</code>```

and it is only slightly more verbose (and arguably easier to read).

As to the question, "Were they ever considered for C#," you would have to ask Anders Hejlsberg or Eric Lippert about that.  My guess is that they view it as syntactic sugar, which in fact it is.

Body:
Fluent interfaces are easily supported in C# by using return this.

In Linq, extension methods are used to accomplish the same thing.  Extension methods over IQueryable or IEnumerable are easily chained together.

Cascades, as described by the page at the link you provided, seem to be merely a subtle refinement of an ordinary Fluent Interface where return this is not required to make it work, as all method calls beginning with .. refer to the first returned result:

query('#my-form').query('button')
    ..classes.add('toggle')
    ..text = 'Click Me!'
    ..labels.add(toggleLabel);

Does C# support this?  No, not exactly.  But you can still write the following equivalent code:

var result = query('#my-form').query('button')
result.classes.add('toggle')
result.text = 'Click Me!'
result.labels.add(toggleLabel);

and it is only slightly more verbose (and arguably easier to read).

As to the question, "Were they ever considered for C#," you would have to ask Anders Hejlsberg or Eric Lippert about that.  My guess is that they view it as syntactic sugar, which in fact it is.


答:
My recommendation: think about how many

implementation exist currently in this world for access management? I would bet some millions.

man-hours are built into this field already? I can't even guess, and most of them are totally parallel...

open source solutions are there, ready to use in your system?

So, it is very good that you started thinking about it, created a simple implementation, identified the core components and their functions.

But now you should focus on the task you have to do, and don't waste time on access management. It will surely be worse (less features, weaker structure, less tested, has several vulnerabilities caused by the problems of your platform you haven't even known) than anything that is available for you right now to integrate and use (well, I have assumed that you are not Superman and not pioneering on an esoteric field, both are very likely).

Imagine your application in its full size, collect the features and assumed counts (user, feature, role, requests per second, ...). Use Google to narrow your search to like five solutions, compare them by their reflection on forums, blogs, etc., select one and use it. On the other hand: separate you actual choice from your code with a custom interface that you create by your feature list. This will be a bless if you have to switch to another solution because of something that you don't know today.

I think this approach has more benefits even if you write this system in order to learn. You should adapt to formalize your requirements, evaluate available solutions and learn from other coders' good solutions instead of making the same beginner mistakes from which those solutions have evolved. To become a reliable programmer, you have to find the right balance between writing and using components, and learn to objectively value your time, and the quality of your code compared to what is available (background knowledge, coding perfection, available amount of man-hours to bug fix and maintain, for development and real-life test).

You don't write your word processor to edit a text file. Why? Then why should you write an access control component (and copy-paste it to other systems that you make)?

In some cases, there is an objective reason for both. In most cases, there is none. Sadly enough, programmers tend to think that a word processor is more serious task (so they use one) than a writing a truly reliable access management (so they write one). Last note: contrary to all above, it is very likely that I will write an access manager - but I have a good reason to do it. :-)

Title: How should I implement permissions?

Body:
I am using cppcms to create a blog like application and I'm trying to write a permission system, although I'm confused as to what would be the most efficient and manageable method.

At the moment, I have a table with permission id, user id, permission type (int) and permission value (an optional parameter, of sorts). For each separate permission, a row must be added.

Which method would you recommend?

If you want any clarification or extra information, feel free to ask.


问:
Approaches to manage related binary files, apart from code
I'm working on a website for a photographer, the whole code is just a few files, and whole repository is a few MBs without the actual photographs.

But, when I add the actual photographs to git and commit, then the repository jumps to 75 MBs. Considering the photos will be updated, the size of the repository is going to grow big as photos gets updated. I know I'm doing something very wrong.

Please, share your methods, for managing big binary files separate from source code, and still maintain dependencies.

PS: I don't use a db currently, all are plain text files.

答: 75MB is not a problem for git, but you might want to check out git-annex which looks like it can do what you want.</p>


问:
In what specific ways did Pascal and or Delphi influence Java?
I was reading in the side bar of the Java language wiki page and it says it was influenced by Pascal and Delphi.
this isn't the fact anymore, there are no references to Delphi on the entire referenced wiki page as of this edit, probably should remove all references to Delph from this question as well

At first glance Java appears to just be C++ with a garbage collector, and no pointers. Delphi and Java both came out the same year.

I am curious if someone who knows Java and Pascal / Delphi really well could look at Java and say "Feature X in Java is influenced by feature Y in Pascal (or Delphi)."

Additionally was the influence in later versions of Java (so the feature from Pascal or Delphi didn't show up until Java version Z), or was it actually in the seeds of the Java language? Delphi and Java both came out the same year, so Delphi's influence in the genesis of Java seems less likely.

Alternatively it may be that Delphi or Pascal influenced the Java Platform in some other way, and not the language specifically.

[This was rewritten to be clearer. That may have changed the scope of the question to the point the existing comments and answers don't fit. My intention was to clarify and not change.]

答:
Contrary to popular folklore, Java was strongly influenced by Objective-C and not C++. This is a usenet post by one of the people working on the Oak project that became Java. He explains that Oak had a number of people who'd come to Sun from NeXT, and that key early decisions in Java's design like single inheritance, multiple interfaces and supporting both primitives and object-type number vales came from ObjC.

Notice that the conversation also describes just how far removed the principles of Modula-3 - and by association Pascal - are from Java.


问:
Company PC refresh, laptop or desktop?
My company is getting PC refreshes with a choice of to have a desktop or laptop.  Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time?

I'm not asking what would be better for coding, but more for convenience and productivity.  I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.

答: Desktop at work, desktop at home, Dropbox and/or GotoMyPC if you need to work remotely or share files. And perhaps a Netbook if you need to travel to meetings where you give presentations or take notes.</p>

ContentLicense: CC BY-SA 2.5

Title: Company PC refresh, laptop or desktop?


问:
Authentication Systems - Separate for Management?
Edit: I admit to being unclear when I first wrote the question. I suppose I wasn't sure of the issue myself, the comments and answers provided up to now helped me focus on the issue, thank you to all involved. This edit is a total rewrite of the question.
End editorial comment

On a dynamic website we have two systems - content management, and user interface (trivial).

We are trying to decide if the two should have separate authentication systems (being two systems, this might increase security [or not - @GlenH7?]), each having its own hierarchy of permissions etc.

Or is it better to have a single system (it's the same database, after all... plus easier maintenance) and only play around with permissions (regular, jumbo, power, super nova, admin, Q)?

答:
An Administrator is Role which is a super-set of all permissions and usually means something special semantically outside these permissions as well, as in having special permissions that no other role can have.

A Regular User with extended permissions is still a Regular User, but with additional permissions and by definition can't have the special permissions of an Administrator.

The two are not logically equivalent or semantically equivalent as they should also be orthogonal.

Maybe what you really want to define is a Power User if you don't have anything specific that an Administrator can only do.

Either way I would add auditing the system and I would try and re-use some underlying or existing role based authentication and authorization system rather than creating your own. This focus on the location of the authentication in this question alone tells me you will get it more wrong than right. Why would you think you need two authentication systems, twice as much work, twice as much change to make mistakes, twice as much chance for failure, etc.


答:
For web applications you may want to consider the Google Picasa  services.

Or alternatevly manage your picture gallery in the Cloud. You may simply store the access link to that pictures, while getting them on your pages.

Title: Approaches to manage related binary files, apart from code

Body:
I'm working on a website for a photographer, the whole code is just a few files, and whole repository is a few MBs without the actual photographs.

But, when I add the actual photographs to git and commit, then the repository jumps to 75 MBs. Considering the photos will be updated, the size of the repository is going to grow big as photos gets updated. I know I'm doing something very wrong.

Please, share your methods, for managing big binary files separate from source code, and still maintain dependencies.

PS: I don't use a db currently, all are plain text files.


问:
What is a normal "functional lines of code" to "test lines of code" ratio?
I'm pretty new to TDD approach and my first experiments say that writing 1 line of functional code means writing about 2-3 lines of testing code. So, in case I'm going to write 1000 LOC, the whole codebase including tests is going to be something like ~3500 LOC.

Is this considered normal? What is the ratio in code you write?

答:
1:3 is normal with TDD.

From my experience, and also from other citations I remember.


答:
To answer the direct question of convenience and productivity, plus the hidden question of extra work at home, I would go with the desktop.  You find yourself looking at work email, continuing work problems and generally bleeding over into your personal life with a laptop.

I personally prefer the flexibility to catch up or take a work from home day, but it does interfere.

As for productivity the desktop for the same price will have more power and memory than the laptop and you still really need the same monitors which is assumed to be equal here, but if not could be a factor.

My old company had a policy of 1 19" monitor with your 14" laptop or two 19" monitors with a desktop.  Pretty stingy on the monitors to be sure, but they did have separate rules.

Title: Company PC refresh, laptop or desktop?

Body:
My company is getting PC refreshes with a choice of to have a desktop or laptop.  Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time?

I'm not asking what would be better for coding, but more for convenience and productivity.  I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.


问:
WCF service and security
Been building a WP7 app and now I need it to communicate to a WCF service I made to make changes to an SQL database. I am a little concerned about security as the user name and password for accessing the SQL database is in the App.Config. I have read in places that you can encrypt the user name and password in the config file.

As the username and password is never exposed to the clients connected to the WCF service, would security in my situation be much of a problem?

Just in case anyone suggests a method of security, I do not have SSL on my web server.

答:
Having a database username and password in App.Config is a risk if your server is compromised and someone is able to access the config file.

Yes, you can encrypt sections of App.Config: have a read of Encrypting Configuration Information Using Protected Configuration on MSDN.

However a simpler method, and the one which I believe is Microsoft's recommended practice, is to use Windows authentication on your database rather than SQL authentication. Grant the Windows account that your WCF service runs under the access it needs to do it's database reads and writes (and no more), and modify the connection string in your App.Config to Integrated Security=SSPI. No username and password in the config file any more.

Title: WCF service and security


答:
Edit:
I'm still staying with my original answer based upon the additional information you provided.  Original answer is below.

Even if the UI and Mgmt sites have completely different content and URLs, I don't see that you have anything to gain from having two authentication / authorization systems.  At a meta level, both sites are dealing with the same information and are using the same sets of authorization rules to determine if someone is allowed to do something or not.

You can still establish two hierarchies of permissions within the same authentication / authorization schema.  User accounts can have varying degrees of privilege and access based upon whatever tree structure you deem appropriate.  Ditto with the Maintenance accounts and the content they would be accessing.  Using the same, underlying layer for that security implementation just makes it easier on you to build and maintain.

If for some reason you were really, really, really worried about regular users even knowing there was a maintenance interface, then I would suggest creating two separate sites / URLs for access but still use the same underlying security layer.  It's trivial to create a second authentication view with its own URL.  That would meet the "perceived isolation" requirement without significantly increasing your workload.

Original Answer

I agree with Jarrod Roberson's answer, and this is intended to provide more detail behind that approach.

It sounds like you need at least three categories of users within your authentication / authorization scheme.

Regular user

As the name implies, this is for the regular users of your site without any special privileges.

Power user

These are essentially regular users but with enhanced privileges for handling maintenance type tasks.  P.SE moderators would be an example of power users.

Administrator

Are users with full rights to the system and can change anything that is exposed through the programming of the site.  Your developers may or may not be Administrators for your production site.

Developers raise an interesting question about what rights to assign.  In some cases, they need Administrator rights so they can fix the wrongs within the system (sorry for the pun).  But most of the time, you don't want them logged in as Administrators but rather as power users or regular users.

One way to solve this is through the use of multiple logins.  "JoeUser" can be their regular login when they aren't exercising their developer role while "JoeAdmin" would be their admin login.  The Admin login can trigger auditing / tracking / etc... while the regular login wouldn't.

Having two separate authentication systems buys you nothing but headache.  In addition to the reasons Jarrod laid out, here are a few more.

It doesn't prevent regular users from logging in as admins.  Regular users would have to know the admin's credentials before they could login as an admin.

It doesn't increase your security.  If anything, a dedicated, privileged authentication system makes it easier for attackers as they can focus on the one system and not worry about getting through as a lesser level user.  IE. they cracked your admin auth system so they know they'll get in as admins.

It makes authentication more annoying for your Administrators.  Because they have to go to a different site to authenticate as an Admin, they are more likely to skip using their regular user logins and just stay logged in as admins.  Not necessarily what you want.

So the answer is essentially this: Code up a single authentication / authorization layer.  Create multiple logins for whoever needs Admin rights.

Title: Authentication Systems - Separate for Management?

Body:
Edit: I admit to being unclear when I first wrote the question. I suppose I wasn't sure of the issue myself, the comments and answers provided up to now helped me focus on the issue, thank you to all involved. This edit is a total rewrite of the question.
End editorial comment

On a dynamic website we have two systems - content management, and user interface (trivial).

We are trying to decide if the two should have separate authentication systems (being two systems, this might increase security [or not - @GlenH7?]), each having its own hierarchy of permissions etc.

Or is it better to have a single system (it's the same database, after all... plus easier maintenance) and only play around with permissions (regular, jumbo, power, super nova, admin, Q)?


问:
What are the major differences between OpenGL ES 2.0 and 1.x?
I have to learn OpenGL and get a basic OpenGL app built, and I have a few questions:

What are specific things programmers need to know to program in these frameworks?

How does the shader language in 2.0 affect using these libraries?

Are there any compelling reasons to start with 1.x before 2.0?

答:
OpenGL ES 2.0 can be hard to understand coming from 1.1 especially if one was using the fixed pipeline as a black box.

In 2.0 you write programs in a C-like language called GLSL that are executed in the graphics card for each vertex or fragment.

For 2.0 you do absolutely need to know your vectors from your matrixes in order to do anything.

I'd recommend using the 1.1 manuals for reference if anything to get all the basic useful matrixes and then using 2.0 as fixed pipelines are just not coming back anytime soon.

GLSL is easy and once you have emulated the old fixed pipeline you can extend it to do things like cel-shading or reflections.


问:
If you could only have one programming related book on your bookshelf what would it be and why?
One per answer please. I'll add my favourite as an answer.</p>

答:
Gödel, Escher, Bach.

!

Body:
Gödel, Escher, Bach.

!


问:
Use verbs with functions, nouns with classes - what about interfaces?
Ok, I understand the normal conventions of using verbs with functions and nouns with classes. What about interfaces? Is there any methodology when coming up with interface names that may not be that obvious?

Just to make it clear, I'm not talking about whether to put an "I" in front of the name or if to use camelCase or PascalCase. I'm wondering about the method of figuring out a clear, semantic name for an interface.

EDIT
I'm obsessing on how to name an interface in the clearest way. I guess it just needs to be a noun too because when I think of naming classes I think of the closest "real" world object it can relate to. I suppose real world interfaces are things like a keyboard, mouse, remote control, ATM screen. Those are all nouns. Anyhow, any additional insight on a good way to formulate interface names would be appreciated.

答:
An interface describes behavior so the names should say so. I am not sure about a rule for this but you will know the name when you hear it.

Some examples:

```<code>Flyable      - Can Fly
Workable     - Can work
Negotiatable - Can negotiate.
</code>```

I think it is not proper to name interfaces with I and call Set with ISet because, as a developer, you should not be worried whether it is an interface or a class. I see this practice does not exist in Java now.

Body:
An interface describes behavior so the names should say so. I am not sure about a rule for this but you will know the name when you hear it.

Some examples:

Flyable      - Can Fly
Workable     - Can work
Negotiatable - Can negotiate.

I think it is not proper to name interfaces with I and call Set with ISet because, as a developer, you should not be worried whether it is an interface or a class. I see this practice does not exist in Java now.

ContentLicense: CC BY-SA 4.0


答:
The ratio is going to vary depending on the size of your methods.  The size of your methods will vary by programming style, language and problem domain.

If your methods are short then 3:1 is reasonable.  If your methods are long then 3:1 is on the high side.

So, to answer your question, it depends.  :-)

Title: What is a normal "functional lines of code" to "test lines of code" ratio?

Body:
I'm pretty new to TDD approach and my first experiments say that writing 1 line of functional code means writing about 2-3 lines of testing code. So, in case I'm going to write 1000 LOC, the whole codebase including tests is going to be something like ~3500 LOC.

Is this considered normal? What is the ratio in code you write?


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
There are two types of people I would hope that FizzBuzz would help me avoid.

Chancers with no knowledge of programming or no relevant knowledge of programming. Usually you can recognise these from the CV but not always and giving them a simple programming task is a good way of making it clear that they are not a programmer.

Java school grads, who have completed a programming course or degree but don't actually know how to program. These people can be harder to filter out because they can talk about theory but they just have no practical skill. Putting a simple problem in front of them and asking for a solution and an explanation of the solution is a pretty good way of seeing the difference between a Petra Java and a Paula Bean.

In either case, I don't really care about a perfect implementation. The test that you need to make with people applying for developer jobs is that they can program at all.

That said, I would probably not bother with that particular test for several reasons now. Firstly it's very well known and either of the above groups would be quick to try it. Secondly I would prefer to use Steve Yegge's phone screen questions to screen out non-programmers before we got as far as bringing them in. If someone recognised those questions it would imply they had read Steve Yegge's blog which would suggest to me they were in the top 1% of developers who take their profession seriously and certainly warrant an interview. Likewise if someone had some good rep here or on SO I would be inclined to interview them.

Title: FizzBuzz - really?


问:
Writing cross-platforms Types, Interfaces and Classes/Methods in C++
I'm looking for the best solution to write cross-platform software, aka code that I write and that I have to interface with different libraries and platforms each time.

What I consider the easiest part, correct me if I'm wrong, is the definition of new types, all I have to do is to write an hpp file with a list of typedefs, I can keep the same names for each new type across the different platforms so my codebase can be shared without any problem. typedefs also helps me to redefine a better scope for my types in my code.

I will probably end up having something like this:

```<code>include
|-windows
| |-types.hpp
|-linux
| |-types.hpp
|-mac
  |-types.hpp
</code>```

For the interfaces I'm thinking about the same solution used for the types, a series of hpp files, probably I will write all the interfaces only once since they rely on the types and all "cross-platform portability" is ensured by the work done on the types.

```<code>include
|
|-interfaces.hpp
|
|-windows
| |-types.hpp
|-linux
| |-types.hpp
|-mac
| |-types.hpp
</code>```

For classes and methods I do not have a real answer, I would like to avoid 2 things:

the explicit use of pointers

the use of templates

I want to avoid the use of the pointers because they can make the code less readable for someone and I want to avoid templates just because if I write them, I can't separate the interface from the definition.

What is the best option to hide the use of the pointers?

I would also like some words about macros and how to implement some OS-specifics calls and definitions.

答:
The easiest way to think about cross-platform programming is that you need a strategy for dealing with changes in the behaviour of the program's environment, across space (i.e. different hardware architectures and operating systems) and time (i.e. different versions of an operating system with new features and different bugs). There already is a pattern for implementing strategies.

You can imagine defining a polymorphic type with member functions that define the "logic" of what you're trying to do. These member functions call abstract member functions that are responsible for entertaining the underlying platform's needs. Clients call a factory method to get an instance of your class: the factory method chooses what concrete implementation to return based on the details of the platform.

This approach results in a public interface with no templates and (with the information I know about the problem) no explicit pointer use. Clients just call a factory method and then use the public interface on your virtual base class. It also completely hides all of the complexity you want to introduce regarding headers and their locations - your clients just include the headers for your virtual types.


问:
Abstraction Layer over ORM Generated Entities
I am learning LINQ to SQL (and planning to learn Entity Framework). Initially I used a abstraction layer to convert LINQ to SQL entities into a domain objects. Later I discovered the “Inheritance Mapping” option and removed the abstraction layer and  started to use ORM entities directly as domain objects.

After some time, I got a road block when I don’t use abstraction layer. Please read it here: https://stackoverflow.com/questions/11470037/get-all-associate-composite-objects-inside-an-object-in-abstract-way

Is it possible to achieve all tasks without using Abstraction layer over ORM?

What are the rationale to decide have/not have abstraction layer?

REFERENCE:

http://martinfowler.com/bliki/OrmHate.html

答:
Depends on the tasks and the ORM used. both NHibernate and Entity Framework are feature rich which makes it very likely they can. NH also has many hooks you can implement to change its behaviour

abstracttions always have costs (learning, dependency, ...) so unless the value they provide outperforms the costs they should be avoided. An ORM is already an abstraction which most of the time provides more value (when relational Database access is involved).


答:
There are variations based on different coding styles and languages. However, regardless of the language you use, the biggest variation is you.

Robert Martin once said:

“As the tests get more specific, the code gets more generic.”

That made me think. More specific tests mean more test code. More generic production code means less code, so test/code ratios should rise as the code evolves.

But wait, that's not good either. In some particular cases, for example when you define a certain algorithm, you may have only 6-10 lines of code containing a couple of "if"s, a while and maybe 2-3 recursions. I can tell you, that code will have probably more 100 lines of test code.

In a real project, something bigger than just a few algorithms, the test/code ratio should be somewhere between 1:1 and 2:1. If it gets above 2:1, it's a smell that you have tests that should be refactored or deleted (or maybe code that is hard to test). You should always invest the same amount of care and refactoring in your tests as in your production code.

Any way, the best answer to your question maybe is "Cyclomatic Complexity". The higher the cyclomatic complexity of your method, the exponentially more test you have to write for it to cover all the cases.


答:
This test very nicely covers several things I want to know about a programmer I might hire:

Can you even program at all?

Can you write a program from scratch (because not everyone can!!!)

Can you solve a problem without over-thinking it.

To elaborate on the last point, there are countless solutions to fizz-buzz. Do you go for readability? Speed? Brevity? Do you try to finish writing the program quickly? How a programmer attacks this simple problem is very telling. If a programmer can't pick a solution and see it through to the end, what does that tell you about how this person will perform on a real task?

Title: FizzBuzz - really?

Body:
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.


答:
The size of my test code is about half of what the 'actual' code is overall. Doing otherwise is indicative that your tests are too complex and/or your code is too hard to test and/or your code is too dense/complex.

Or you're simply testing too much, and wasting your time on diminishing returns.

Also see "when is unit testing inappropriate or unnecessary?"


答:
For software critical application, the usual ratio is one day of testing for each 10 functional LoC.

And this is not counting TDD which is not about test but about specification.


答:
You might consider storing images in a submodule. This would allow you to keep code and images in separate repos. </p>

<p>My company uses submodules for our shared libraries, and though at times a little clunky, it may be the solution you're looking for. </p>

Body:
You might consider storing images in a submodule. This would allow you to keep code and images in separate repos.

My company uses submodules for our shared libraries, and though at times a little clunky, it may be the solution you're looking for.


问:
What recommendations can you give in managing a team of remote software engineers?
I am a Web application developer who also is responsible for project managing some projects, I sometimes have to manage remote developers, who work for me under a contract basis. I feel that sometimes it is really difficult to manage. I am facing some strange situations. For example:

Once a developer didn't respond for two days while we had to deliver a project. (didn't attend calls or respond to emails )

Once a developer templated a CMS with static solution (this one had less expertise I think).

Once I asked a developer to complete search functionality, the next day he said done, but when I looked, it wasn't done. Upon asking I came to know that, he had done the search but not search result listing formatting :). (I guess he is unable to manage his time while working from home)

So does this mean that I don't have right people? Or there is a problem in project management that I need to cover? I understand that sometimes misunderstandings can happen, and therefore we need to communicate in writing using a tool like unfuddle or basecamp, but what we can do for instance in the above situations? The person who did has at least 2 years of experience as a developer.

So I actually want to know: where is the problem? I am a programmer and know that programmers understand these things, then what should I do in such cases?

答:
At first glance, the problems you call out have little to do with working remotely, and a lot to do with the interview process.

Interviewing contract resources and vendors is brutally difficult. So difficult, in fact, that for small projects that need to be contracted out it may be more efficient just to think of the first couple projects as part of the interview process, and only consider a vendor reliable after a few successful engagements reflect key skills.

Here's the core interview tasks that my team uses for new vendors:

Technical Skills: We spend an hour w/ watching new resources write code to a problem we give them at the begining of the hour (w/ screen sharing software). We expect developers to be able to write code, and to ask high quality clarifying questions to make sure that they understand the task they are assigned. We also expect outstanding communication skills: If you can't write code and talk about the code you're writing, you wont' be able to collaborate effectively.

Communication skills & work experience: Once we know that a candidate can write code and talk about what they're doing, we walk through their resume with them and talk about their previous experience: do they have real collaboration experience? What has guided their career choices so far: is the work we need done compatible with their professional goals?

At the end of the interview process, we're looking for a resource that people are going to fight over, someone you want to get on your project. If none of the interviewers is anxious to get the candidate on their team, there's not a good fit. This process is heavily inspired by Joel Spolsky's writing about how to find people who are smart and will get things done, and Brad Smart's book on topgrading.

Now as the problems you call out:

MIA developer: this can happen with virtual or in-person developers, and usually only if you've not screened carefully. If a vendor doesn't show up when they've commited to be available, its game over, whether their virtual or IRL.

CMS w/ static solution: when you give a project to someone who doesn't have the required experience, they'll fail wether they're in the office or not.

Work not finished: again, I've had loads of experience with developers not fininishing work, both in the office and virtually. Almost always, this is a result of insufficient technical screening before giving someone a project.

In my experience, which includes more than 15 years of working both in offices and on virtual teams, effective developers are usually productive, and waste of time developers are usually a waste of time. I'll do everything in my power to work with effective developers, and to support them with whatever mix of virtual and in-office work they preffer. And if I do have to work with waste-of-time developers, I'll assume that they'll destroy value and try to minimize their impact until I can roll them off the team, regardless of whether they're in the office or not.


答:
My answer to this question has evolved relatively recently. The existing answers cover what I would have said in the past. Actually, this is still covered by the top answer - the "appreciate the constructs in higher-level programming" point, but it's a special-case that I think is worth mentioning...

According to this Jeff Atwood blog post, which references a study, understanding assignment is a key issue in understanding programming. Learner programmers either understand that the notation just represents steps that the computer follows, and reasons by the steps, or else gets perpetually confused by misleading analogies to mathematical equations etc.

Well, if you understand the following from 6502 assembler...

```<code>LDA variable
CLC
ADC #1
STA variable
</code>```

That really is just the steps. Then when you learn to translate that to an assignment statement...

```<code>variable = variable + 1;
</code>```

You don't need an misleading analogy to a mathematical equation - you already have a correct mental model to map it to.

EDIT - of course if the explanation you get of LDA variable is basically ACCUMULATOR = variable, which is exactly what you get from some tutorials and references, you end up back where you started and it's no help at all.

I learned 6502 assembler as my second language, the first being Commodore Basic, and I hadn't really learned much of that at the time - partly because there was so little to learn, but also because assembler just seemed so much more interesting back then. Partly the times, partly because I was a 14 year old geek.

I don't recommend doing what I did, but I wonder if studying a few very simple examples in a very simple assembler language might be a worthwhile preliminary to learning higher-level languages.

OwnerDisplayName: Артём Царионов

Title: How does learning assembly aid in programming?

Body:
I have been programming in higher level languages (Python, C#, VBA, VB.NET) for around 10 years and I have completely zero understanding on what's going on, "under the hood."

I am wondering what are the benefits of learning assembly, and how will it aid me as a programmer? Can you please provide me with a resource that will show me exactly the connection between what I write in higher level code to what happens in assembly?

Body:
My answer to this question has evolved relatively recently. The existing answers cover what I would have said in the past. Actually, this is still covered by the top answer - the "appreciate the constructs in higher-level programming" point, but it's a special-case that I think is worth mentioning...

According to this Jeff Atwood blog post, which references a study, understanding assignment is a key issue in understanding programming. Learner programmers either understand that the notation just represents steps that the computer follows, and reasons by the steps, or else gets perpetually confused by misleading analogies to mathematical equations etc.

Well, if you understand the following from 6502 assembler...

LDA variable
CLC
ADC #1
STA variable

That really is just the steps. Then when you learn to translate that to an assignment statement...

variable = variable + 1;

You don't need an misleading analogy to a mathematical equation - you already have a correct mental model to map it to.

EDIT - of course if the explanation you get of LDA variable is basically ACCUMULATOR = variable, which is exactly what you get from some tutorials and references, you end up back where you started and it's no help at all.

I learned 6502 assembler as my second language, the first being Commodore Basic, and I hadn't really learned much of that at the time - partly because there was so little to learn, but also because assembler just seemed so much more interesting back then. Partly the times, partly because I was a 14 year old geek.

I don't recommend doing what I did, but I wonder if studying a few very simple examples in a very simple assembler language might be a worthwhile preliminary to learning higher-level languages.


问:
What came first, the compiler, or the source?
I'm curious about the birth of the compiler.  How did programming begin?  Did people first build hardware that recognized a certain set of commands, or did people define a language and then build hardware around it?  And on a related note, what was the first programming language?</p>

答:
The algorithms were sorted out on paper, then the alus were wired up physically/mechanically (moving wires).  to change the program you move the wires and run again.

Later the assembly language sorted out on paper, translated to machine code by hand, then using switches, etc to feed it into ram.  Or punch cards, etc.  Eventually you can make an assembler, then you can program in assembly not machine code, then you can make a compiler.  Eventually you can bootstrap that compiler.  And make new languages and new compilers, etc.

The first language was not a language, later the first language was assembly language.  for every processor the first language is assembly language (derived from the machine code).  The instruction set is designed first then the hardware to implement it then assembler, then compilers.


答:
The photos are original work, they need to be stored safely and reliably.

Options are storing revisions in a file name/folder or zipped tarballs with dates and times convention for each revision, a proper revision control or something in between. It is a fact that, beyond circumventing the first few laws of thermodynamics, as photos are changed and files added, the stored data will grow.

If you are prepared to discard old versions of the files to save disk space or otherwise reduce the size of the files you store, then GIT (and most other rev control tools) is not what you want.

If you want the certainty and control that a revision control tool provides, then you have to spend the money - Find the $100 and buy a 2 terabyte disk, I am sure your photographer would rather you do that than ask him to got an retake all the photos you just lost and cannot recover because you had a "whoops" moment at the keyboard.

As previously suggested, separate repo or sub modules will offer a nice solution of separating the data (photos) from the program source.

Whatever you do - make sure the photos are reliably backed up. GIT just happens to be wonderful for this task.


问:
How does learning assembly aid in programming?
I have been programming in higher level languages (Python, C#, VBA, VB.NET) for around 10 years and I have completely zero understanding on what's going on, "under the hood."

I am wondering what are the benefits of learning assembly, and how will it aid me as a programmer? Can you please provide me with a resource that will show me exactly the connection between what I write in higher level code to what happens in assembly?

答:
Writing in assembly would not give you magic increase of speed as due to amount of details (register allocation etc.) you will probably write the most trivial algorithm ever.

Additionally with modern (read - designed after 70-80's) processors assembly will not give you sufficient number of details to know what is going on (that is - on most processors). Modern PU (CPUs and GPUs) are quite complex as far as scheduling instructions go. Knowing basics of assembly (or pseudoassembly) will allow to understand computer architecture books/courses which would provide further knowledge (caches, out-of-order execution, MMU etc.). Usually you don't need to know complex ISA to understand them (MIPS 5 is quite popular IIRC).

Why understand processor? It might give you much more understanding what's going on. Let's say you write matrix multiplication in naive way:

```<code>for i from 0 to N
    for j from 0 to N
        for k from 0 to N
            A[i][j] += B[i][k] + C[k][j]
</code>```

It may be 'good enough' for your purpose (if it is 4x4 matrix it might be compiled to vector instructions anyway). However there are quite important programs when you compile massive arrays - how to optimize them? If you write the code in assembly you might have a few % of improvement (unless you would do as most people do - also in naive way, underutilizing registers, loading/storing to memory constantly and in effect having slower program then in HL language).

However you can reverse tho lines and magically gain performance (why? I leave it as 'homework') - IIRC depending on various factors for large matrices it can be even 10x.

```<code>for i from 0 to N
    for k from 0 to N
        for j from 0 to N
            A[i][j] += B[i][k] + C[k][j]
</code>```

That said - there are working on compilers being able to do it (graphite for gcc and Polly for anything using LLVM). They are even capable of transforming it into (sorry - I'm writing blocking from memory):

```<code>for i from 0 to N
    for K from 0 to N/n
        for J from 0 to N/n
            for kk from 0 to n
                for jj from 0 to n
                    k = K*n + kk
                    j = J*n + jj
                    A[i][j] += B[i][k] + C[k][j]
</code>```

To summarise - knowing basics of an assembly allows you to dig into various 'details' from processor design which would allow you to write faster programs. It might be good to know differences between RISC/CISC or VLIW/vector processor/SIMD/... architectures. However I would not start with x86 as they tend to be quite complicated (possibly ARM too) - knowing what is a register etc. is IMHO sufficient for start.

OwnerDisplayName: Артём Царионов

Body:
Writing in assembly would not give you magic increase of speed as due to amount of details (register allocation etc.) you will probably write the most trivial algorithm ever.

Additionally with modern (read - designed after 70-80's) processors assembly will not give you sufficient number of details to know what is going on (that is - on most processors). Modern PU (CPUs and GPUs) are quite complex as far as scheduling instructions go. Knowing basics of assembly (or pseudoassembly) will allow to understand computer architecture books/courses which would provide further knowledge (caches, out-of-order execution, MMU etc.). Usually you don't need to know complex ISA to understand them (MIPS 5 is quite popular IIRC).

Why understand processor? It might give you much more understanding what's going on. Let's say you write matrix multiplication in naive way:

for i from 0 to N
    for j from 0 to N
        for k from 0 to N
            A[i][j] += B[i][k] + C[k][j]

It may be 'good enough' for your purpose (if it is 4x4 matrix it might be compiled to vector instructions anyway). However there are quite important programs when you compile massive arrays - how to optimize them? If you write the code in assembly you might have a few % of improvement (unless you would do as most people do - also in naive way, underutilizing registers, loading/storing to memory constantly and in effect having slower program then in HL language).

However you can reverse tho lines and magically gain performance (why? I leave it as 'homework') - IIRC depending on various factors for large matrices it can be even 10x.

for i from 0 to N
    for k from 0 to N
        for j from 0 to N
            A[i][j] += B[i][k] + C[k][j]

That said - there are working on compilers being able to do it (graphite for gcc and Polly for anything using LLVM). They are even capable of transforming it into (sorry - I'm writing blocking from memory):

for i from 0 to N
    for K from 0 to N/n
        for J from 0 to N/n
            for kk from 0 to n
                for jj from 0 to n
                    k = K*n + kk
                    j = J*n + jj
                    A[i][j] += B[i][k] + C[k][j]

To summarise - knowing basics of an assembly allows you to dig into various 'details' from processor design which would allow you to write faster programs. It might be good to know differences between RISC/CISC or VLIW/vector processor/SIMD/... architectures. However I would not start with x86 as they tend to be quite complicated (possibly ARM too) - knowing what is a register etc. is IMHO sufficient for start.


答:
How long have you been programming, and what size of applications?

This question is not the "who do you think you are?" kind, but points to the fundamental problem of all frameworks. Be it a simple stream parser module, a GUI manager or "the overall platform independent frame", they must restrict direct coding, and as a replacement, provide a service that is equivalent or better for "any" task that might appear. You must have seen many problems before starting any framework.

I have spent 20 years in programming, I have searched for the core concepts of this "ultimate framework" all the time, and realized that I have always been going "in the wrong direction on a highway". I think I have some answers to consider, the ones that apply here are:

the question is wrong. Platform independence means language independence too: there are platforms where C++ is not available or not the best answer;

so don't waste your time on implementing language tricks for C++, they somehow limit the services of all platforms. Get used to the idea that you will generate those header files from an external (therefore truly platform independent, like JSON) type declaration ;-)

Following the comments and downvotes, I decided to add the following:

When mentioning the years, I wanted to express the importance of learning from mistakes. You might think that your first ideas are perfect, and the codes bug free. My codes always have bugs, although I do my best to avoid them - and my concepts were formed during creating different frameworks under "IRL" applications. They were quite weak for the first times, and I had to throw several versions and learn a lot from those experiences. This is only a warning, and a reason why my findings should be considered (and not accepted just because of that).

I did not want to do any "self marketing" here, I thought that anyone interested enough to judge my words would check my profile as well. If not: here you can see what I call platform independent programming, and for the impatient, a short summary might explain why I have spent almost 20 years on it.

Cheerio!

Title: Writing cross-platforms Types, Interfaces and Classes/Methods in C++

Body:
I'm looking for the best solution to write cross-platform software, aka code that I write and that I have to interface with different libraries and platforms each time.

What I consider the easiest part, correct me if I'm wrong, is the definition of new types, all I have to do is to write an hpp file with a list of typedefs, I can keep the same names for each new type across the different platforms so my codebase can be shared without any problem. typedefs also helps me to redefine a better scope for my types in my code.

I will probably end up having something like this:

```<code>include
|-windows
| |-types.hpp
|-linux
| |-types.hpp
|-mac
  |-types.hpp
</code>```

For the interfaces I'm thinking about the same solution used for the types, a series of hpp files, probably I will write all the interfaces only once since they rely on the types and all "cross-platform portability" is ensured by the work done on the types.

```<code>include
|
|-interfaces.hpp
|
|-windows
| |-types.hpp
|-linux
| |-types.hpp
|-mac
| |-types.hpp
</code>```

For classes and methods I do not have a real answer, I would like to avoid 2 things:

the explicit use of pointers

the use of templates

I want to avoid the use of the pointers because they can make the code less readable for someone and I want to avoid templates just because if I write them, I can't separate the interface from the definition.

What is the best option to hide the use of the pointers?

I would also like some words about macros and how to implement some OS-specifics calls and definitions.


问:
Should I create specific classes for JSON Objects or only use the container(Array/Dictionary) for accessing Data?
I'm using Foursquare to get a List of Restaurants nearby inside an iOS app. The Result is stored in an Array which consists of Dictionaries and regarding how deep the Data is, each Dictionary contains also an Array with Dictionaries and so on. The Result should be shown inside a UITableView. Should I create a Class that represents a Restaurant and then create an instance for every Restaurant which I put in an Array and use this as the Data Source for my UITableView or should I use the complete Array I got the first Time.
I think, using an Array with a dedicated Restaurant class would make the handling much easier but maybe there are reasons to not do it this way? Performance maybe?</p>

答:
I have not been in iOS programming for a long time, so double check my answer.

My rule of thumb: create a class when you want to encapsulate a certain functionality. If you want an "intelligent" Restaurant object (some business logic, validation, calculated fields), you should create that class. To follow Apple conventions, you should then implement NSCoding protocol that transfers the class fields to and from Dictionaries, and use a JSON serializer that can transform the standard objects in the JSON file to Restaurant instances using your code. This sounds a "strong" solution, but has its flaws.

iOS is screen-oriented (business logic in the view controllers), and you would spend a lot of time writing that NSCoding functions only to use Restaurants instead of Dictionaries behind the UITableViewDataSource callback functions (which you will have to write the same way in either case).

So in a simple "proof of concept" case, I would recommend not playing a lot with NSCoding, Restaurant and other stuff, but using the NSArray of Dictionaries coming from the JSON. Primarily not for runtime performance, but the amount of programming time, code complexity - and the possible errors. You can switch to using dedicated classes if you really have to: if using dictionaries would make your code uncomfortable.


答:
Focus on creating options for yourself. </p>

<p>If your project and budget permit, hire more than one programmer.  This should create a healthy level of competition, which is always good.  This should also ensure that knowledge is shared amongst the team and will increase redundancy.  </p>

Title: What recommendations can you give in managing a team of remote software engineers?

Body:
I am a Web application developer who also is responsible for project managing some projects, I sometimes have to manage remote developers, who work for me under a contract basis. I feel that sometimes it is really difficult to manage. I am facing some strange situations. For example:

Once a developer didn't respond for two days while we had to deliver a project. (didn't attend calls or respond to emails )

Once a developer templated a CMS with static solution (this one had less expertise I think).

Once I asked a developer to complete search functionality, the next day he said done, but when I looked, it wasn't done. Upon asking I came to know that, he had done the search but not search result listing formatting :). (I guess he is unable to manage his time while working from home)

So does this mean that I don't have right people? Or there is a problem in project management that I need to cover? I understand that sometimes misunderstandings can happen, and therefore we need to communicate in writing using a tool like unfuddle or basecamp, but what we can do for instance in the above situations? The person who did has at least 2 years of experience as a developer.

So I actually want to know: where is the problem? I am a programmer and know that programmers understand these things, then what should I do in such cases?

Body:
Focus on creating options for yourself.

If your project and budget permit, hire more than one programmer.  This should create a healthy level of competition, which is always good.  This should also ensure that knowledge is shared amongst the team and will increase redundancy.


问:
Multi-threaded application design
I'm currently planning a Windows service. It will be a multi-threaded application which will continuously check for database records and process them. My first thoughts were to set a number of max available threads and create new thread for each process. This works OK but since I'm creating a new thread for every new process I fear that its overhead will multiply if there are lots of records to process. My question is, is this a good design or would you recommend any other solutions?

Here's what the application will do basically:

Check for available number of threads

If there are available threads check the database for records to process.

If there are records to process select top 100 of them

Create a new process

Call a web service for each record and update the record according to web service call result (This call+update usually take around 500ms so process will be live for about 50 seconds)

Continue to step 1

This is currently what I am doing:

```<code>timer1.Tick += Tick();

private void Tick()
{
    //do some text logging
    //do some TextBox updating
}

int MaxThreads = 10

while(true)
{
    if(ThreadCount < MaxThreads)
    {
        new Thread(() => Process()).Start();
        ThreadCount++;
    }
    else
    {
        Thread.Sleep(10000);
    }
}

private void Process()
{
    //call ws
    //update records

    ThreadCount--;
}
</code>```

答:
You should have a look at the thread pool pattern in Wikipedia, I think this is what you are looking for. The trick is to create n threads once when your service starts, avoiding the overhead of thread creation (see this question on SO) during runtime.

As for your workflow, you may want to consider switching the first two steps:

First check if there are records to process, and if there are, see if your thread pool has a free thread. This is an optimisation problem, you want to reach the decision no processing (because there is no data, or no resources for it) with as little effort as possible. If you reach this decision more often because there is no data to process, check for this first.

Some will argue that this is premature optimisation, but I personally prefer to err a little more on the premature side.

Title: Multi-threaded application design


答: .Net has a built in thread pool that you can use to do work. But even better check the Task Parallel Library in .Net 4. This makes the most common scenarios for multithreading very simple to implement. Like using Parallel.For to process in parallel. Using Task to start a work in background and waiting for all of them to finish is another approach.</p>

Title: Multi-threaded application design

Body:
I'm currently planning a Windows service. It will be a multi-threaded application which will continuously check for database records and process them. My first thoughts were to set a number of max available threads and create new thread for each process. This works OK but since I'm creating a new thread for every new process I fear that its overhead will multiply if there are lots of records to process. My question is, is this a good design or would you recommend any other solutions?

Here's what the application will do basically:

Check for available number of threads

If there are available threads check the database for records to process.

If there are records to process select top 100 of them

Create a new process

Call a web service for each record and update the record according to web service call result (This call+update usually take around 500ms so process will be live for about 50 seconds)

Continue to step 1

This is currently what I am doing:

```<code>timer1.Tick += Tick();

private void Tick()
{
    //do some text logging
    //do some TextBox updating
}

int MaxThreads = 10

while(true)
{
    if(ThreadCount < MaxThreads)
    {
        new Thread(() => Process()).Start();
        ThreadCount++;
    }
    else
    {
        Thread.Sleep(10000);
    }
}

private void Process()
{
    //call ws
    //update records

    ThreadCount--;
}
</code>```


答:
The best example of coding for multiple platforms that I know of is the "Apache Portable Runtime"

This is an excellent C library that was initially written to move all platform OS dependent code out if the main fork of the Apache web server code.

It may or may not be suitable for your use (either because of licensing restrictions or you really need C++ code). Either way it is an excellent example of how to go about insulating your code form platform dependencies, and, there are some great examples on dealing with platform weirdness.


答: I would go with specific classes - it will be much easier to write unit tests and maintain code even if you lose some performance. It is not a place where you should prefer performance over clarity.</p>

Title: Should I create specific classes for JSON Objects or only use the container(Array/Dictionary) for accessing Data?

Body:
I'm using Foursquare to get a List of Restaurants nearby inside an iOS app. The Result is stored in an Array which consists of Dictionaries and regarding how deep the Data is, each Dictionary contains also an Array with Dictionaries and so on. The Result should be shown inside a UITableView. Should I create a Class that represents a Restaurant and then create an instance for every Restaurant which I put in an Array and use this as the Data Source for my UITableView or should I use the complete Array I got the first Time.
I think, using an Array with a dedicated Restaurant class would make the handling much easier but maybe there are reasons to not do it this way? Performance maybe?</p>


问:
PHP function __autoload($class_name) how to Load two class path directories
I am using following function to autoload classes, it works fine if i am using only one directory called 'classes' however when i try to use Smarty lib also it fails and give me the error

```<code>Fatal error: Class 'Database' not found in /home/...
</code>```

for ex:

```<code>require_once(DOC_ROOT."/libs/Smarty.class.php");
function __autoload($class_name) {
    require_once( CLASS_LIB."/".$class_name . '.class.php');
}
$db = new Database();
$session=new Session();
$smarty = new Smarty();
</code>```

but if i do this it give me the error unable to load the smarty class..

```<code>function __autoload($class_name) {
    require_once( CLASS_LIB."/".$class_name . '.class.php');
    require_once(DOC_ROOT."/libs/Smarty.class.php");
}

$db = new Database();
$session=new Session();
$smarty = new Smarty();

Warning: require_once(/home/.../classes/Smarty_Internal_TemplateCompilerBase.class.php) [function.require-once]: failed to open stream: No such file or directory in /home/.../includes/init.php
</code>```

Any idea what i am i doing wrong here ? i need to be able to load classes directory automatically but needs to make sure i dont loose smarty path too..

答:
I solve the problem spl_autoload_register function two times.

below is the code for reference.

```<code>spl_autoload_register('load_api');
spl_autoload_register('load_lib');

function load_api($class){
    if(!file_exists(CLASS_LIB."/".$class. '.class.php') )
        return false;
    require_once( CLASS_LIB."/".$class. '.class.php');
    return true;
}
function load_lib($class){
    if( !file_exists(DOC_ROOT."/libs/Smarty.class.php") )
        return false;
    require_once(DOC_ROOT."/libs/Smarty.class.php");
    return true;
}
</code>```

Body:
I solve the problem spl_autoload_register function two times.

below is the code for reference.

spl_autoload_register('load_api');
spl_autoload_register('load_lib');

function load_api($class){
    if(!file_exists(CLASS_LIB."/".$class. '.class.php') )
        return false;
    require_once( CLASS_LIB."/".$class. '.class.php');
    return true;
}
function load_lib($class){
    if( !file_exists(DOC_ROOT."/libs/Smarty.class.php") )
        return false;
    require_once(DOC_ROOT."/libs/Smarty.class.php");
    return true;
}


问:
Is 37Signals Basecamp a hype?
What's so unique about it? Heard great things about it, used it, found that beside the Google Apps Integration there's nothing really special about it. Maybe I just don't get it?

So, what's your reason to use basecamp?

答:
I don't think there is anything wrong with it, but there are a lot of other ways to address the same issues.  I also do not understand the love/loyalty it seems to generate with some users.

Personally, it has never fit what I was working on very well, so I have never had a place to use it long-term.

Title: Is 37Signals Basecamp a hype?


问:
Coding in 'core php' and separating logic from presentation
What are the various ways of acheiving this ? Can someone please guide me?

I have to code a website for a friend (designer). The friend wants me to use core php and not any framework like codeigniter (something I really like and am comfortable with !) .

I had a look at a couple of roll your own MVC frameworks guides, but am not sure if this is the ideal approach.  Since any solution I might come up with may have various bugs/security issues.
My goal is to use plain php , without the help of thirdparty frameworks, to code a site , where the logic is separate from the view .

Thanks

答:
The easy method is to put all your html in a separate view folder, and just do a

```<code>include $site_path . 'views/' . $myfilename;
</code>```

at the end of each code file.

How robust of a structure you set up for yourself really depends on the complexity of the project.

Body:
The easy method is to put all your html in a separate view folder, and just do a

include $site_path . 'views/' . $myfilename;

at the end of each code file.

How robust of a structure you set up for yourself really depends on the complexity of the project.


问:
How to ease the maintenance of event driven code?
When using an event based component I often feel some pain at maintenance phase.

Since the executed code is all split around it can be quite hard to figure what will be all the code part that will be involved at runtime.

This can lead to subtle and hard to debug problems when someone adds some new event handlers.

Edit from comments:
Even with some good practices on-board, like having an application wide event bus and handlers delegating business to other part of the app, there is a moment when the code starts to become hard to read because there is a lot of registered handlers from many different places (especially true when there is a bus).

Then sequence diagram starts to look over complex, time spend to figure out what is happening is increasing and debugging session becomes messy (breakpoint on the handlers manager while iterating on handlers, especially joyful with async handler and some filtering on top of it).

//////////////

Example

I have a service that is retrieving some data on the server. On the client we have a basic component that is calling this service using a callback. To provide extension point to the users of the component and to avoid coupling between different components, we are firing some events: one before the query is sent, one when the answer is coming back and another one in case of a failure.
We have a basic set of handlers that are pre-registered which provide the default behavior of the component.

Now users of the component (and we are user of the component too) can add some handlers to perform some change on the behavior (modify the query, logs, data analysis, data filtering, data massaging, UI fancy animation, chain multiple sequential queries, whatever).
So some handlers must be executed before/after some others and they are registered from a lots of different entry point in the application.

After a while, it can happens that a dozen or more handlers are registered, and working with that can be tedious and hazardous.

This design emerged because using inheritance was starting to be a complete mess. The event system is used at a kind of composition where you don't know yet what will be your composites.

End of example

//////////////

So I'm wondering how other people are tackling this kind of code. Both when writing and reading it.

Do you have any methods or tools that let you write and maintain such code without to much pain ?

答:
It sounds like you are looking for State Machines & Event Driven Activities.

However, you might also want to look at State Machine Markup Workflow Sample.

Here you are a short overview of state machine implementation. A state machine workflow consists of states. Each state is composed of one or more event handlers. Each event handler must contain a delay or an IEventActivity as the first activity. Each event handler can also contain a SetStateActivity activity that is used to transition from one state to another.

Each state machine workflow has two properties: InitialStateName and CompletedStateName. When an instance of the state machine workflow is created, it is put into the InitialStateName property. When the state machine reaches the CompletedStateName property, it finishes execution.


答: I think proper logging can help quite a big. Make sure that every event thrown/handled is logged somewhere (you can used logging frameworks for this). When you're debugging, you can consult the logs to see the exact order of execution of your code when the bug occurred. Often this will really help narrow down cause of the problem.

Title: How to ease the maintenance of event driven code?

Body:
When using an event based component I often feel some pain at maintenance phase.

Since the executed code is all split around it can be quite hard to figure what will be all the code part that will be involved at runtime.

This can lead to subtle and hard to debug problems when someone adds some new event handlers.

Edit from comments:
Even with some good practices on-board, like having an application wide event bus and handlers delegating business to other part of the app, there is a moment when the code starts to become hard to read because there is a lot of registered handlers from many different places (especially true when there is a bus).

Then sequence diagram starts to look over complex, time spend to figure out what is happening is increasing and debugging session becomes messy (breakpoint on the handlers manager while iterating on handlers, especially joyful with async handler and some filtering on top of it).

//////////////

Example

I have a service that is retrieving some data on the server. On the client we have a basic component that is calling this service using a callback. To provide extension point to the users of the component and to avoid coupling between different components, we are firing some events: one before the query is sent, one when the answer is coming back and another one in case of a failure.
We have a basic set of handlers that are pre-registered which provide the default behavior of the component.

Now users of the component (and we are user of the component too) can add some handlers to perform some change on the behavior (modify the query, logs, data analysis, data filtering, data massaging, UI fancy animation, chain multiple sequential queries, whatever).
So some handlers must be executed before/after some others and they are registered from a lots of different entry point in the application.

After a while, it can happens that a dozen or more handlers are registered, and working with that can be tedious and hazardous.

This design emerged because using inheritance was starting to be a complete mess. The event system is used at a kind of composition where you don't know yet what will be your composites.

End of example

//////////////

So I'm wondering how other people are tackling this kind of code. Both when writing and reading it.

Do you have any methods or tools that let you write and maintain such code without to much pain ?


答:
Event driven code is not the real problem. I fact I have no problem following logic in even driven code, where call-back are explicitly defined or in-line call-backs are used. For example generator style callbacks in Tornado are very much easy to follow. </p>

<p>What is real hard to debug are dynamically generated function calls. The (anti?)pattern which I would call the Call-back Factory from Hell. However, this kind of function factories are equally hard to debug in traditional flow. </p>

Body:
Event driven code is not the real problem. I fact I have no problem following logic in even driven code, where call-back are explicitly defined or in-line call-backs are used. For example generator style callbacks in Tornado are very much easy to follow.

What is real hard to debug are dynamically generated function calls. The (anti?)pattern which I would call the Call-back Factory from Hell. However, this kind of function factories are equally hard to debug in traditional flow.


答:
I can understand you might want to avoid the use of some kind of 3rd party framework for continuity and/or dependency reasons, but that still leaves you with design principles to follow. In the end I would advise to your friend that it might be very beneficial for him to consider a framework which is well supported and which you are able to work with. It will likely cut back development time and catch many security holes you never even heard of.

Failing that, my guess is that you need to make a good overall design before you start coding to make sure you have at least a good overview of how you want to set up the relationships between the namespaces and the classes in those namespaces. (not necessarily in UML, it could just be a text document) Although it's almost overused in this regard, MVC is a very good pattern for separating core logic from presentation and input handling (including the security side of input handling, like SQL injection and the like).

As in any coding, security is mostly by design followed up by good coding practices.
Make sure you have a good idea what the site should, and more importantly, should not be capable of so you can set constraints on what the system is capable of and what the users of the site are allowed to do.

BTW, does no frameworks also mean that you can't make use of templating engines like smarty and the like? They can help you do a lot of stuff for you and improve your security for you.

Title: Coding in 'core php' and separating logic from presentation

Body:
What are the various ways of acheiving this ? Can someone please guide me?

I have to code a website for a friend (designer). The friend wants me to use core php and not any framework like codeigniter (something I really like and am comfortable with !) .

I had a look at a couple of roll your own MVC frameworks guides, but am not sure if this is the ideal approach.  Since any solution I might come up with may have various bugs/security issues.
My goal is to use plain php , without the help of thirdparty frameworks, to code a site , where the logic is separate from the view .

Thanks


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答:
What should be in a coding standard?   As little as possible.  Less rather more.  And with justification, please.

Not because I'm some cowboy coder who wants no process, but because I've seen heavy coding specs with no logic behind it beyond (presumably) "I found this on the 'Net somewhere back in '95" that just end up becoming a bureaucratic nightmare to work with.

Some people honestly seem to believe that by cranking up the standards they will see a corresponding increase in code "quality" and perhaps by that measure they will.  In the meantime they'll ignore architecture, performance, common sense and a bunch other things that end up mattering more than the number of lines in a file.

Title: What should be in a coding standard?


问:
What is the most basic and simple platform for collaborative development (PHP project)?
I need to work with 4-5 programmers on a fairly average PHP application using codeigniter. We're in 5 different locations in one city, and all of the programmers are all not too well educated and I'm assuming that most of them have never used any version control system.

Can you recommend some very very easy-to-get-into platform for collaborating on a project like this? I'm talking about something that is only a tad more sophisticated than a shared dropbox folder.

答:
You already know the answer

Version control was designed to solve this exact problem.  If your developers are unwilling to learn to use this standard development practice, you may need to reconsider your developers.  What kind of software are they going to churn out if they're showing an aversion to standard accepted practices, as well as an aversion to learning new things?

I would suggest having them read Pro Git and setting up a private git repository for your team.


问:
Designing a library that is easy to use: composition or inheritance
I have designed a small library for work that consists of a few exposed classes. These can basically be thought of as a server class and client class. But now that I am writing all the test cases and examples, I am questioning myself on whether the classes should be used in a class or inherited.

I know about the composition over inheritance theology but at the same time, the OOP basics pop into my head: has-a and is-a relationships.

My main question is which makes more sense and which would make it easier for the programmers that use my library?

I have already ready numerous topics on SO and Programmers regarding this topic, none really target my question though:

Where does this concept of "favor composition over inheritance" come from?

Why should I prefer composition over inheritance?

Composition vs. Inheritance

答:
In the first place, any class you do write should be inheritable/extendable.  C# seems to seal all its system classes and so causes me no end of trouble.  Inheritence is tricky, particularly when the superclass programmer doesn't know what the subclass programmer will need and the subclasser can't modify the superclass.  (And in some cases cann't even look at the superclass's code.)  But inheritance can give your end users a lot of power for very little effort on their part.

But otherwise, I'd go with composition.  I frequently start with a base class, extend it in all directions, then realize the base class should be an interface.  If it's all in my code, this is no problem, but people using your library are going to be stuck with your choice.  In Java I've ended up with two classes that look identical as far as my needs are concerned.  If I could make each of them implement my own simple interface (by adding "extends myInterface"--they've both already got the methods) I'd be all set, but I have to treat them as distinct, unrelated classes.

The best idea might be to provide good interfaces and default implementations so the end users can do whatever they want.  I guess my point is that your library's users should be the ones to make the composition vs. inheritance decision; your job is to give them the option.