问:
Effectiveness of FizzBuzz and Beyond
As part of the interview process we initially ask the candidates to do 'FizzBuzz' nowadays the percentage of candidates that can correctly answer FizzBuzz has increased dramatically - this may be due to it's popularity on the web.

About a year ago, as a second question we began asking a question very similar to the original FizzBuzz. The question was designed to be as simple as the original FizzBuzz, and to also assess a particular ability of the candidate, specifically the ability to order and prioritize in a meaningful and logical manner a set of "business rules" that have been provided in some arbitrary order. The wording of the question initially seems slightly ambiguous, which may make it difficult for non-native English speakers, but if thought through can be correctly resolved - Also it gives the candidate the opportunity to ask questions for clarification, which is always a good thing.

We find this a very important skill to have as a developer, as software development is typically based on functional requirements that are derived in no particular order over time, that may place constraints and conditions upon other areas of the software without explicitly indicating and it is the job of the astute developer to at the very least investigate potential issues and conflicts with regards to the implementation.

What we found was that a little over 65% of the candidates (sample size of 38) that passed FizzBuzz completely failed FizzBuzz v2.0 Normally these candidates would be detected later on in the process, but it seems to be a nice way to detect them early on.

My question is not about whether or not FizzBuzz is outdated, but rather what factors could be contributing to such a high number of candidates failing the FizzBuzz v2 question.

Is the question too ambiguous?

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

Question:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list will do one of the following:

Print only Fizz if the string contains the letter A

Print only Buzz if the string contains the letter B

Print only BuzzBuzz if the string contains both A and B

Print only FizzFizz if the string does not contain both A and B

Print only FizzBuzz if the string contains only one A and only one B

Some typical questions asked by candidates are:

Should it be case sensitive?

Does "contains A and B" mean A should come before B

What should be printed if none of the points are met?

What should happen if more than one condition can be met?

We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.

答:
Perhaps the easiest way to avoid ambiguity is to show some examples:

"A"      returns "Fizz"
"aAbA"   returns "Fizz"
"B"      returns "Buzz"
"aBbB"   returns "Buzz"
"AB"     returns "FizzBuzz"
"ABaabb" returns "BuzzBuzz"
""       returns "FizzFizz"
"ab"     returns "FizzFizz"

Title: Effectiveness of FizzBuzz and Beyond


问:
Simplest token-system for authenticating and authorizating
I want to make Python script that will accept input from Vim and send it to my web-site. So basically I want to make Vim my text-editor for blog articles.

Of course, I need to authenticate and authorizate. I wanted to simply ask username and password. My college asked me why not to take login data from file. I answered that I don't want to save password in plain-text. He told me to use tokens!

So how to do it? I understand that I need to generate random token for user and knowing it will allow anyone to login. It should be really strong and random so nobody can guess it. Is there something else? Will it be safe to save it in text file?

I would like to hear how would you implement it in the simplest possible yet secure way. Some links to literature would be good too!

答:
Although you still need a way to authenticate your user the first time (against a hashed password) you can then set a secure cookie that will prove your user is the same one still.

To do this securely, you need a server-side secret, and cookie values that have the time of creation, the username, and that secret hashed together, so that when your user returns for the next HTTP connection you can a) retrieve the username, and b) verify the cookie is still valid and secure.

This is what the mod_auth_tkt Apache module implements, as well as the Pyramid AuthTktAuthenticationPolicy class and the plone.app.session package.

You could take a look through the source code of the latter two to see what they do to create and verify these cookies:

plone.app.session code; the tktauth module does most of the work here.

AuthTktAuthenticationPolicy code; I linked directly to the AuthTktCookieHelper class that does the heavy lifting for the cookie; I explained some of the fields the policy takes before:

https://stackoverflow.com/questions/12232364/pyramid-security-questions-double-cookies-insecure-cookies-expiration/12234593#12234593

https://stackoverflow.com/questions/12765349/pyramid-authtktauthenticationpolicy-secret-parameter

OwnerDisplayName: daGrevis

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Martijn Pieters


问:
Were there major changes in testing practices in ASP .NET between 3.5 and 4.5?
Obviously, testing methods are language-independent. An integration test stays an integration test no matter what the technology.

But platforms implement some kinds of testing support. And the details vary between implementations, so a programmer has to learn how to use the tools of their framework. And platforms evolve, so best practices in one version may become obsolete or at least inefficient in the next version. See for example this StackOverflow question about unit tests for which at least the first three answers seem to be valid: One describing the correct solution for the current version, one describing the solution which used to be best before the .NET framework included an ExpectedException attribute, and one describing a generic solution which is tool-independent.

My question is: were there any major testing-related changes between the .NET framework versions 3.5 and 4.5? Something as disruptive to testing as introducing generics was to programming in general, or introducing the Membership framework was to authentication? Or were there only small enhancing changes?

I am asking this because I wonder whether learning materials written for 3.5 are still reasonably valid today.

答:
I would say 3.5 testing information is still reasonably valid. Microsoft has added some enhancements, but I wouldn't call them disruptive or assert that the paradigm has shifted.

One change is code contracts, though I don't think they affect unit testing so much as provide an additional/improved way to validate parameters, which may change the way code is tested.

Most of the changes/improvements are not with the framework but more with the IDE -- Visual Studio 2012 introduces some new tools and features, including support for third-party frameworks, test management, as well as a new isolation framework called Fakes.

Fakes is a great addition (if you have the 2012 Ultimate version), but arguably not much different than third-party frameworks that were available previously, most notably Typemock Isolator.

ContentLicense: CC BY-SA 4.0


问:
what are the main differences between a web server and application server?
I am new to web development and just started exploring the things. I read about how web page is processed and sent to client by a web server but I got confused with application server. what is the difference between them ? why app. server is needed ? and few examples of both of them .</p>

答:
Technically, they mean the same thing.  In colloquial use, however, a "web server" generally means a server that produces web pages that are meant to be consumed by people with web browsers.

An "application server," on the other hand, uses HTTP as a transport layer for one program to communicate with another, generally using data exchange formats such as JSON or XML that aren't meant to be rendered as a document.

Of course, if the same server provides both HTML pages and an API to programatically access the underlying data, the distinction can get a bit blurry...


问:
C# Interview Preparation - References?
This is a specific question relating to C#. However, it can be extrapolated to other languages too.

While one is preparing for an interview of a C# Developer (ASP.NET or WinForms or ), what would be the typical reference material that one should look at?

Are there any good books/interview question collections that one should look at so that they can be better prepared?

This is just to know the different scenarios. For example, I might be writing SQL Stored Procedures and Queries, but I might stumble when asked suddenly

Given an Employee Table with the following column(s).

EmployeeId, EmployeeName, ManagerId

Write a SQL Query which will get me the Name of Employee and Manager Name?

NOTE: I am not asking for a Question Bank so that I can learn by rote what the questions are and reproduce them (which, obviously will NOT work!)

答:
Take a look at Scott Hanselman's blog post on "What Great .NET Developers Ought to Know".

From there you should be able to figure out how to search and study based on the concepts he mentions there.

ContentLicense: CC BY-SA 2.5

Title: C# Interview Preparation - References?


问:
Why aren't young programmers interested in mainframes?
A key issue with mainframes is that the cohort of supporting programmers is dwindling. While normally this wouldn't be a problem in that a falling supply of programmers would be offset by an increasing amount of salary those causing a rising supply of programmers via the law of supply and demand, I'm not sure this is really happening for mainframes.

While they still form critical infrastructure for many businesses, the simple fact is there isn't an adequate number of young programmers coming up along to keep the support population populated.

Why is this? What makes mainframes unattractive to young programmers?

答:
That answer is that there's no future in it. I have twenty-two years of experience as a mainframe programmer and I've been out of work for five years. I'm going back to school to get my Bachelor degree in web development. Why would anyone in their right mind want to be a mainframe COBOL programmer?

Ken


答:
Look, I'm 42 and I'm not interested in mainframes. Well, let's qualify that. I'm interested in the history of computing. I've studied mainframe architectures to some extent, and understand how for instance IBM mainframes influenced microprocessor architectures such as the Motorola 68000 or 80386. In the 1960's mainframes already blazed at speeds exceeding 30 Mhz, and sported advanced multi-tasking operating systems with virtual memories. To people used to those environments, early microprocessors were disappointing in many ways, and it took quite a while for microprocessor based architectures to catch up with similar capabilities and performance.

But catch up those architectures did, and mainframes stopped being "hip" long ago. It happened when hackers could get minicomputers on their benches and soon after that workstations running Unix.

Mainframes have been alien to young programmers since early 1980-something. That might have been an excellent time for mainframe companies to ask themselves your very question.

Today the answer is cross-generationally recursive: young programmers are not interested in mainframes because even if they have parents or teachers interested in computing, those parents and teachers (40+ geezers like me) were already not interested in doing anything with mainframes a quarter century ago.

Anyway, today, a cell phone can handle the tasks that mainframes were used for 30 years ago! Farms of inexpensive server boxes are the new mainframe.  So in a way there are new mainframe programmers today, only their specialty is racking together networked machines to build clouds. In a stretch, we could say that Mark Zuckerberg and his gang were doing a new kind of mainframe programming when they produced Facebook, in the sense that it's not just a little application that just runs on a simple microprocessor with a disk.

By the way one of the last specialties of the mainframe was virtualization. But that is now ubiquitous in desktop/server machines. People started doing it badly at first, using software techniques. VM's were so useful that users didn't mind the performance hit.  Then Companies like Intel looked at the mainframe again and learned a couple of more lessons by supporting virtualization in hardware to make it fast.

Title: Why aren't young programmers interested in mainframes?

Body:
A key issue with mainframes is that the cohort of supporting programmers is dwindling. While normally this wouldn't be a problem in that a falling supply of programmers would be offset by an increasing amount of salary those causing a rising supply of programmers via the law of supply and demand, I'm not sure this is really happening for mainframes.

While they still form critical infrastructure for many businesses, the simple fact is there isn't an adequate number of young programmers coming up along to keep the support population populated.

Why is this? What makes mainframes unattractive to young programmers?


答:
Web Server Definition

A web server is a service that handles specifically requests in the HTTP protocol format. The server responses to requests made using the HTTP format, and in turn responds using a valid HTTP response. All responses from a web server follow the W3 standards for HTTP protocols. Including, and not limited to, server 500 errors, redirects and various content types.

A web server may respond with a content type that supports non-HTML formats. Such as PDF files, binary files, and even JSON/XML responses. The key factor in understanding that these requests came from a web server is understanding that response is a HTTP response. The content in the response is just an application specific content type.

A web server may run multiple CGI languages to provide the HTTP responses. These can include Python, PHP, Java and ASP (among others). These languages operate under the web server, but in turn provide valid HTTP responses. There for, it's still a web server.

Application Server Definition

An application server is a service that handles specifically requests for business operations, and performs business logic. It is not limited to the HTTP protocol, but can operate using that protocol if it fits the business requirements.

Application servers tend to operate in TCP/IP communications. Including sockets, and other Internet low-level communications. It's possible for an application to use a web server as it's hosting environment.

Examples of tools that would require an application server could be, a gaming server, a chat server, a video conferencing server, a cloud-based accounting application, etc.. etc..

In most cases application servers wrap their business logic under an API layer. That API layer can be access via a common protocol the client supports, or via custom socket communication. There are multiple development platforms that have all these things built-in for the developer. They include platforms like J2EE or .NET

Title: what are the main differences between a web server and application server?

Body: I am new to web development and just started exploring the things. I read about how web page is processed and sent to client by a web server but I got confused with application server. what is the difference between them ? why app. server is needed ? and few examples of both of them .</p>


问:
Basic memcached question
I have been reading up on distributed hashing. I learnt that consistent hashing is used for distributing the keys among cache machines. I also learnt that, a key is duplicated on mutiple caches to handle failure of cache hosts. But what I have come across on memcached doesn't seem to be in alignment with all this. I read that all cache nodes are independent of each other and that if a cache goes down, requests go to DB. Theres no mention of cache miss on a host resulting in the host directing the request to another host which could either be holding the key or is nearer to the key.

Can you please tell me how these two fit together? Is memcached a very preliminary form of distributed hashing which doesnt have much sophistication?

答:
The memcached servers does not communicate with each other. It is the responsibility of clients to choose which memcached server to use. This methodology reduces the overhead between servers and it doesn't need to lookup key from each server. Therefore memcached is very fast not only by using RAM. Although many cached objects would be missed during server rearrangement or failure, the cached object could still be found by chance,

e.g., you have 3 memcached servers and each of them hold key 1, 2, 3. When server with key 3 is down, clients ask for key 3 would go to server with key 1, and client ask for key 1 would still go to sever with key 1, assume the key is distributed with odd and even by now.

Title: Basic memcached question


问:
How should we draw the release burndown chart?
I have been in various Agile projects and seen many release burndown chart styles. Most of them were handled manually since somehow all the tools that I have run across don't produce really useful burndown charts.

In reality, we may not be dealing with all stories estimated and we just keep burning down. Many times, the scope is added during the release.

Currently, I am dealing with these problems with the burndown chart and have questions about the following things:

How do we represent added scope in the release burndown chart?

How do we deal with unestimated stories in release burndown chart
assuming that there is high probability that we will do it but we
just do not have time to estimate them yet?

How do you project the end of the release?

The burndown chart below is from the fictional case study in the appendix of classic Mike Cohn's Estimating and Planing book.

答:
This is currently how my colleagues and I solve the burndown problems in the Agile tool that we are building

The added scoped is represented by the vertical line just like Mike Cohn's graph. We also emphasize this with the light-grey bars.

Unestimated stories are calculated based on current average velocity (of estimated stories) times number of unestimated stories. They are shown in the darker-grey bars. Estimated stories are shown in the darkest-grey bars.

Projection is based on the velocity of the last three iterations but we give more weight to the later iterations.

The graph does not look like it is burning down but it does reflect the reality that the scope is being added along the way and there are number of stories not estimated. We think this is a Really Useful Burndown Chart, at least for our internal projects, and we certainly welcome feedback :-)


问:
Why are cryptic short identifiers still so common in low-level programming?
There used to be very good reasons for keeping instruction / register names short. Those reasons no longer apply, but short cryptic names are still very common in low-level programming.

Why is this? Is it just because old habits are hard to break, or are there better reasons?

For example:

Atmel ATMEGA32U2 (2010?): TIFR1 (instead of TimerCounter1InterruptFlag), ICR1H (instead of InputCapture1High), DDRB (instead of DataDirectionPortB), etc.

.NET CLR instruction set (2002): bge.s (instead of branch-if-greater-or-equal.short), etc.

Aren't the longer, non-cryptic names easier to work with?

When answering and voting, please consider the following. Many of the possible explanations suggested here apply equally to high-level programming, and yet the consensus, by and large, is to use non-cryptic names consisting of a word or two (commonly understood acronyms excluded).

Also, if your main argument is about physical space on a paper diagram, please consider that this absolutely does not apply to assembly language or CIL, plus I would appreciate if you show me a diagram where terse names fit but readable ones make the diagram worse. From personal experience at a fabless semiconductor company, readable names fit just fine, and result in more readable diagrams.

What is the core thing that is different about low-level programming as opposed to high-level languages that makes the terse cryptic names desirable in low-level but not high-level programming?

答:
I'm surprised that no one has mentioned laziness and that other sciences are not discussed.
My daily work as programmer shows to me that naming conventions for any kind of variable in a program are influenced by three different aspects:

The scientific background of the programmer.

The programming skills of the programmer.

The environment of the programmer.

I think it is of no use to discuss about low level or high level programming. In the very end it can always be pinned down to the former three aspects.

An explanation of the first aspect:
Many "programmers" are not programmers in the first place. They are mathematicians, physicists, biologists or even psychologists or economists but many of them are not computer scientists. Most of them have their own domain specific keywords and abbreviations which you can see in their naming "conventions". They are often trapped in their domain and use those known abbreviations without thinking of readability or coding guides.

An explanation of the second aspect:
As most of the programmers are no computer scientists their programming skills are limited. Thats why they often dont care about coding conventions but more on domain specific conventions as stated as first aspect. Also if you do not have the skills of a programmer you do not have the understanding of coding conventions. I think most of them dont see the urgent need to write understandable code. Its like fire and forget.

An explanation of the third aspect:
It is unlikely to brake with the conventions of your environment which can be old code you have to support, coding standards of your company (run by economists who dont care about coding) or the domain you belong to. If someone started to use cryptic names and you have to support him or his code you are unlikely to change the cryptic names. If there are no coding  standards at your company I bet almost every programmer will write their own standard. And last if you are surrounded by domain users you will not start to write another languange than they use.


问:
Pair programming when driver and observer have different skill level and experience
I know pair programming is an agile software development technique in which two programmers work together at one workstation. One, the driver, writes code while the other, the observer, reviews each line of code as it is typed in.

But I just wonder the strategy still work in the case. For example

if they have a very different programming skill level.

if one never experience in the problem domain while another have.

Is it still OK if they have low programming skill level?

Could you suggest the pair programming strategy in the case above?

答:
This is exactly the use case pair programming was made for: sharing experience between old beard and young grasshopper.

This is a two-way sharing: agile insects have much to teach to rheumatic brains.


答:
Assuming that the more experienced person in the pair has the temperament to mentor the other person, pairing someone with little experience in the language or the problem domain with an experienced person would facilitate knowledge transfer. The less experienced person would have a mentor to instruct them on the language, the domain, the application, and the best practices or conventions of the team.

There's an interesting summary on C2 wiki about knowledge transfer using pair programming. The more senior person, who was brought on to serve as the team mentor, learned a lot from the junior programmers and his knowledge even increased as a result of being paired with more junior, less experienced software developers. There are some other stories about expert programmers being pair with domain experts, as well.

Title: Pair programming when driver and observer have different skill level and experience

Body:
I know pair programming is an agile software development technique in which two programmers work together at one workstation. One, the driver, writes code while the other, the observer, reviews each line of code as it is typed in.

But I just wonder the strategy still work in the case. For example

if they have a very different programming skill level.

if one never experience in the problem domain while another have.

Is it still OK if they have low programming skill level?

Could you suggest the pair programming strategy in the case above?


答:
In my experience if both the programmers have low skill level it can be a problem. In that case there is often a tendency to try copy-paste programming. I think it can be a good idea not to pair two novice programmers together until they reach specific level determined by the team.

Otherwise pair programming can be a great idea assuming of course two guys are ready to share what they know. Not only is it a great way to keep everyone informed of the source code but also acts as good place for new ideas and discussions.


问:
Does auto make C++ code harder to understand?
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

答:
I have two guidelines:

If the type of the variable is obvious, tedious to write or hard to
determine use auto.

```<code>auto range = 10.0f; // Obvious

for (auto i = collection.cbegin(); i != cbegin(); ++i) // Tedious if collection type
// is really long

template <typename T> ... T t; auto result = t.get(); // Hard to determine as get()
// might return various stuff
</code>```

If you need specific conversion or the result type is not obvious and might cause confusion.

```<code>class B : A {}; A* foo = new B(); // 'Convert'

class Factory { public: int foo(); float bar(); }; int f = foo(); // Not obvious
</code>```

OwnerDisplayName: Felics

Body:
I have two guidelines:

If the type of the variable is obvious, tedious to write or hard to
determine use auto.

auto range = 10.0f; // Obvious

for (auto i = collection.cbegin(); i != cbegin(); ++i) // Tedious if collection type
// is really long

template <typename T> ... T t; auto result = t.get(); // Hard to determine as get()
// might return various stuff

If you need specific conversion or the result type is not obvious and might cause confusion.

class B : A {}; A* foo = new B(); // 'Convert'

class Factory { public: int foo(); float bar(); }; int f = foo(); // Not obvious


问:
Which is better: to include HTML inside PHP code or outside it?
Look at this:

```<code><?php
echo "Hello World";
?>
<br />
<?php
echo "Welcome";
?>
</code>```

And now look at this:

```<code><?php
echo "Hello World";
echo "<br />";
echo "Welcome";
?>
</code>```

Which one of the above examples is considered to better (at least from performance point of view)?.

I know the examples are trivial but I want to follow good practice habits from the beginning so when I have more and more lines they would not affect the performance or whatever in a negative way.

答:
You're learning, forget about performance in PHP pages. Instead, choose the way that is easiest to read.

Looking at your two examples the second one is most definitely easiest to read, though I think that's because of the spacing you've used. You say you're looking to develop good habits from the start, I think your time can be better spent by making your code read well. This might mean rewriting a section several times until you're happy with it.

If you're really keen on the behind-the-scenes, I'll have a go at explaining what happens with static content in a PHP page. One of the first things is to "parse" the entire page into executable code (like you see between <?php ?> tags). One part of this is to turn any static text into an echo.

So this:

```<code><?php echo "Hello World"; ?>
<br />
<?php echo "Welcome"; ?>
</code>```

is transformed into something like:

```<code>echo "Hello World";
echo "<br />";
echo "Welcome";
</code>```

There's a very small cost associated with the parsing, but no difference in executing the resulting code. If you're using a PHP accelerator the parsing is only done once and then cached, so you would see no performance difference after the first page load.

Remember: easy to read!

Body:
You're learning, forget about performance in PHP pages. Instead, choose the way that is easiest to read.

Looking at your two examples the second one is most definitely easiest to read, though I think that's because of the spacing you've used. You say you're looking to develop good habits from the start, I think your time can be better spent by making your code read well. This might mean rewriting a section several times until you're happy with it.

If you're really keen on the behind-the-scenes, I'll have a go at explaining what happens with static content in a PHP page. One of the first things is to "parse" the entire page into executable code (like you see between <?php ?> tags). One part of this is to turn any static text into an echo.

So this:

<?php echo "Hello World"; ?>
<br />
<?php echo "Welcome"; ?>

is transformed into something like:

echo "Hello World";
echo "<br />";
echo "Welcome";

There's a very small cost associated with the parsing, but no difference in executing the resulting code. If you're using a PHP accelerator the parsing is only done once and then cached, so you would see no performance difference after the first page load.

Remember: easy to read!


问:
How to become an expert in C++
I have some experience in Java programming and enterprise application development. I have done OOP, data structures in C++ for my undergraduate studies. But I couldn't touch C++ for years. Now I am interested in C++ again and I would like to polish my C++ knowledge and become an expert in C++ . How do I start my journey in C++ again?

In this journey would like to learn some advanced concepts in C++ like network programming, distributed computing,.. etc.

答:
Disclaimer: What you read here are my personal ideas and they are not necessarily correct or widely accepted.

In short, practice! and probably more practice. If I want to talk in detail, there are few things that I like to point out. I was in more or less the same situation, having some experience in java and knowing c++ in surface.

To master c++ neither books nor video lectures were so much of help. Don't get me wrong, books are fine but in my case, it was only a matter of checking syntax or knowing the concept in detail. What really helped me, was developing couple of very serious projects with c++ and while doing that, I pretty much mastered some of the most important concepts. So again, practice, doing projects and meanwhile knowing what you are doing. By "knowing what you are doing" I mean you should know what exactly your code is doing (e.g. what is the difference between pass by reference and pass by pointer and etc).

Moreover, you should learn some details like how the compiler and linker work, what are macros and more. The point is, java is very nice language when developing(personal opinion); it's easy and fast to develop and you don't really need to be worry about lots of programming aspects. C++ on the other hand is not that easy. If you want to really master the language, you should know about the details of compiler, linker, macros, debuggers and etc.

I don't want to start a battle of operating systems here but I strongly suggest to work with linux. Nice architecture of linux allows you really see how things work and tools like cmake (which is cross platform btw) allows you to have a better understating of the compilation process. If you don't wanna use linux, at least forget about automated IDEs like ms visual studio where everything happens with a simple click.

But if I want to make only one suggestion, I have to repeat again: PRACTICE!

Title: How to become an expert in C++


答:
When I got promoted to my current team I was the newbie in J2EE but I was the expert in the domain. My senior (the new team leader) was skilled in J2EE but not in the platform.

I think I learned more about Java2EE in these 4 months with pair programming than reading a book and the team leader learned about the platform as well.

The experience gap between the two is the key to pair programming imho.


答:
Obviously there are a lot of areas you can look at, STL and Boost libraries spring to mind, but as an ex-Java developer you need to fix up the basic concepts that are different first.

Chief amongst these is object lifetimes, in Java you have a GC and finalisers and all that, with C++ you have explicitly defined scopes and deterministic places where your object will (automatically) go away when it leaves scope. Typically you create an object on the stack rather than the heap in C++, and let the compiler decide when to free it. Do not think that you have to create all objects on the heap and let the GC decide when they're no longer used. If you do need a longer lifetime object, or a large one that would suit living on the heap, use a smart pointer class to manage it. You might want to check up on the latest spec with its features like lambdas and especially the move operator syntax too.

Google for RAII and make sure you learn C++ scopes, its trivially easy, but like many things that are easy you need to take the small amount of time to understand them.

Title: How to become an expert in C++

Body:
I have some experience in Java programming and enterprise application development. I have done OOP, data structures in C++ for my undergraduate studies. But I couldn't touch C++ for years. Now I am interested in C++ again and I would like to polish my C++ knowledge and become an expert in C++ . How do I start my journey in C++ again?

In this journey would like to learn some advanced concepts in C++ like network programming, distributed computing,.. etc.


答:
I think it is a nice interview question. The requirements are unclear, just as they are often in reality. You check whether the candidate is intelligent enough to realize this (even under stress), that he/she is not afraid to ask questions they deem necessary, and is able to put the requirements into a sensible structure. And it does tell a little bit about their programming abilities, though you should also pose some more complicated problems containing recursion and pointers, since this problem is too easy.

However, I do worry a little about the "successful" candidates not asking questions. I'd try to find out whether they realized you can apply up to 4 of the rules in some cases and that there is nothing in the question that would resolve that ambiguity, and have them explain how they dealt with that. Perhaps your question is not ambiguous enough to force them to ask, or perhaps you should ask them to think aloud.

BTW: I find it strange that you are talking about a "correct solution". If you word the question like that, it is legitimate to print either of "Fizz", "Buzz", "BuzzBuzz" or "FizzBuzz" if you get "AB". So IMHO any solution with no questions asked is plain wrong.

Title: Effectiveness of FizzBuzz and Beyond

Body:
As part of the interview process we initially ask the candidates to do 'FizzBuzz' nowadays the percentage of candidates that can correctly answer FizzBuzz has increased dramatically - this may be due to it's popularity on the web.

About a year ago, as a second question we began asking a question very similar to the original FizzBuzz. The question was designed to be as simple as the original FizzBuzz, and to also assess a particular ability of the candidate, specifically the ability to order and prioritize in a meaningful and logical manner a set of "business rules" that have been provided in some arbitrary order. The wording of the question initially seems slightly ambiguous, which may make it difficult for non-native English speakers, but if thought through can be correctly resolved - Also it gives the candidate the opportunity to ask questions for clarification, which is always a good thing.

We find this a very important skill to have as a developer, as software development is typically based on functional requirements that are derived in no particular order over time, that may place constraints and conditions upon other areas of the software without explicitly indicating and it is the job of the astute developer to at the very least investigate potential issues and conflicts with regards to the implementation.

What we found was that a little over 65% of the candidates (sample size of 38) that passed FizzBuzz completely failed FizzBuzz v2.0 Normally these candidates would be detected later on in the process, but it seems to be a nice way to detect them early on.

My question is not about whether or not FizzBuzz is outdated, but rather what factors could be contributing to such a high number of candidates failing the FizzBuzz v2 question.

Is the question too ambiguous?

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

Question:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list will do one of the following:

Print only Fizz if the string contains the letter A

Print only Buzz if the string contains the letter B

Print only BuzzBuzz if the string contains both A and B

Print only FizzFizz if the string does not contain both A and B

Print only FizzBuzz if the string contains only one A and only one B

Some typical questions asked by candidates are:

Should it be case sensitive?

Does "contains A and B" mean A should come before B

What should be printed if none of the points are met?

What should happen if more than one condition can be met?

We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.


答: I would suggest one piece of advice, go on stackoverflow, look for unanswered questions about C++ and try and answer them. The amount you learn from answering questions is immense, and you'll be surprised how often they tend to crop up as issues further down the line for you.

Title: How to become an expert in C++


答:
I understand that you are the only person (or one of very few) to use this mechanism:

if you want to authenticate other users of your webapp, then refer to @Martin's answer, otherwise:

your token is technically called a shared secret. It works and it is secure (as long as the secret is not shared to the outside world, like e.g. readable from the web, etc.).

saving it in a text-file is secure if the storage is secure.

another very simple way would be basic auth. it should be sent over ssl, though. see this question for some further discussion on its security implications.

Title: Simplest token-system for authenticating and authorizating

Body:
I want to make Python script that will accept input from Vim and send it to my web-site. So basically I want to make Vim my text-editor for blog articles.

Of course, I need to authenticate and authorizate. I wanted to simply ask username and password. My college asked me why not to take login data from file. I answered that I don't want to save password in plain-text. He told me to use tokens!

So how to do it? I understand that I need to generate random token for user and knowing it will allow anyone to login. It should be really strong and random so nobody can guess it. Is there something else? Will it be safe to save it in text file?

I would like to hear how would you implement it in the simplest possible yet secure way. Some links to literature would be good too!


问:
The best way to implement authentication for a REST API
We develop social-based applications for mobile. Every application consumes RESTful API web-services. When I implement login I usually store the username and password somewhere on device. Then I send them and as a response I get access to my profile. But I also know there's another way to do this.

One somehow generates a token with a particular algorithm, and then send it instead of the username and password to gain access.

How should I implement that? Should I send this token along with every other request than login?

答:
oAuth is the standard for this but there are more solutions.

Don't try to implement security, tokens etc. all by yourself since that's a difficult and risky topic. Take for example a look here:

https://stackoverflow.com/questions/4574868/securing-my-rest-api-with-oauth-while-still-allowing-authentication-via-third-pa


答:
There are several way how to implement authentication in RESTful context, and it is more safe to send only tokens instead of login/password: you could easy make tokens to be invalid by timeout or by some other criteria, and ask user to re-authenticate.

For example authentication REST requests using HMAC. In this approach, client will have public and secret keys. To all requests that require authentication, you should add publiс key, and use secret key to calculate hash of your request

```<code>var myRequest = "https://myserver/resource?publicId=12345&param=value";
var requestHash = hmac_implementation(myRequest);
myRequest = myRequest + '&hmac=' + requestHash;
</code>```

Now server could identify request by public key and calculate requestHash itself. If both hashes are equal, then user is authorized.

Btw, you also have to use https to secure communication over a computer network — this will dramaticaly reduce number of possible problems.

Title: The best way to implement authentication for a REST API

Body:
We develop social-based applications for mobile. Every application consumes RESTful API web-services. When I implement login I usually store the username and password somewhere on device. Then I send them and as a response I get access to my profile. But I also know there's another way to do this.

One somehow generates a token with a particular algorithm, and then send it instead of the username and password to gain access.

How should I implement that? Should I send this token along with every other request than login?

Body:
There are several way how to implement authentication in RESTful context, and it is more safe to send only tokens instead of login/password: you could easy make tokens to be invalid by timeout or by some other criteria, and ask user to re-authenticate.

For example authentication REST requests using HMAC. In this approach, client will have public and secret keys. To all requests that require authentication, you should add publiс key, and use secret key to calculate hash of your request

var myRequest = "https://myserver/resource?publicId=12345&param=value";
var requestHash = hmac_implementation(myRequest);
myRequest = myRequest + '&hmac=' + requestHash;

Now server could identify request by public key and calculate requestHash itself. If both hashes are equal, then user is authorized.

Btw, you also have to use https to secure communication over a computer network — this will dramaticaly reduce number of possible problems.


答:
There are so many different ideas here. I can't accept any of the existing answers as the answer: firstly, there are likely many factors contributing to this, and secondly, I can't possibly know which one is the most significant one.

So here's a summary of answers posted by others here. I'm  posting this as CW and my intention is to eventually mark it accepted. Please edit if I missed something out. I tried to rephrase each idea to express it concisely yet clearly.

So why are cryptic short identifiers so common in low-level programming?

Because many of them are common enough in the respective domain to warrant a very short name. This worsens the learning curve, but is a worthwhile tradeoff given the frequency of use.

Because there is usually a small set of possibilities that is fixed (the programmer can't add to the set).

Because readability is a matter of habit and practice. branch-if-greater-than-or-equal.short is initially more readable than bge.s, but with some practice the situation becomes reversed.

Because they often have to be typed out in full, by hand, because low-level languages often don't come with powerful IDEs that have good autocompletion, or a/c is not reliable.

Because it's sometimes desirable to pack a lot of information into the identifier, and a readable name would be unacceptably long even by high-level standards.

Because that's what low-level environments have looked like historically. Breaking habit requires conscious effort, runs the risk of annoying those who liked the old ways, and must be justified as worthwhile. Sticking with the established way is the "default".

Because many of them originate elsewhere, such as schematics and datasheets. Those, in turn, are affected by space constraints.

Because the people in charge of naming things have never even considered readability, or don't realize they are creating a problem, or are lazy.

Because in some cases the names have become part of a protocol for interchange of data, such as the use of assembly language as an intermediate representation by some compilers.

Because this style is instantly recognizable as low-level and thus looks cool to geeks.

I personally feel that some of these do not actually contribute to the reasons why a newly developed system would choose this naming style, but I felt it would be wrong to filter some ideas out in this type of answer.

Title: Why are cryptic short identifiers still so common in low-level programming?

Body:
There used to be very good reasons for keeping instruction / register names short. Those reasons no longer apply, but short cryptic names are still very common in low-level programming.

Why is this? Is it just because old habits are hard to break, or are there better reasons?

For example:

Atmel ATMEGA32U2 (2010?): TIFR1 (instead of TimerCounter1InterruptFlag), ICR1H (instead of InputCapture1High), DDRB (instead of DataDirectionPortB), etc.

.NET CLR instruction set (2002): bge.s (instead of branch-if-greater-or-equal.short), etc.

Aren't the longer, non-cryptic names easier to work with?

When answering and voting, please consider the following. Many of the possible explanations suggested here apply equally to high-level programming, and yet the consensus, by and large, is to use non-cryptic names consisting of a word or two (commonly understood acronyms excluded).

Also, if your main argument is about physical space on a paper diagram, please consider that this absolutely does not apply to assembly language or CIL, plus I would appreciate if you show me a diagram where terse names fit but readable ones make the diagram worse. From personal experience at a fabless semiconductor company, readable names fit just fine, and result in more readable diagrams.

What is the core thing that is different about low-level programming as opposed to high-level languages that makes the terse cryptic names desirable in low-level but not high-level programming?


问:
Using a product licensed under GNU GPLv3 for internal company use
I am in the process of a creating a small web portal for the department I'm working in. For this is need to present some data, and have found the following: http://www.pchart.net/, which could seem to be of great help to me.

The above is licensed under GNU GPLv3, and my question is whether it would be allowed for me to use the above, for free.

To clarify, the portal that I'm creating will in no way be sold or generate money, but will purely be for internal informational purposes.

I have read through the terms and conditions of the GPLv3, and as far as i can make out, my situation is legal, but i want to be absolutely sure that I'm not using the software illegally.

答: GPL does not restrict usage in any way. Even making money is OK. Only further distribution is subject to the license terms.</p>


问:
How can I avoid mistakes using the same variable name again?
This isn't a rare case and occurs with me often and I spent countless time trying to debug the code.

Latest example, this PHP code where I used $email for the parameter and for object as well.

```<code>private function _mail( $email )
{
    if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ):
        $email = new Zend_Mail();
        $email->setSubject( $this->request->post('subject') )
            ->setBodyHtml( $this->request->post('message') )
            ->setFrom( $this->request->post('from') )
            ->addTo( $email )
            ->send();
        unset($email);
    endif;
}
</code>```

It was throwing an error, strtr() expects parameter 1 to be an string object given and it was really frustrating to browse through zend libraries to see what obscure string statement was throwing this error.

How to avoid such mistakes?

答:
One good aspect of modern programming languages is that you can have large variable names. In Object oriented programming, which you are utilising, Java conventions are quite popular.

So it would be better to have a descriptive name for the Zend_Mail object, such as

```<code>$zendMail = new Zend_Mail();
</code>```

In the beginning it will consume a bit more time until the brain shifts making it a habit, but that time will have a huge return of investment and stress from having to debug similar cases.

Body:
One good aspect of modern programming languages is that you can have large variable names. In Object oriented programming, which you are utilising, Java conventions are quite popular.

So it would be better to have a descriptive name for the Zend_Mail object, such as

$zendMail = new Zend_Mail();

In the beginning it will consume a bit more time until the brain shifts making it a habit, but that time will have a huge return of investment and stress from having to debug similar cases.


问:
Wiki-like tool for writing specifications and documentation
I am looking for a wiki or wiki-like system for writing and managing specification and documentation for a software project.

I know there are lots of wiki-implementations available, but are there some that are especially well-suited for this kind of task?

Actually it doesn't have to be a wiki, just a system that makes it easy to write and navigate specs and documentation, and which support change tracing.

答: For the personal project (existing only in my PC) I use Wiki in a Jar. In the past I worked with Redmine (it has furthermore a system of bug tracking and SCM  )</p>


问:
Effectiveness of FizzBuzz and Beyond
As part of the interview process we initially ask the candidates to do 'FizzBuzz' nowadays the percentage of candidates that can correctly answer FizzBuzz has increased dramatically - this may be due to it's popularity on the web.

About a year ago, as a second question we began asking a question very similar to the original FizzBuzz. The question was designed to be as simple as the original FizzBuzz, and to also assess a particular ability of the candidate, specifically the ability to order and prioritize in a meaningful and logical manner a set of "business rules" that have been provided in some arbitrary order. The wording of the question initially seems slightly ambiguous, which may make it difficult for non-native English speakers, but if thought through can be correctly resolved - Also it gives the candidate the opportunity to ask questions for clarification, which is always a good thing.

We find this a very important skill to have as a developer, as software development is typically based on functional requirements that are derived in no particular order over time, that may place constraints and conditions upon other areas of the software without explicitly indicating and it is the job of the astute developer to at the very least investigate potential issues and conflicts with regards to the implementation.

What we found was that a little over 65% of the candidates (sample size of 38) that passed FizzBuzz completely failed FizzBuzz v2.0 Normally these candidates would be detected later on in the process, but it seems to be a nice way to detect them early on.

My question is not about whether or not FizzBuzz is outdated, but rather what factors could be contributing to such a high number of candidates failing the FizzBuzz v2 question.

Is the question too ambiguous?

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

Question:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list will do one of the following:

Print only Fizz if the string contains the letter A

Print only Buzz if the string contains the letter B

Print only BuzzBuzz if the string contains both A and B

Print only FizzFizz if the string does not contain both A and B

Print only FizzBuzz if the string contains only one A and only one B

Some typical questions asked by candidates are:

Should it be case sensitive?

Does "contains A and B" mean A should come before B

What should be printed if none of the points are met?

What should happen if more than one condition can be met?

We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.

答:
Instead of giving a candidate contradictory/unclear requirements, just ask them how they handle those situations. Otherwise you're making yourself look incompetent or worse putting competent people on the treacherous balance beam of "how do I get the answers I need without implying that this interview question or the person asking it is stupid?"

Either way, it's irritating as all getout. Interviews are a matching process and by that, I mean a 2-way street. Direct questions and clarity of intent are a lot more important than putting the candidate under a pressure cooker, IMO. FizzBuzz is a good example of a coding question because it's short and sweet. Don't re-use it directly. Write simple questions like it that follow that model.

But for FFS don't get clever about it and hide the real test behind another test. Just ask people how they handle the damn problem. An experienced dev will have dealt with ambiguous requirements repeatedly and will be delighted to tell you their strategies. You might even learn something.

And don't assume everybody wants to use a whiteboard or is comfortable handwriting period. Some of us have been typing since we were 12 (with much thanks to Space Quest). I can't even think straight with a pen or marker in my hand. It's 20-freaking-13, what's with the whiteboards already? When people hand me a pen and paper and ask me to do a code-test it's hard to suppress a laugh.

Title: Effectiveness of FizzBuzz and Beyond


答: You might try Sphinx, with the documents checked into your source control management infrastructure of choice. This has the advantages of source control and a relatively lightweight markup language, reStructuredText, that is easy to learn and pretty well instrumented for conversions (to HTML, to PDF, and so on).</p>

Title: Wiki-like tool for writing specifications and documentation

Body:
I am looking for a wiki or wiki-like system for writing and managing specification and documentation for a software project.

I know there are lots of wiki-implementations available, but are there some that are especially well-suited for this kind of task?

Actually it doesn't have to be a wiki, just a system that makes it easy to write and navigate specs and documentation, and which support change tracing.


问:
What are the drawbacks of Python?
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)

答:
Things I don't like about Python:

Threading (I know its been mentioned already, but worth mentioning in every post).

No support for multi-line anonymous functions (lambda can contain only one expression).

Lack of a simple but powerful input reading function/class (like cin or scanf in C++ and C or Scanner in Java).

All strings are not unicode by default (but fixed in Python 3).

Title: What are the drawbacks of Python?


问:
Sorting : Useful for more than just viewing data?
Context

I'm currently working on a personal project involving functional reactive JavaScript, and I've come up with an odd question. Note that this question is not JavaScript specific, but that is the context in which I am asking it.

Scenario

When filtering a collection of data, you end up with a smaller set of data. Therefore, correctly filtering your data earlier (rather than later) ends up optimizing your later code, as it does not need to iterate through the portion of data which will not be used. (think filtering before mapping, instead of visa-versa)

However, I was wondering if there's a scenario in which sorting provides similar benefits, or if sorting is generally used as a way of formatting data to be displayed, so that an end user may more easily absorb it (sort by name, city, state, etc).

Question

When is sorting your data more desirable than sorting the corresponding views of that data?

答:
Well the obvious answer is that for some data structures knowing that the data is already sorted changes lookups from O(n) to O(log n) e.g. finding an element in an array using binary search rather than linear.

I'm not sure how useful this is to you if you are doing FRP though, one assumes that FRP means you probably aren't using array like structures in the first place?

I'd also point out that this is a bit different than filter then map. the map gains the benefit of a previous filter without needing any knowledge of the filter. binary search however requires knowing the data is sorted.


答:
In PHP I prefix function/method paramaters with 'in' - and don't use any variable starting with 'in' within the body. It's not ideal, but it works.

Dimitris point about more descriptive names is also helpful.

Title: How can I avoid mistakes using the same variable name again?

Body:
This isn't a rare case and occurs with me often and I spent countless time trying to debug the code.

Latest example, this PHP code where I used $email for the parameter and for object as well.

```<code>private function _mail( $email )
{
    if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ):
        $email = new Zend_Mail();
        $email->setSubject( $this->request->post('subject') )
            ->setBodyHtml( $this->request->post('message') )
            ->setFrom( $this->request->post('from') )
            ->addTo( $email )
            ->send();
        unset($email);
    endif;
}
</code>```

It was throwing an error, strtr() expects parameter 1 to be an string object given and it was really frustrating to browse through zend libraries to see what obscure string statement was throwing this error.

How to avoid such mistakes?


问:
How should I distinguish between built-in types in Python?
I have a function that accepts either a string or a dictionary as an argument. That is, it can be called as either:

```<code>lookup_person({name: "John Smith", age: 57})
</code>```

or

```<code>lookup_person("John Smith")
</code>```

My first inclination is to use type or isinstance to distinguish the type of the argument, but I've seen a lot of ink spilled over whether and when rigid type detection is appropriate. The prevailing wisdom I've read suggests that I should test if my object implements some interface, but testing for particular string or dictionary methods seems significantly less safe than simply testing if the type of the object is a string or dictionary.

Is it possible to employ duck typing here, and is it appropriate to do so? Or do I have a larger problem, and my approach here somehow fundamentally not Pythonic?

EDIT: To clarify, passing a dictionary is the "typical" use. Passing in a string is simply an API shorthand for a single-entry dictionary with name, i.e., lookup_person({name:"John Smith"}).

答:
You definitely can use duck typing here, although I'm not sure why you want to accept both a dictionary and a string in this case.

I'd ask for forgiveness instead of permission in this case:

```<code>try:
    name = person['name']  # treat as dictionary
except TypeError:
    name = person          # assume it's a string instead
</code>```

but do review if asking for permission might be faster for your case.

Body:
You definitely can use duck typing here, although I'm not sure why you want to accept both a dictionary and a string in this case.

I'd ask for forgiveness instead of permission in this case:

try:
    name = person['name']  # treat as dictionary
except TypeError:
    name = person          # assume it's a string instead

but do review if asking for permission might be faster for your case.


答:
Various scenarios spring to mind, the textbook ones being searches and finding minimum / maximum values; on a sorted list, searching is typically O(log n) and min/max is O(1), while on an unsorted list, you'll get O(n) for both.

Besides that, depending on what you need to do with your data, other optimizations may be possible that exploit sortedness of a list - think of things like axis sorting in collision detection.

Title: Sorting : Useful for more than just viewing data?

Body:
Context

I'm currently working on a personal project involving functional reactive JavaScript, and I've come up with an odd question. Note that this question is not JavaScript specific, but that is the context in which I am asking it.

Scenario

When filtering a collection of data, you end up with a smaller set of data. Therefore, correctly filtering your data earlier (rather than later) ends up optimizing your later code, as it does not need to iterate through the portion of data which will not be used. (think filtering before mapping, instead of visa-versa)

However, I was wondering if there's a scenario in which sorting provides similar benefits, or if sorting is generally used as a way of formatting data to be displayed, so that an end user may more easily absorb it (sort by name, city, state, etc).

Question

When is sorting your data more desirable than sorting the corresponding views of that data?


问:
Is the use of security conditionals in a view a violation of MVC?
Often what's displayed to a user (e.g. on a web page) will be based partly on security checks.  I usually consider user-level / ACL security to be part of the business logic of a system.  If a view explicitly checks security to conditionally display UI elements, is it violating MVC by containing business logic?</p>

答: If it's only about displaying the UI element I think it's ok (how else would you do it anyway?). If there would be any data in those elements the model should have made sure that the containers are empty. And of course the code to get the permission data should have been handled before the view, so there is no active access to the model here.</p>


答:
I would say no.

Usually, this kind of security checks are going to be done by the controller.

As from Wikipedia:

A controller can send commands to its associated view to change the view's presentation of the model

And I do not think it should be done directly in the view. If it is done via javascript, for instance, it could be a security issue (one could disable javascript and access privilleged data).

Again, from Wikipedia:

A view requests from the model the information that it needs to generate an output representation.

Title: Is the use of security conditionals in a view a violation of MVC?

Body: Often what's displayed to a user (e.g. on a web page) will be based partly on security checks.  I usually consider user-level / ACL security to be part of the business logic of a system.  If a view explicitly checks security to conditionally display UI elements, is it violating MVC by containing business logic?</p>


答:
There can be two types of security conditionals, one on the model and another on the view. The view controls the display of relevant elements depending on permissions of the current user, but the model controls access to the underlying data. As long as the model has all of the right verifications/validations, then even if the view is lacking, there is still security.

Usually you have to have both, since the view needs to change for different levels/roles. The controller sends the relevant data that would change the view, but the view still needs to do something with that data to hide/display content to the right user.

That's why most templating frameworks have conditional elements (Handlebars example):

```<code>{{#if isCurrentUserAdmin}}
    ....
{{/if}
</code>```

So that means that it's not a violation, as long as the appropriate pieces are in the correct place.

Body:
There can be two types of security conditionals, one on the model and another on the view. The view controls the display of relevant elements depending on permissions of the current user, but the model controls access to the underlying data. As long as the model has all of the right verifications/validations, then even if the view is lacking, there is still security.

Usually you have to have both, since the view needs to change for different levels/roles. The controller sends the relevant data that would change the view, but the view still needs to do something with that data to hide/display content to the right user.

That's why most templating frameworks have conditional elements (Handlebars example):

{{#if isCurrentUserAdmin}}
    ....
{{/if}

So that means that it's not a violation, as long as the appropriate pieces are in the correct place.


问:
SQL: empty string vs NULL value
I know this subject is a bit controversial and there are a lot of various articles/opinions floating around the internet. Unfortunatelly, most of them assume the person doesn't know what the difference between NULL and empty string is. So they tell stories about surprising results with joins/aggregates and generally do a bit more advanced SQL lessons. By doing this, they absolutely miss the whole point and are therefore useless for me. So hopefully this question and all answers will move subject a bit forward.

Let's suppose I have a table with personal information (name, birth, etc) where one of the columns is an email address with varchar type. We assume that for some reason some people might not want to provide an email address. When inserting such data (without email) into the table, there are two available choices: set cell to NULL or set it to empty string (''). Let's assume that I'm aware of all the technical implications of choosing one solution over another and I can create correct SQL queries for either scenario. The problem is even when both values differ on the technical level, they are exactly the same on logical level. After looking at NULL and '' I came to a single conclusion: I don't know email address of the guy. Also no matter how hard i tried, I was not able to sent an e-mail using either NULL or empty string, so apparently most SMTP servers out there agree with my logic. So i tend to use NULL where i don't know the value and consider empty string a bad thing.

After some intense discussions with colleagues i came with two questions:

am I right in assuming that using empty string for an unknown value is causing a database to "lie" about the facts? To be more precise: using SQL's idea of what is value and what is not, I might come to conclusion: we have e-mail address, just by finding out it is not null. But then later on, when trying to send e-mail I'll come to contradictory conclusion: no, we don't have e-mail address, that @!#$ Database must have been lying!

Is there any logical scenario in which an empty string '' could be such a good carrier of important information (besides value and no value), which would be troublesome/inefficient to store by any other way (like additional column). I've seen many posts claiming that sometimes it's good to use empty string along with real values and NULLs, but so far haven't seen a scenario that would be logical (in terms of SQL/DB design).

P.S. Some people will be tempted to answer, that it is just a matter of personal taste. I don't agree. To me it is a design decision with important consequences. So i'd like to see answers where opion about this is backed by some logical and/or technical reasons.

答:
I could think of a reason for having NULL and the empty string:

You have valid email addresses: me@example.com

You have none (and probably should ask for one): NULL

You know that this person does not have an email address: Empty String.

However I would not recommend that and use a separate field for whether to ask whether you know that none is existing.

Title: SQL: empty string vs NULL value


答:
I would say no.

But for a different reason than @rvcoutinho said (though he cites wikipedia which makes me feel wrong in my thinking)

I would say any relevant security concerns should be shared by the Model given to the view (depending on the number of combinations you may wish to use a ViewModel for this reason), in that you could have switches for the security bits.

This allows the two layer security validation: at the UI layer so a postback is subverted for the normal case, as well as at the server layer for bad actors where the model maintains the security knowledge inside of itself so the controller hands off the info to the model which immediately tosses it out.

Two layer security like this is the standard in industry, and this way allows your security logic only need exist in two places so it's a bonus, as soon as you put security logic in your controller, you're putting it there, and in the UI and in the model (the model needs it as it's the last line of defense and especially important for any uses outside of that MVC web-app like a desktop client or any server management tools)


问:
Can multiple CPU's / cores access the same RAM simultaneously?
This is what I guess would happen:

If two cores tried to access the same address in RAM, one would have to wait for the other to access the RAM.  The second time that each core would try to access the same address, they may still have that RAM cached, so they could access their respective caches simultaneously.

If two cores tried to access different addresses in the same RAM, one would have to wait for the other to access the RAM.

In other words, I would imagine that for RAM intensive programming tasks, multiprocessing won't help much unless it involved reading from the same address in RAM multiple times per core.

So, can multiple CPU's / cores access the same RAM simutaneously, or is what I'm saying correct?

答:
So, can multiple CPU's / cores access the same RAM simutaneously, or is what I'm saying correct?

There are many different machine architectures out there, each with its own set of features. One category of multiprocessing machines is called MISD, for Multiple Instruction Single Data, and such machines are designed to provide the same data to several processors all at the same time. A related class of machines known as SIMD architectures (Single Instruction Multiple Data) are much more common and also provide access to the same memory at the same time, but the memory contains instructions instead of data. In both MIMD and SIMD, "access" means read access -- you can imagine the trouble you'd have if two units tried to write to the same location at the same time!


问:
call sub function based on variable value
I have a function containing other functions. These function are called based on value of variable action.

These sub functions are logically grouped - i.e., they all deal with file manipulation.

Each function has 2 to 5 lines.

I would like to improve the style.

Is there a more concise way of achieving this end than what I have below? I feed there is a log of defining functions that contain not many LOC.

```<code>def my_function(action):

    return { '1': func_a, '2': func_b, '3': func_c, '4': func_d}.get(action, err)()

    def func_a():
        ...
        ...
        return ...
    def func_b():
        ...
        ...
        ...
        return ...
    def func_c():
        ...
        ...
        return ...
    def func_d():
        ...
        ...
        return ...
    def err():
        return
</code>```

*discaimer: actual functions have logical names.

My issue is with the proliferation of functions to define

答:
If you cannot factor out common code in these functions they may not be reduced in size, if you cannot factor out features into common feature paths they cannot be reduced in number.

That said this approach is marvelous in my opinion and I have used dictionaries of functions to great effect in the past.

I can give one suggestion to your approach:
Don't nest all the functions inside of the dispatching function. This may alleviate some of your concerns of cleanliness, perhaps something like:

```<code>def my_function(action):
    return { '1': func_a, '2': func_b, '3': func_c, '4': func_d}.get(action, err)()

def func_a():
    ...
    ...
    return ...
def func_b():
    ...
    ...
    ...
    return ...
</code>```

By having separate functions which return the dispatchable functions, you can effectively move those functions to wherever they best fit in your system hierarchy, and your dispatcher simply calls them out. However if the nesting approach is the best modeling given your system then stick with what you have.

Body:
If you cannot factor out common code in these functions they may not be reduced in size, if you cannot factor out features into common feature paths they cannot be reduced in number.

That said this approach is marvelous in my opinion and I have used dictionaries of functions to great effect in the past.

I can give one suggestion to your approach:
Don't nest all the functions inside of the dispatching function. This may alleviate some of your concerns of cleanliness, perhaps something like:

def my_function(action):
    return { '1': func_a, '2': func_b, '3': func_c, '4': func_d}.get(action, err)()

def func_a():
    ...
    ...
    return ...
def func_b():
    ...
    ...
    ...
    return ...

By having separate functions which return the dispatchable functions, you can effectively move those functions to wherever they best fit in your system hierarchy, and your dispatcher simply calls them out. However if the nesting approach is the best modeling given your system then stick with what you have.


答:
Summary: it's generally possible for a single core to saturate the memory bus if memory access is all it does.

If you establish the memory bandwidth of your machine, you should be able to see if a single-threaded process can really achieve this and, if not, how the effective bandwidth use scales with the number of processors.

The details will depend on the architecture you're using. Assuming something like modern SMP and SDRAM:

If two cores tried to access the same address in RAM ...

could go several ways:

they both want to read, simultaneously:

two cores on the same chip will probably share an intermediate cache at some level (2 or 3), so the read will only be done once. On a modern architecture, each core may be able to keep executing µ-ops from one or more pipelines until the cache line is ready

two cores on different chips may not share a cache, but still need to co-ordinate access to the bus: ideally, whichever chip didn't issue the read will simply snoop the response

if they both want to write:

two cores on the same chip will just be writing to the same cache, and that only needs to be flushed to RAM once. In fact, since memory will be read from and written to RAM per cache line, writes at distinct but sufficiently close addresses can be coalesced into a single write to RAM

two cores on different chips do have a conflict, and the cache line will need to be written back to RAM by chip1, fetched into chip2's cache, modified and then written back again (no idea whether the write/fetch can be coalesced by snooping)

If two cores tried to access different addresses ...

For a single access, the CAS latency means two operations can potentially be interleaved to take no longer (or perhaps only a little longer) than if the bus were idle.

Title: Can multiple CPU's / cores access the same RAM simultaneously?

Body:
This is what I guess would happen:

If two cores tried to access the same address in RAM, one would have to wait for the other to access the RAM.  The second time that each core would try to access the same address, they may still have that RAM cached, so they could access their respective caches simultaneously.

If two cores tried to access different addresses in the same RAM, one would have to wait for the other to access the RAM.

In other words, I would imagine that for RAM intensive programming tasks, multiprocessing won't help much unless it involved reading from the same address in RAM multiple times per core.

So, can multiple CPU's / cores access the same RAM simutaneously, or is what I'm saying correct?


问:
IOC and stateless services. Short-lived or single-instance?
Given a garbage-collected framework, when using an IOC container to inject purely stateless services, is it generally better to use the container's single-instance lifespan or to recreate the object each time it is used and throw it, and all its dependencies, away as soon as you're done with them?</p>

答:
You mention that your service has dependencies.

If any dependency in your graph of dependencies is not completely stateless, or if one of your dependencies in your graph of dependencies should be modified to be not so completely stateless anymore, then the whole system will fail. And the errors you get will probably be very cryptic, thus making it difficult to discover the problem.

Say you are a team of developers working on the project. It is highly unlikely that each and every one of them are aware that IOC configuration requires all these components to stay completely stateless. They may know it now, but that awareness will fade over time. And if you hire a new guy, he/she will not be aware either.

So I would definitely set up the IOC container to return a new instance every time. It is simply the safer choice, imho.

I would certainly not worry about resources. The cost of construction and garbage collection of objects is probably insignificant compared to e.g. just a single database lookup.


答:
It's trickier than you have put it.

According to pChart license page, GPLv3 only applies to non-commercial use.

The pChart library is released under two different licenses. If your
application is not a commercial one (eg: you make no money by
redistributing it) then the GNU GPLv3 license (General Public License)
applies.

[...]

If your application can't meet the GPL license or is a commercial one
(eg: the library is integrated in a software or an appliance you're
selling) then you'll have to buy a commercial license.

It's not immediately obvious that internal use in commercial entity can be considered non-commerical use. Even though the examples given would suggest that if you're not distributing commercial software with that library, you're in the clear. Still, if you want to be 100% sure, you'd actually have to contact authors.

Obviously, if GPLv3 indeed applies, than it's considered internal distribution, and not subject to the license's restrictions.

Title: Using a product licensed under GNU GPLv3 for internal company use

Body:
I am in the process of a creating a small web portal for the department I'm working in. For this is need to present some data, and have found the following: http://www.pchart.net/, which could seem to be of great help to me.

The above is licensed under GNU GPLv3, and my question is whether it would be allowed for me to use the above, for free.

To clarify, the portal that I'm creating will in no way be sold or generate money, but will purely be for internal informational purposes.

I have read through the terms and conditions of the GPLv3, and as far as i can make out, my situation is legal, but i want to be absolutely sure that I'm not using the software illegally.


答:
Yes and no.

If the actual security decision is made by the view, then yes, you are violating MVC. If, however, the view delegates the actual decision to the model, then you're fine. There is nothing wrong with a view making decisions on which elements to show, based on information from the model.

For example, if you have an "edit" button that is only visible for users with "editor" permissions, then it is fine for the view to ask the model who the current user is and whether they have the "editor" permission, then using this information to decide whether to show the button or not. If, however, the view were to do the authentication and authorization logic itself, then you'd be violating MVC.


问:
Implementing the transport layer for a SIP UAC
I have a somewhat simple, but specific, question about implementing the transport layer for a SIP UAC.

Do I expect the response to a request on the same socket that I sent the request on, or do I let the UDP or TCP listener pick up the response and then route it to the correct transaction from there? The RFC does not seem to say anything on the matter.

It seems that especially using UDP, which is connection-less, that I should just let the listeners pick up the response, but that seems sort of counter intuitive. Particularly, I have seen plenty of UAC implementations which do not depend on having a Listener in the transport layer.

Also, most implementations I have looked at do not have the UAS receiving loop responding on the socket at all. This would tend to indicate that the client should not be expecting a reply on the socket that it sent the request on.

For clarification:

Suppose my transport layer consists of the following elements:

```<code>TCPClient (Sends Requests for a UAC via TCP)
UDPClient (Sends Requests for a UAC vid UDP)
TCPSever (Loop receiving Requests and dispatching to transaction layer via TCP)
UDPServer (Loop receiving Requests and dispatching to transaction layer via UDP)
</code>```

Obviously, the *Client sends my Requests. The question is, what receives the Response? The *Client waiting on a recv or recvfrom call on the socket it used to send the request, or the *Server?

Conversely, the *Server receives my requests, What sends the Response? The *Client? doesn't this break the roles of each member a bit?

Update
I did a packet capture on an SIP Invite transaction between Ekiga and a PolyCom server. Ekiga was the client, and the polycom was the server. In the invite request Ekiga used port 5060 in the via header. 5060 is the port that its UAS is listening on, so that would seem to indicate that the UDPServer is receiving the responses to all requests and not the UDPClient that sent the request. Is this valid reasoning?

答:
On reading section 18 of RFC3261 about the transport layer, it quite clearly states that the transport layer must be able to receive responses for a transaction on each of

The TCP socket used for sending the request (TCPClient)

A new TCP connection to the address that the request was sent from and the port number as advertised in the 'sent-by' field of the 'Via' header (TCPServer on sending IP address)

A new TCP connection to where the UA is normally listening for new transactions (TCPServer)

An UDP datagram on the address that the request was sent from and the port number as advertised in the 'sent-by' field of the 'Via' header (UDPServer on sending IP address)

An UDP datagram where the UA is normally listening for new transactions (UDPServer)

So, basically only the UDPClient can't receive responses.

As for sending responses, when the request came in on a reliable transport (TCP), try to use the same socket for the response.
If that is not possible, open a new connection as if you are sending an entirely new message. That should give the least surprises.

Regarding the *Server and *Client roles: Usually, the Client sends requests and receives responses, while the server receives requests and sends responses. However, for UDP this model does not really work. There you might go for the model that the Client sends datagrams, while the server receives datagrams (independent of whether they are requests or responses).


问:
Preventing override of methods in Objective-C
Objective-C lacks private methods or java-esque final methods.  This means that it is possible for a subclass to (accidentally) override some of the internals of a superclass.

How does one prevent overriding methods in Objective-C?

答:
How does one prevent overriding methods in Objective-C?

You write in the documentation for your class something like:

Subclasses should not override this method.

Seriously. I copied that quote straight from the documentation for UIView.

Objective-C encourages a culture of doing by convention many things which would be enforced by a compiler in other languages, and this is one of those things. I'm sure you could play some games in with the runtime whereby you get the IMP for the method you're about to call and compare it to the IMP of your own class's method. But then, it's possible that someone might swizzle an is-a on you, or otherwise play their own games, and in the end it's usually best to just say "Please don't do that."


答:
There are several issues involved in this question.

Authentication (is this user who he says he is) should not be a concern of the View.

Authorization (Is the current user allowed to do this) is a concern of the View, because it can affect what gets presented to the user. Thus, the code for displaying an edit-button can be surrounded with a conditional like if model.userCanEdit() ... endif.

The determination of which authorization attributes a user has, that is business logic and should be placed in the Model. (For example that the 'edit' privilege requires you to have 2000 reputation; or that you must be the author or a moderator)


答:
If a view explicitly checks security to conditionally display UI elements, is it violating MVC by containing business logic?

Yes, it is a violation of MVC.

The view is there only to display elements, and the logic should be in the model. By having the view do something (in your case, check the security), you are placing the logic there.


问:
When to favor ASP.NET WebForms over MVC
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?

答:
My 2 cents is to always use ASP.NET MVC for new projects if you have the option.  In my opinion, webforms is not a good way to develop web apps, period.

I think abstracting away basic REST is bad, the entire postback model is bad, the way html/css is handed with a reliance on the GUI editor is bad, the emphasis on stuff like wizards and GUIs to set stuff up is bad, the URLs are bad.

Title: When to favor ASP.NET WebForms over MVC


问:
Reasons for removal of function types in Java 8
I have been trying to understand why the JDK 8 Lambda Expert Group (EG) decided not to include a new function type into the Java programming language.

Going over the mailing list I found a thread with the discussion about removal of function types.

Many of the statements are ambiguous to me, maybe because of the lack of context and in some cases because of my limited knowledge on the implementation of type systems.

However, there are a couple of questions that I believe I can safely formulate in this site to help me understand better what they meant.

I know I could ask the questions in the mailing list, but the thread is old and all decisions are already made, so chances are that I will be ignored, above all seeing that these guys are already getting delayed with their plans.

In his answer to support the removal of function types and endorse the use of SAM types, Brian Goetz says:

No reification.  There was a long thread about how useful it would be for  function types to be reified.  Without reification, function
types are hobbled.

I couldn't find the thread he mentions. Now, I can understand that the introduction of a structural function type may imply certain complications in the Java mostly nominal type system, what I cannot understand is how parametrized SAM types are different in terms of reification.

Aren't they both subject to the same reification problems? Does anyone understands how function types are different than parametrized SAM types in terms of reification?

In another comment Goetz says:

There are two basic approaches to typing: nominal and structural.  The  identity of a nominal is based on its name; the identity of a
structural type  is based on what it is composed of (such as "tuple of
int, int" or "function  from int to float".) Most languages pick
mostly nominal or mostly structural; there are not a lot of languages
that successfully mix nominal and structural typing except  "around
the edges."  Java is almost entirely nominal (with a few exceptions:
arrays are a structural type, but at the bottom there is always a
nominal  element type; generics have a mix of nominal and structural
too, and this is  in fact part of the source of many of people's
complaints about generics.) Grafting a structural type system
(function types) onto Java's nominal type  system means new complexity
and edge cases.  Is the benefit of function types  worth this?

Those of you with experience in the implementation of type systems. Do you know any examples of these complexities or edge cases that he mentions here?

Honestly I get confused by these allegations when I consider that a programming language like Scala, which is entirely based on the JVM, has support for structural types like functions and tuples, even with the reification problems of the underlying platform.

Don't get me wrong, I am not saying that a function type should be better than the SAM types. I just want to understand why they took this decision.

答:
The SAM approach is actually somewhat similar to what Scala (and C++11) do with anonymous functions (created with Scala's => operator or C++11's []() (lambda) syntax).

The first question to answer on the Java side is whether to have the return type of a lambda statement be a new primitve type, like int or byte, or an object type of some sort.  In Scala, there are no primitive types -- even an integer is an object of class Int -- and functions are no different, being objects of class Function1, Function2, and so forth, depending on the number of arguments the function takes.

C++11, ruby and python similarly have lambda expressions which return an object which is callable in explicit or implicit way.  The returned object has some standard method (such as #call which can be used to call it as a function.  C++11, for instance, uses a std::function type which overloads operator() so that calls of the object's call method even look like function calls, textually.  :-)

Where the new proposal for Java gets messy is in the use of structural typing to allow assigning such a method to another object, such as a Comparator which has a single main method with a different name.  While this is conceptually icky in some ways, it does mean that the resulting object can be passed to existing functions which take an object to represent a callback, a comparator, and so on, and expect to be able to call a well-defined single method such as #compare or #callback.  C++'s trick of overriding operator() neatly dodged this issue even before C++11, since all such callback options were callable the same way, and thus the STL required no adjustment to allow C++11 lambdas to be used with sort and so on.  Java, not having used a standard naming for such objects in the past (perhaps because no trick like operator overloading made a single approach obvious), isn't so lucky, so this hack prevents them from having to change a whole lot of existing APIs.


答:
I think that you have two different concept here. You have the email address of a recipient and an email message that will be sent to the recipient. So why not : </p>

```<code>private function _mail( $recipient )
{
    if( filter_var( $recipient, FILTER_VALIDATE_EMAIL ) ):
        $mail = new Zend_Mail();
        $mail->setSubject( $this->request->post('subject') )
            ->setBodyHtml( $this->request->post('message') )
            ->setFrom( $this->request->post('from') )
            ->addTo( $recipient )
            ->send();
    endif;
}
</code>```

Body:
I think that you have two different concept here. You have the email address of a recipient and an email message that will be sent to the recipient. So why not :

private function _mail( $recipient )
{
    if( filter_var( $recipient, FILTER_VALIDATE_EMAIL ) ):
        $mail = new Zend_Mail();
        $mail->setSubject( $this->request->post('subject') )
            ->setBodyHtml( $this->request->post('message') )
            ->setFrom( $this->request->post('from') )
            ->addTo( $recipient )
            ->send();
    endif;
}


问:
How do you interview someone with more experience than you?
The company I'm working for is looking to hire a senior developer with more experience than me, and they expect me to do the technical part of the interview. I've only been programming a few years and am not sure I have the knowledge needed to evaluate the coding skills of someone who has greater understanding/experience than I do.

Can anyone recommend some technical interview questions to ask that are a good means for evaluating higher-level programming skills, but still be ones I can understand?

I would say I'm past the jr. programmer level, but nowhere near senior. Most of what I've done is built small apps (web and desktop), some of them fairly complicated, but all of them have been meant to be used by no more then a handful of users. I feel I have a decent understanding of most programming concepts and am capable of learning/teaching myself just about anything, however I lack experience. As my boss is fond of telling me, "You don't know what you don't know".

In particular, things we'd like the person we hire to have experience with (that I don't have) is: Multi-tier development, multi-user environment, large-scale application development, two-way messaging, shared sessions, and Multi-threading/BackgroundWorkers.

UPDATE:

In response to Thor's comment below, we hired someone a few months ago and I think it has been working out great. I am learning a lot, not just about coding but also about things like design patterns, software architecture, documentation, and how other larger programming teams get stuff done. Its not always easy having someone come in and point out better ways to do things you have done, but if you can swallow your pride and be willing to try out new things you can learn a lot.

The interview process went better than I expected. I started asking questions about things I was familiar with, then asked some questions about some things I was struggling with. Whenever the interviewee said something I didn't understand, I'd ask them to explain it to me and then write it down so I could look it up later on. Overall, I felt I was able to get a pretty good idea of the applicant's skill level, intelligence, and what they'd be like to work with.

答:
You can't.

Instead, I would suggest you to come up in the interview with a list of problems you have today, and ask him how he would solve them.

This a is very interesting method for the following two reasons:

It is free consultancy. Even if you don't hire the guy, he may suggest nice solutions to your problems.

If he comes with interesting solutions, he is a problem solver. The kind of guy you want to hire.