答:
A thread pool is a group of pre-instantiated, idle threads which stand ready to be given work.  These are preferred over instantiating new threads for each task when there is a large number of short tasks to be done rather than a small number of long ones.  This prevents having to incur the overhead of creating a thread a large number of times.

Implementation will vary by environment, but in simplified terms, you need the following:

A way to create threads and hold them in an idle state.  This can be accomplished by having each thread wait at a barrier until the pool hands it work.  (This could be done with mutexes as well.)

A container to store the created threads, such as a queue or any other structure that has a way to add a thread to the pool and pull one out.

A standard interface or abstract class for the threads to use in doing work.  This might be an abstract class called Task with an execute() method that does the work and then returns.

When the thread pool is created, it will either instantiate a certain number of threads to make available or create new ones as needed depending on the needs of the implementation.

When the pool is handed a Task, it takes a thread from the container (or waits for one to become available if the container is empty), hands it a Task, and meets the barrier.  This causes the idle thread to resume execution, invoking the execute() method of the Task it was given.  Once execution is complete, the thread hands itself back to the pool to be put into the container for re-use and then meets its barrier, putting itself to sleep until the cycle repeats.

Title: What is a thread pool?


问:
Help identify the pattern for reacting on updates
There's an entity that gets updated from external sources. Update events are at random intervals. And the entity has to be processed once updated. Multiple updates may be multiplexed. In other words there's a need for the most current state of entity to be processed.

There's a point of no-return during processing where the current state (and the state is consistent i.e. no partial update is made) of entity is saved somewhere else and processing goes on independently of any arriving updates.

Every consequent set of updates has to trigger processing i.e. system should not forget about updates. And for each entity there should be no more than one running processing (before the point of no-return) i.e. the entity state should not be processed more than once.

So what I'm looking for is a pattern to cancel current processing before the point of no return or abandon processing results if an update arrives. The main challenge is to minimize race conditions and maintain integrity.

The entity sits mainly in database with some files on disk. And the system is in .NET with web-services and message queues.

What comes to my mind is a database queue-like table. An arriving update inserts row in that table and the processing is launched. The processing gathers necessary data before the point of no-return and once it reaches this barrier it looks into the queue table and checks whether there're more recent updates for the entity. If there are new updates the processing simply shuts down and its data is discarded. Otherwise the processing data is persisted and it goes beyond the point of no-return.

Though it looks like a solution to me it is not quite elegant and I believe this scenario may be supported by some sort of middleware.

If I would use message queues for this then there's a need to access the queue API in the point of no-return to check for the existence of new messages. And this approach also lacks elegance.

Is there a name for this pattern and an existing solution?

答:
The processing gathers necessary data before the point of no-return and once it reaches this barrier it looks into the queue table and checks whether there're more recent updates for the entity. If there are new updates the processing simply shuts down and its data is discarded. Otherwise the processing data is persisted and it goes beyond the point of no-return.

Depending on the frequency of updates received, the system can enter on periods of starvation - where the just-processed updates are discarded continuously because new ones are being received.

Instead of throwing away the computations, you can just keep an stack of the outputs generated.

Take a look at LMAX Architecture: http://martinfowler.com/articles/lmax.html

ContentLicense: CC BY-SA 3.0


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
```<code>print "hello world\n";
</code>```

and its derivations seems to be popular. :-)

ContentLicense: CC BY-SA 2.5

Body:
print "hello world\n";

and its derivations seems to be popular. :-)


问:
Multiple files in powershell
How to using multiple files in Powershell to ensure modularity?

function.ps1 could have all the utility functions?

command1.ps1 could have calls related to a command?

答:
Read up on how to write PowerShell Modules.

See also: https://stackoverflow.com/questions/5549516/run-a-powershell-script-from-another-one

Title: Multiple files in powershell


问:
Validation and Verification explanation (Boehm) - I cannot understand its point
Hopefully my last thread about V&V as I found the B.Boehm is text which I just do not understand well (likely my technical English is not that good).

http://csse.usc.edu/csse/TECHRPTS/1979/usccse79-501/usccse79-501.pdf

Basically he says that verification is about checking that products derived from requirements baseline must correspond to it and that deviation leads only to changes in these derived products (design, code). But he says it begins with design and ends with acceptance tests (you can check the V model inside).

The thing is, I have accepted ISO12207 in terms of all testing is validation, yet it does not make any sense here. In order to be sure the product complies with requirements (acceptance test) I need to test it. Also it says that validation problems means that requirements are bad and needs to be changed - which does not happen with testing that testers do, who just checks correspondence with requirements.

答:
According to Wikipedia,

It is sometimes said that validation can be expressed by the query "Are you building the right thing?" and verification by "Are you building it right?"

This means that validation is concerned with making sure that what you build is what the requirements describe, and verification is concerned with making sure that what you build is correct, robust, and possesses other nice "ilities".

Acceptance testing, therefore, is usually good to check for validation, but not verification. On the other hand, unit testing and integration testing, for example, are good to check for verification but usually not for validation.


问:
What triggered the popularity of lambda functions in modern mainstream programming languages?
In the last few years anonymous functions (AKA lambda functions) have become a very popular language construct and almost every major / mainstream programming language has introduced them or is planned to introduce them in an upcoming revision of the standard.

Yet, anonymous functions are a very old and very well-known concept in Mathematics and Computer Science (invented by the mathematician Alonzo Church around 1936, and used by the Lisp programming language since 1958, see e.g. here).

So why didn't today's mainstream programming languages (many of which originated 15 to 20 years ago) support lambda functions from the very beginning and only introduced them later?

And what triggered the massive adoption of anonymous functions in the last few years? Is there some specific event, new requirement or programming technique that started this phenomenon?

IMPORTANT NOTE

The focus of this question is the introduction of anonymous functions in modern, main-stream (and therefore, maybe with a few exceptions, non functional) languages.
Also, note that anonymous functions (blocks) are present in Smalltalk, which is not a functional language, and that normal named functions have been present even in procedural languages like C and Pascal for a long time.

Please do not overgeneralize your answers by speaking about "the adoption of the functional paradigm and its benefits", because this is not the topic of the question.

答: If may add my €0.02, although I would agree with the importance of JavaScript introducing the concept, I think more than concurrent programming I would blame the current fashion of asynchronous programming. When doing async calls (necessary with the webpages), simple anonymous functions are so obviously useful, that every web programmer (i.e., every programmer) had to get very familiar with the concept.</p>


问:
Filling array with numbers from given range so that sum of adjacent numbers is square number
Problem: Fill all the cells using distinct numbers from <1,25> set, so that sum of two adjacent cells is a square number.

(source: http://grymat.im.pwr.wroc.pl/etap1/zad1etp1213.pdf; numbers 20 and 13 have been given)

I've already solved this problem analytically and now I would like to approach it using an algorithm.

I would like to know how should I approach these kind of problems in general (not a solution, just a point for me to start).

答:
The key is to recognize that this is actually another problem- the Travelling Salesman.

Each number between 1-25 is a vertex. If x + y = square, then there is an edge between x and y. For n numbers, you can build this graph in O(n^2). Now visit each node so that no node is visited more than once. This is NP-Complete and the essence of TSP.

Once you recognize this variant, you can start by adapting solutions to TSP to your specific instance of it.


答:
To add some more confusion, ISO 12207:2008 does say that all testing activities are actually the validation.
IMHO it does not comply with this text as it states that validation problems are these when the specification needs to be changed.
I would disagree that verification is an acceptance test or maybe I misunderstood the article.

To sum it up:

If you follow the ISO, then you verify requirements are reflected in design, code or other documents. You validate it by actual testing to see if it does what is needed.

If you follow this document, then verification would be checking that all requirement refinements are corrects, and IMHO it would include testing as the acceptance test is explicitly mentioned.

Hope someone will correct me..

Title: Validation and Verification explanation (Boehm) - I cannot understand its point

Body:
Hopefully my last thread about V&V as I found the B.Boehm is text which I just do not understand well (likely my technical English is not that good).

http://csse.usc.edu/csse/TECHRPTS/1979/usccse79-501/usccse79-501.pdf

Basically he says that verification is about checking that products derived from requirements baseline must correspond to it and that deviation leads only to changes in these derived products (design, code). But he says it begins with design and ends with acceptance tests (you can check the V model inside).

The thing is, I have accepted ISO12207 in terms of all testing is validation, yet it does not make any sense here. In order to be sure the product complies with requirements (acceptance test) I need to test it. Also it says that validation problems means that requirements are bad and needs to be changed - which does not happen with testing that testers do, who just checks correspondence with requirements.


问:
Thin client Web browser?
Many times i have heard people saying that a particular hardware to be running a thin client web browser. But from the definition of "thin-client", doesnt all browser qualify as a thin-client? as all they do is rendering the information sent from a remote server minimizing the work at the browser end?</p>

答: Although all browsers indeed qualify to be a thin client, browsers running certain plug-ins also qualify to be a fat client. For example, if you have an Adobe Flash or a Microsoft Silverlight plugin, your browser can be programmed to run a thick client built on top of a given plugin.</p>

Title: Thin client Web browser?


问:
Compiled code spreadsheet-like cell management? (auto-updating)
Okay so I am fully aware how spreadsheets manage cells, they build dependency graphs where when one cell changes it tells all the other cells that are dependent on it that it changed. So they can from there update.

How they update I think involves either re-evaluating the formulas stored as strings, or re-evaluating the abstract syntax tree which I think is stored differently and might be faster. Something like that.

What I'm looking to do is manage a few variables in my code so I don't have to update them in the correct way, which would be a nightmare. But I also want it much faster than spreadsheets. And since I'm not looking for any functionality as great as are in these spreadsheets, I just figured from that thought point that there has to be a way to have a very fast implementation of this functionality. Especially since I don't have to modify cells after compiling unless that would be an option.

I'm very new to programming so I have no idea. One example might be to have a code-generator that generates code that does this for me. But I have no clue what the generated code would look like. Specifically, how exactly would variables inform others that they need to update, and what do those variables do to update?

I'm looking for any kind of ideas. Programming is not my job but nonetheless I was hoping to have some kind of system like this that would greatly help me with some stuff. Of course I have been programming plenty lately so I can still program. I just don't have the full scope on things.

I'm looking for any kind of ideas, thank you very much in advance!

Also, please help me with the tags. I know C# and Java mainly and I'm hoping to implement this in either of those languages and I'm hoping this can stay in those tags. Forcing this into some kind of spreadsheet tag wouldn't be accurate.

答:
Check out the Observer Pattern.

Some examples in here, and much more can be found with Google.


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答: Ward Cunningham</p>

Body: Ward Cunningham


问:
Can I implement the readers and writers algorithm in OpenMP by replacing counting semaphores with another feature?
After reading about OpenMP and not finding functions to support semaphores, I did an internet search for OpenMP and the readers and writers problem, but found no suitable matches.

Is there a general method for replacing counting semaphores in OpenMP with something that it supports?  Or is there just a gap in the environment where it does not permit things that are asymmetrical like the third readers and writers problem shown on the following page?

http://en.wikipedia.org/wiki/Readers-writers_problem#The_third_readers-writers_problem

答:
I found your question while looking for an answer myself. That being said, I found the following link: http://bisqwit.iki.fi/story/howto/openmp/

They have a section explaining how to use locks which seems very similar to mutex/semaphore.

Another tool for doing similar things is the critical sections directive even though I don't think it can be used for the reader writer problem because I think it will cause race condition.

Hope this was helpfull :D


问:
Where should I put a method that returns a list of active entries of a table?
I have a class named GuestbookEntry that maps to the properties that are in the database table named "guestbook". Very simple!

Originally, I had a static method named getActiveEntries() that retrieved an array of all GuestbookEntry objects. Each row in the guestbook table was an object that was added to that array. Then while learning how to properly design PHP classes, I learned some things:

Static methods are not desirable.

Separation of Concerns

Single Responsibility Principle

If the GuestbookEntry class should only be responsible for managing single guestbook entries then where should this getActiveEntries() method most properly go?

Update:

I am looking for an answer that complies with the SOLID acronym principles and allows for test-ability. That's why I want to stay away from static calls/standard functions.

DAO, repository, ...? Please explain as though your explanation will be part of "Where to Locate FOR DUMMIES"... :-)

答: Personally I'd go for a class, 'Guestbook',  that contains the array of GuestbookEntries and have the function as a member of that class.  The function can still return an array of entries as desired.</p>


问:
Verification as QA - makes sense?
Preparing my thesis, I found another interesting discrepancy. While some books say verification it terms of static analysis of work products is quality control (looking for defects), other say it is actually quality assurance because the process of checking is decreasing the probability of real defects when these deliverables will be used for product manufacture.
I hesitate as both seems to be correct: it is a way of checking for defects (deviation from requirements, design flaws etc.) so it looks like quality control, but also it is a process which does not have to be done and if done, can yield better quality.</p>

答:
Quality Control is the act of looking at products, aimed at detecting defects in individual products as they roll along the production line. Quality Assurance is about the processes implemented to ensure quality control is achieved - now and in the future. Therefore in the software world, the act of performing static analysis is QC, while the process that ensures the analyses is done (and measure how effective it is etc) is QA. (i.e. QA is the act of planing to do it, QC is the act of doing it)

The argument that the act of inspection is QA because it decreases the probably of a defect is flawed in my mind. That is like arguing something like "Using OOP is QA, as it decreases defects...."  Simply look at who performs the task. If it's a Quality Process person, it's likely to be QA. If it's a skilled engineer, it's likely to be QC. Inspection is certainly done by a skilled engineer - it's QC...

Within the software development community these terms are used loosely and interchanged randomly. In many Software houses Test is QA and QA is Test, even some books don't distinguish the difference - how do you expect the subtle difference between QA and QC will be understood.

Apart from the focus of the industry and lack of Quality training in general,  I believe this is largely the result of what software is. Unlike a factory, where each widget you product is a unique product (for instance - people understand how one car might have a defect that none others have), every software "widget" (i.e. what the customer gets) is exactly the same no matter if you product 2 or 2 billion of them. Therefore, Quality Control on software is only done 'once' (per release) - and is only subtly different to the QA process to most people.

Title: Verification as QA - makes sense?


答:
Anything to do with Hello World comes to mind. You could go with different variations if you plan on storing multiple languages.

For something more non-trivial, there's Fibbonacci.

Title: What are some famous one-liner or two-liner programs and equations?

Body:
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!


问:
Is it bad style to redundantly check a condition?
I often get to positions in my code where I find myself checking a specific condition over and over again.

I want to give you a small example: suppose there is a text file which contains lines starting with "a", lines starting with "b" and other lines and I actually only want to work with the first two sort of lines. My code would look something like this (using python, but read it as pseudocode):

```<code># ...
clear_lines() # removes every other line than those starting with "a" or "b"
for line in lines:
    if (line.startsWith("a")):
        # do stuff
    elif (line.startsWith("b")):
        # magic
    else:
        # this else is redundant, I already made sure there is no else-case
        # by using clear_lines()
# ...
</code>```

You can imagine I won't only check this condition here, but maybe also in other functions and so on.

Do you think of it as noise or does it add some value to my code?

答:
You actually don't need the clear_lines() at the start. If the line is neither "a" or "b", the conditionals simply won't trigger. If you want to get rid of those lines then make the else into a clear_line(). As it stands you are doing two passes through your document. If you skip the clear_lines() at the beginning and do it as part of the foreach loop then you cut your processing time in half.

It's not only bad style, it's bad computationally.


答:
You can raise an exception in else case. This way it's not redundant. Exceptions aren things that aren't supposed to happen but are checked anyway.

```<code>clear_lines() # removes every other line than those starting with "a" or "b"
for line in lines:
    if (line.startsWith("a)):
        # do stuff
    if (line.startsWith("b")):
        # magic
    else:
        throw BadLineException
# ...
</code>```

Title: Is it bad style to redundantly check a condition?

Body:
I often get to positions in my code where I find myself checking a specific condition over and over again.

I want to give you a small example: suppose there is a text file which contains lines starting with "a", lines starting with "b" and other lines and I actually only want to work with the first two sort of lines. My code would look something like this (using python, but read it as pseudocode):

```<code># ...
clear_lines() # removes every other line than those starting with "a" or "b"
for line in lines:
    if (line.startsWith("a")):
        # do stuff
    elif (line.startsWith("b")):
        # magic
    else:
        # this else is redundant, I already made sure there is no else-case
        # by using clear_lines()
# ...
</code>```

You can imagine I won't only check this condition here, but maybe also in other functions and so on.

Do you think of it as noise or does it add some value to my code?

Body:
You can raise an exception in else case. This way it's not redundant. Exceptions aren things that aren't supposed to happen but are checked anyway.

clear_lines() # removes every other line than those starting with "a" or "b"
for line in lines:
    if (line.startsWith("a)):
        # do stuff
    if (line.startsWith("b")):
        # magic
    else:
        throw BadLineException
# ...


问:
Will it be okay to use Amazon Glacier for everyday data retrieval?
I am planning to use cloud storage for my app.  What my app will do is retrieval of users data and user authentication and have the ability to sync data continuously.

Is it a good idea to use Amazon Glacier?  Is there a bandwidth limitation or request or any downside of using it?

答:
Glacier is an archiving service.  According to their site "Amazon Glacier is optimized for data that is infrequently accessed and for which retrieval times of several hours are suitable".  It's meant for data that you don't want to throw away but don't need to access regularly.

To draw a metaphor with paper documents.  If the paper on your desk is RAM, the filing cabinet in your office is your HDD, the departmental records room is Amazon S3, the offsite record archival that takes a week to requisition a box of files is Glacier.


答: The use case you describe sounds like a better fit for Amazon S3. Amazon Glacier is designed for long term archives, rarely read and not required immediately.</p>

Title: Will it be okay to use Amazon Glacier for everyday data retrieval?

Body:
I am planning to use cloud storage for my app.  What my app will do is retrieval of users data and user authentication and have the ability to sync data continuously.

Is it a good idea to use Amazon Glacier?  Is there a bandwidth limitation or request or any downside of using it?


问:
Is there an open source license with proprietairy-like terms?
Is there any license meeting the following criteria:

source code available (users allowed to browse the source)

users are allowed to modify the code with credits to the original author

not allowed to sell the software itself or any other program using code from it

can be sold by original author

答:
For starters, the original author doesn't need a license to do anything with the program.  They own it outright, including it in your requirements just complicates the issue.

With that out of the way, you're not looking for an "open source" license, just a source license.  Lots of 'enterprise' software is distributed this way, allowing for site-specific customization to the software.  You'll see licenses that authorize "research and personal use only" but explicitly denying redistribution rights.  Early versions of Unix were basically distributed this way.

What you're asking for isn't novel or new but there aren't exactly standard, public licenses floating around that say what you want.  Time to lawyer up and write your own.


答:
Conditional operator :

minVal = (a < b) ? a : b;

Switch case

for-each loop [Java]


答:
I recently had to implement a firmware programmer using the Motorola S-record format, very similar to what you describe.  Since we had some time pressure, my first draft ignored redundancies and made simplifications based on the subset I actually needed to use in my application.  It passed my tests easily, but failed hard as soon as someone else tried it.  There was no clue what the problem was.  It got all the way through but failed at the end.

So I had no choice but to implement all the redundant checks, in order to narrow down where the issue was.  After that, it took me around two seconds to find the issue.

It took me maybe two hours extra to do it the right way, but wasted a day of other people's time as well in troubleshooting.  It's very rare that a few processor cycles are worth a day of wasted troubleshooting.

That being said, where reading files are concerned, it's often beneficial to design your software to work with reading it and processing it one line at a time, rather than reading the entire file into memory and processing it in memory.  That way it will still work on very large files.


问:
Should you ever re-estimate user stories?
My current project is having a 'discussion' which is split down the middle- "this story is more complex than we originally thought, we should re-estimate" vs "you should never re-estimate as you only ever estimate up and never down".

Can anyone shed some light on whether you ever should re-estimate?

IMHO I'd imagine you could bring up an entirely new card for a new requirement or story, but going back and re-estimating on backlog items seems to skew the concept of relative sizing and will only ever 'inflate' your backlog.

答:
There is no problem re-estimating backlog items, up or down. Development is a learning process, so it's expected that some future backlog items became simpler or more complex depending on the knowledge gained in past sprints.

Maybe the 'velocity' (if used by the team/company as a metric) could not be exactly measured in the event of a huge re-estimation, but the most important thing is that re-estimation exercises would sharp the team own estimates in future. The key to be predictable is to use the most update information, not restrained to an early estimate.


答:
This is an excedingly common practice and the way of dealing with it is via higher-order filters.

Essentially, you pass a function to the filter method, along with the list/sequence that you want to filter against and the resulting list/sequence contains only those elements that you want.

I'm unfamiliar with python syntax (though, it does contain such a function as seen in the link above), but in c#/f# it looks like this:

c#:

```<code>var linesWithAB = lines.Where(l => l.StartsWith("a") || l.StartsWith("b"));
foreach (var line in linesWithAB)
{
    /* line is guaranteed to ONLY start with a or b */
}
</code>```

f# (assumes ienumerable, otherwise List.filter would be used):

```<code>let linesWithAB = lines
    |> Seq.filter (fun l -> l.StartsWith("a") || l.StartsWith("b"))

for line in linesWithAB do
    /* line is guaranteed to ONLY start with a or b */
</code>```

So, to be clear: if you use tried and tested code/patterns, it is bad style. That, and mutating the list in-memory the way you appear to via clear_lines() loses you thread safety and any hopes of parallelism that you could have had.

Body:
This is an excedingly common practice and the way of dealing with it is via higher-order filters.

Essentially, you pass a function to the filter method, along with the list/sequence that you want to filter against and the resulting list/sequence contains only those elements that you want.

I'm unfamiliar with python syntax (though, it does contain such a function as seen in the link above), but in c#/f# it looks like this:

c#:

var linesWithAB = lines.Where(l => l.StartsWith("a") || l.StartsWith("b"));
foreach (var line in linesWithAB)
{
    /* line is guaranteed to ONLY start with a or b */
}

f# (assumes ienumerable, otherwise List.filter would be used):

let linesWithAB = lines
    |> Seq.filter (fun l -> l.StartsWith("a") || l.StartsWith("b"))

for line in linesWithAB do
    /* line is guaranteed to ONLY start with a or b */

So, to be clear: if you use tried and tested code/patterns, it is bad style. That, and mutating the list in-memory the way you appear to via clear_lines() loses you thread safety and any hopes of parallelism that you could have had.


问:
what kind of certificate needed for my application ?
I am releasing free C# softwares I've created using Visual Studio.
In the future, some of these softwares might become Paid.
I was wondering if I need to purchase any kind of license for them ?

I understand that it's good to have a certificate for your website (SSL?), if your trying to sell your software but what about your applications ?

I just don't want anti-virus/browsers flagging my application as not trusted.
Any suggestion is appreciated.

答:
It sounds like what need is to have your programs digitally signed (i.e. Code Signing). This is similar in concept to an SSL certificate, in that it proves that the program is from whomever the certificate was issued to & has not been modified (e.g. malicious code added).

The key to understanding Code Signing though, is that the certificates are seperate from SSL certificates - they're specifically called code signing certificates.

I've used VeriSign in the past when going through the Microsoft Logo Certification program, but found that their certificates are much more expensive than those available from GoDaddy or Comodo.

Edit

Also, there's an article on MSDN: Introduction to Code Signing that you may find useful too.


问:
Should a developer create test cases and then run through test cases?
I work for a company where the development manager expects a developer to create test cases before writing any code.  These test cases have to then be maintained by the developers.  Every-so-often a developer will be expected to run through the test cases.

From this you should be able to gather that the company in question is rather small and there are no testers.

Coming from a Software Architect position and having to write / execute test cases wearing my 'tester' hat is somewhat of a shock to the system.  I do it anyway but it does seem to be a rather expensive exercise :)

EDIT:

I seem to need to elaborate here:  I am not talking about unit-testing, TDD, etc. :)

I am talking about that bit of testing a tester does.  Once I have developed a system (with my unit tests / tdd / etc.) the software goes through a testing phase.  Should a developer be that tester and developer those test cases?

I think the misunderstanding may stem from the fact that developers, typically, are not involved with this type of testing and, therefore, assumed I am referring to that testing we do do: unit testing.  But alas, no.

I hope that clears it up.

答:
Sure. A developer should create test cases and then run through test cases.

Before the development community was convinced of the benefits, some
  people thought that unit tests were a waste of time. Some developers
  thought that their job was to write production code, so spending time
  on unit tests, which aren't production code, wasn't what they were
  being paid for.

These days, most professional developers know that unit tests are an
  important part of writing production code. It means you deliver better
  quality code and it makes jobs like refactoring or adding new features
  easier.

The research team found was that the TDD teams produced code that was
  60 to 90 percent better in terms of defect density than non-TDD teams
  - via Phil Haack.

If your code isn't covered by unit tests, it is legacy code.

From  http://www.enhance-php.com/Content/About-Unit-Testing/

EDIT:

Should a developer be that tester?

Yes, developer can test the Unit Test part.

But for other tests, for example, acceptance test, regression test you should have professional and dedicated tester.


问:
How get and set accessors work
The standard method of implementing get and set accessors in C# and VB.NET is to use a public property to set and retrieve the value of a corresponding private variable.  Am I right in saying that this has no effect of different instances of a variable?  By this I mean, if there are different instantiations of an object, then those instances and their properties are completely independent right?  So I think my understanding is correct that setting a private variable is just a construct to be able to implement the get and set pattern?  Never been 100% sure about this.</p>

答:
OK sorry - on  re-reading my question wasn't 100% clear, so here's the combined explanation on use of get/set to help others who want to know the rationale of using this pattern (thanks PDR - I've upvoted your response which was the most useful in constructing this explanation):

the get/set pattern in object oriented programming (including in .NET), is a pattern that looks like this (in VB.Net):

```<code>Private _Organisation As String
Public Property Organisation() As String
    Get
        Return _Organisation
    End Get
    Set(ByVal value As String)
        _Organisation = value
    End Set
End Property
</code>```

The get/set pattern is used as a pattern that provides a structure that allows logic to be added during the setting or retrieval of a property instance of an instantiated class, which can be useful in various programming scenarios.

If this pattern is implemented but no logic is actually performed in the 'get' or 'set' methods, the pattern can add unnecessary code which can constitute 'over engineering'.  It's not a requirement for all properties to use the get/set pattern

A property can have a 'get' accessor only, which is done in order to make that property read-only

When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted.  The intermediate variable is usually prefixed with an underscore.

this intermediate variable should be made private in order to ensure that it can only be accessed via its get/set calls and therefore more loosely coupled in the application (see the answer to this question from 'pdr' for more details)

The intermediate variable is simply a technique that must be used when implementing a get/set pattern.  Setting this intermediate variable has no effect on 'protecting' the variable across different instantiations of the objects- instances of an object and their property values are completely independent

Title: How get and set accessors work

Body:
OK sorry - on  re-reading my question wasn't 100% clear, so here's the combined explanation on use of get/set to help others who want to know the rationale of using this pattern (thanks PDR - I've upvoted your response which was the most useful in constructing this explanation):

the get/set pattern in object oriented programming (including in .NET), is a pattern that looks like this (in VB.Net):

Private _Organisation As String
Public Property Organisation() As String
    Get
        Return _Organisation
    End Get
    Set(ByVal value As String)
        _Organisation = value
    End Set
End Property

The get/set pattern is used as a pattern that provides a structure that allows logic to be added during the setting or retrieval of a property instance of an instantiated class, which can be useful in various programming scenarios.

If this pattern is implemented but no logic is actually performed in the 'get' or 'set' methods, the pattern can add unnecessary code which can constitute 'over engineering'.  It's not a requirement for all properties to use the get/set pattern

A property can have a 'get' accessor only, which is done in order to make that property read-only

When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted.  The intermediate variable is usually prefixed with an underscore.

this intermediate variable should be made private in order to ensure that it can only be accessed via its get/set calls and therefore more loosely coupled in the application (see the answer to this question from 'pdr' for more details)

The intermediate variable is simply a technique that must be used when implementing a get/set pattern.  Setting this intermediate variable has no effect on 'protecting' the variable across different instantiations of the objects- instances of an object and their property values are completely independent


问:
Gerrit code review, or Github's fork and pull model?
I am starting a software project that will be team AND community developed. I was previously sold on gerrit, but now Github's fork and pull request model seem to almost provide more tools, ways to visualize commits, and ease of use.

For someone who has at least a little experience with both, what are the pros/cons of each, and which would be better for a team based project which wants to leave open the possibility for community development?

答:
The major difference between Gerrit's and GitHub's workflows are how changes are modeled.

In Gerrit, every commit is a change that stands on its own. Although Gerrit will show you the relationships between commits, reviews are performed on a per-commit basis. Teams that are good at breaking large changes down into small, self-contained commits are likely to have more success with Gerrit. However, since Gerrit's model includes successive revisions to a particular commit it encourages Git workflows that many developers are not accustomed to, such as amending an earlier commit and re-pushing it, or squashing a growing set of commits from a topic branch into a single commit.

In Github, a pull request models a relationship between two branches. The expected workflow on Github is to commit one or more changes into a topic branch (often in a fork of the repository, but not necessarily) and create a pull request between that branch and the "upstream" branch. In this case, what is being reviewed is a set of commits that continues to grow as the review continues. The result is a set of changes that can then be merged atomically when they are complete. Pull requests can be effective at tracking changes with a larger scope that may be implemented over multiple commits. Pull requests also support SCM workflows that more developers are accustomed to, such as responding to a review comment by submitting a follow-up commit in the same branch.

A big advantage in Github's favor is the number of developers that are familiar with it compared to Gerrit. Gerrit can be popular with Git power-users, but friction-free use of it requires intermediate or advanced git knowledge, and tolerance of a steep learning curve.

Gerrit's advantage is a deeper relationship with Git. Github Pull Requests are far enough removed from Git's standard data model that one must use either Github's web UI or its proprietary API to create pull requests. Gerrit's interface for creating and updating changes is the git protocol itself.


问:
What is the most reliable session storage in PHP: Memcache, database or files?
What is the best and most safest way to handle PHP sessions. Is the best way to store sessions in:

Database (more reliable, but high bottleneck, slow speed, not good for high database usage websites)?

Memcache (super fast, but distributed more security problems, chances of loosing data when the server restarted and chances of loosing data when the cache is full)?

Files (default option, I guess slow since it reads and writes from file I/O, less security, etc).

Which method is the best? What are the problems and good things of each of those approaches?

答:
It depends on your needs.

There are some differences between files and database storage. See this question.

However, you can do what's done in Rails 3 by default, and use only encrypted cookies for your session. So you encrypt all values in a way that only you can decrypt it later (e.g. private/public keys), and you let the client do the state keeping for you.

On the one hand it limits you to 4Kb, which is actually usually enough (since you usually want to store IDs, not whole objects), but the really nice benefit you get is that you don't need to worry about session cleanup. You leave that up to the client, where it actually should be.


答:
I also work at a company where most teams have no dedicated testing/QA function. We prefer to describe it as quality is everyone's responsibility: making sure the code you write does what it is intended to do is never someone else's problem. Writing and executing manual test plans is not mandated as a solution, but quality software is expected and teams must find some way to achieve that.

The intended effect of this organizational style in my organization was to make everyone act responsibly in the short term and to encourage innovative approaches to quality in the longer term. Many teams started off dedicating a day out of each sprint to manual testing. After a while, more teams began to do more thorough code review and design review, and some teams have automated all or part of their pre-release smoke tests to reduce the time spent testing and to reduce the risk of error.

You're right that dedicating engineer and architect time to repetitive manual testing is a pretty costly approach, but it has the effect of making those producing the code feel the impact of their mistakes and, given the right sort of team, can encourage a deeper understanding of the full path of a change from brain to production, rather than an attitude of just "throwing code over the wall" for QA and operations teams to deal with.

Title: Should a developer create test cases and then run through test cases?

Body:
I work for a company where the development manager expects a developer to create test cases before writing any code.  These test cases have to then be maintained by the developers.  Every-so-often a developer will be expected to run through the test cases.

From this you should be able to gather that the company in question is rather small and there are no testers.

Coming from a Software Architect position and having to write / execute test cases wearing my 'tester' hat is somewhat of a shock to the system.  I do it anyway but it does seem to be a rather expensive exercise :)

EDIT:

I seem to need to elaborate here:  I am not talking about unit-testing, TDD, etc. :)

I am talking about that bit of testing a tester does.  Once I have developed a system (with my unit tests / tdd / etc.) the software goes through a testing phase.  Should a developer be that tester and developer those test cases?

I think the misunderstanding may stem from the fact that developers, typically, are not involved with this type of testing and, therefore, assumed I am referring to that testing we do do: unit testing.  But alas, no.

I hope that clears it up.


答:
I do not see a big problem per se in the process you describe. True, dedicated testers traditionally have more experience in designing such test cases, but then again, if your developers do that regularly this won't matter.

However, there is something to be said about being blind to your own faults. Testing your own stuff means you already have an established mindset on whatever it is you test, simply because you developed it. A separate tester will add a fresh perspective and is much more likely to find problems f.ex. in the usability area.

The one major drawback that has not been mentioned before is that you may not be allowed to do so in some projects, depending on the standards you have to adhere to. Several SW development standards explicitly forbid testing your own stuff (not in the TDD sense, but in terms of validation/acceptance testing). In such cases, testing your own work most likely is a breach of the project's contract.


问:
Why do browsers leak memory?
A colleague and I were speaking about browsers (using a browser control object in a project), and it appears as plain as day that all browsers (Firefox, Chrome, IE, Opera) display the same characteristic or side-effect from their usage and that being 'Leaking Memory'.

Can someone explain why that is the case? Surely as with any form of code, there should be proper garbage collection?

PS. I've read about some defensive patterns on why this can happen from a developer's perspective. I am aware of an article Crockford wrote on IE; but why is the problem symptomatic of every browser?
Thanks

答:
Here is the best answer I found on the 'Net, Memory Leakage in Internet Explorer - revisited, and a snippet to explain why:

The above pattern will leak due to the circular reference created
  between a DOM node and a JS element.

Since the JScript garbage collector is a mark and sweep GC, you may
  think that it would handle circular references. And in fact it does.
  However this circular reference is between the DOM and JS worlds. DOM
  and JS have separate garbage collectors. Therefore they cannot clean
  up memory in situations like the above.

Title: Why do browsers leak memory?


答:
What you are describing is a test plan or test case.  Ideally you would have an independent QA specialist that would create and possibly run these test cases.

However, given the small size of your company/team, having the developer create a test plan from the requirements prior to creating the code is the next best thing.

By creating the test case at this point in the process you have less knowledge about the solution and would ideally write a better test case.

I am not a big fan of this method though.  If the company/organization doesn't want to spring for dedicated QA, then a possible improvement in the process would be to have a peer write and run the test case.


答:
I'm a big fan of independence at the Testing stage:

An architect has a vested interest in showing his specification is correct

A developer has a vested interest in finding all the non-conformances

But

A developer has a vested interest in making sure his own code passes the test

A tester has a vested interest in finding all the non-conformances

Yes, a single individual can do all roles - and this is commonly happens, especially in small teams and small companies. But you cannot beat independence.

But if you are having to fulfill multiple roles, please wear the hat for the job, not with any other hat :)


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
I see Conway's Game of Life in APL floating around a lot:

An extra bonus is that this will make sure you're handling unicode correctly.


问:
Combining Ruby and C++
I've been discussing a conceptual project with a friend of mine and the the most effective way we've seen of doing it is writing the engine in C++ while the logic would be done in Ruby.

However, we would need data to be passed around often, for example:

Engine reports that A happened, that gets triggered in a proc array (event "A" is passed but proc doesnt use it)

Ruby decides that we need to wait for B to happen

Ruby adds a proc to an array. The array of procs is iterated during each cycle in the C++ engine

C++ engine reports that B happened and passes "event B (should be a Ruby object)

Ruby receives event B and decides what to do next

I don't work with multiple languages often, and was wondering if it's possible to implement things in this way. I know that there's the ruby VALUE in C++, but what is the standard way of combining the two? Of course I know Ruby follows the Perl "more than 1 way to do it", but there's often a standardized way.

I ran a quick test with SWIG but quickly ran into a problem. From what I can see, Ruby (1.9.3p286, though it uses the 1.9.1 gems afaik) can't load the shared object. Here's the code, actions done and more information.

I tried compiling to the latest Ruby and SWIG version to see if maybe it was some compile error upstream. I got no errors and the problem remains. Seems it might be an incompatibility between these SWIG and Ruby versions... or a problem with the current Ruby version.

答:
Swig is the way to go. The data passing is also possible there in my understanding with typemaps. Have a look at it.

Also look at some helpful links below

Extending Ruby

rice (Github)

Ruby extention with C

Title: Combining Ruby and C++


答:
There are 4 places a browser can leak memory:

The web page

In modern browsers this is fully up to the web developer. Garbage-collected environments don't collect memory that is still being referenced to, and there are a lot of ways to keep referencing memory without meaning to (e.g. create a closure to attach as an event handler and accidentally include a bunch of variables in that closure's scope). A web developer can solve these leaks completely by properly handling variable references in their code. A page reload typically frees up the memory.

Add-ons

If add-ons are also written in a garbage-collected language (like javascript), then they suffer from the same issue. However a page reload will typically not free up this memory, so it appears as if the browser is leaking memory whereas it's actually the add-on developer's fault. To my knowledge this is the biggest cause of browser leaks (which is why the default recommendation is to test whether the leak occurs without add-ons).

Browser engine

All modern browser engines are written in C++. C++ is not garbage-collected, but uses explicit memory allocation instead. If developers allocate memory and then forget to deallocate it, the engine leaks memory. To my knowledge all the browser makers do a lot of testing and code review to find and solve these kinds of leaks. It's not 100% fixed, and never will be, but it's not a huge problem anymore.

Non-leaks

Finally there are a range of caching features that mean the browser's process will grow in scope while using it. These aren't leaks, they're intended to optimally make use of available RAM. Typically the memory footprint grows to a maximum and then hovers there.

Title: Why do browsers leak memory?

Body:
A colleague and I were speaking about browsers (using a browser control object in a project), and it appears as plain as day that all browsers (Firefox, Chrome, IE, Opera) display the same characteristic or side-effect from their usage and that being 'Leaking Memory'.

Can someone explain why that is the case? Surely as with any form of code, there should be proper garbage collection?

PS. I've read about some defensive patterns on why this can happen from a developer's perspective. I am aware of an article Crockford wrote on IE; but why is the problem symptomatic of every browser?
Thanks


答:
The best is to store at Memcached as we can easily resolve the other issues
(cache size, security, etc.)

facebook is the #1 consumer of memcached. Please
  read if interested:
  http://www.facebook.com/note.php?note_id=39391378919

How to resolve the other issues?

https://stackoverflow.com/questions/235470/how-to-effectively-implement-sessions-in-gae

http://bakery.cakephp.org/articles/rynop/2010/09/10/using-memcached-to-run-your-sessions

https://groups.google.com/forum/?fromgroups=#!topic/web2py/lDQspjf0RIk

Title: What is the most reliable session storage in PHP: Memcache, database or files?

Body:
What is the best and most safest way to handle PHP sessions. Is the best way to store sessions in:

Database (more reliable, but high bottleneck, slow speed, not good for high database usage websites)?

Memcache (super fast, but distributed more security problems, chances of loosing data when the server restarted and chances of loosing data when the cache is full)?

Files (default option, I guess slow since it reads and writes from file I/O, less security, etc).

Which method is the best? What are the problems and good things of each of those approaches?


问:
Graphically intensive silverlight design
I'm designing a silverlight application for showing sheet music from a midi file.

I want to create a horizontally scrolling musical staff.

At my job I maintain a winforms application that is a scrolling Gantt chart of airplane schedules, and it basically has a rows collection, and it maps the left-most pixel and right-most pixels of the control to datetimes. Then the paint method loops through what it determines will be the visible rows, and draws a screen that shows the schedule information between the two dates.

Would I be correct in assuming that I would need to something similar in silverlight for my sheetmusic, or would it be better to just create a horizontal scrollviewer containing a canvas that I have drawn programmaticially on.

Am I headed in the right direction? I havent seen any articles on designing such a custom control: can you point me at any?

答:
It think your second idea - that of a horizontal scroll viewer is the "better" one.

With Silverlight, unless you get into the really low level drawing of 3D elements, you don't need (or indeed have) the same concept as a "paint" method.

It might even be worth looking at a horizontal StackPanel with a background image of the staves. Then each element in the panel could be a note (or a collection of notes) that would draw themselves.


答:
In design by contract, one guesses each function must do its job as described in its documentation. So, each function has a list of pre-conditions, that is, conditions on the function's inputs as well as post-conditions, that is, conditions of the function's output.

The function must guarantee to its clients that, if the inputs respect the pre-conditions, then the output will be as described by the post-conditions. If at least one of the pre-conditions is not respected, the function can do what it wants (crash, return any result, ...). Therefore pre and post-conditions are a semantic description of the function.

Thanks to contract, a function is sure its clients use it correctly and a client is sure the function does its job correctly.

Some languages handle contracts natively or through a dedicated framework. For the others, the best is to check the pre and post-conditions thanks to asserts, as @Lattyware said. But I would not call that defensive programming, since in my mind this concept is more focused on the protection against the (human) user's inputs.

If you exploit contracts, you can avoid the redundantly checked condition since either the called function perfectly works and you don't need the double check, or the called function is dysfunctional and the calling function can behave as it wants.

The harder part is then to define which function is responsible of what, and to strictly document these roles.


问:
PyQt application architecture
I'm trying to give a sound structure to a PyQt application that implements a card game. So far I have the following classes:

Ui_Game: this describes the ui of course and is responsible of
reacting to the events emitted by my CardWidget instances

MainController: this is responsible for managing the whole
application: setup and all the subsequent states of the application
(like starting a new hand, displaying the notification of state
changes on the ui or ending the game)

GameEngine: this is a set of classes that implement the whole game
logic

Now, the way I concretely coded this in Python is the following:

```<code>class CardWidget(QtGui.QLabel):
    def __init__(self, filename, *args, **kwargs):
        QtGui.QLabel.__init__(self, *args, **kwargs)
        self.setPixmap(QtGui.QPixmap(':/res/res/' + filename))

    def mouseReleaseEvent(self, ev):
        self.emit(QtCore.SIGNAL('card_clicked'), self)

class Ui_Game(QtGui.QWidget):
    def __init__(self, window, *args, **kwargs):
        QtGui.QWidget.__init__(self, *args, **kwargs)
        self.setupUi(window)
        self.controller = None

    def place_card(self, card):
        cards_on_table = self.played_cards.count() + 1
        print cards_on_table

        if cards_on_table <= 2:
            self.played_cards.addWidget(card)
            if cards_on_table == 2:
                self.controller.play_hand()

class MainController(object):
    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)
        self.window = QtGui.QMainWindow()
        self.ui = Ui_Game(self.window)
        self.ui.controller = self
        self.game_setup()
</code>```

Is there a better way other than injecting the controller into the Ui_Game class in the Ui_Game.controller? Or am I totally off-road?

答:
I would say you should do the contrary, a good design would be for your application to be able to run whatever its context is. That's why for every application I code, I create a CLI tool that implements the logic, and then I implement a GUI. Where am I heading to ?

You're creating a MainController object that holds the world, and then modifies the Ui_Game object to give back a reference to itself. That's not elegant, and given your context that's not the best way.

If you really want to go this way you should instead do the following:

```<code>class Ui_Game(QtGui.QWidget):
    def __init__(self, controller, *args, **kwargs):
        QtGui.QWidget.__init__(self, *args, **kwargs)
        self.setupUi(controller.window)
        self.controller = controller

[...]

Ui_Game(self)
</code>```

That's for the elegancy.

But for your context, I'd advise you to totally separate the game logic from the UI logic, and thus have some start or main function that initializes all your objects, and bind them together. Also, you create a widget that seems to populate itself inside the window, whereas the widget shall not know where it will be used. So here something close to what I'd do:

```<code>class GameGUI:
    def __init__(self, game):
        # so you can give all your UI elements a game to play with
        self.game = game
        # start and populate the Ui_Game stuff
        self.app = QtGui.QApplication(sys.argv)

    def main_loop(self):
        # wait for the UI to cease
        return self.app._exec()

def start():
    # here you can argparse your CLI arguments, so you can choose
    # your interface (readline, ncurses, Qt, web, whatever...?)
    # and setup your application (logfile, port to bind to, look
    # of the GUI...)
    game = MyGame()
    game.setup()
    return GameGUI(game).main_loop()

import sys
if __name__ == "__main__":
    sys.exit(start())
</code>```

So, now the flow is more limpid:

you start in the start() function, which will prepare the environment for your application to run correctly

check arguments if any,

initializes the Game,

give it to the GUI,

build the GUI (through GameGUI that will create the windows and the widgets)

run the GUI (through main_loop())

Always remember that OOP is all about decoupling.

HTH

Title: PyQt application architecture

Body:
I would say you should do the contrary, a good design would be for your application to be able to run whatever its context is. That's why for every application I code, I create a CLI tool that implements the logic, and then I implement a GUI. Where am I heading to ?

You're creating a MainController object that holds the world, and then modifies the Ui_Game object to give back a reference to itself. That's not elegant, and given your context that's not the best way.

If you really want to go this way you should instead do the following:

class Ui_Game(QtGui.QWidget):
    def __init__(self, controller, *args, **kwargs):
        QtGui.QWidget.__init__(self, *args, **kwargs)
        self.setupUi(controller.window)
        self.controller = controller

[...]

Ui_Game(self)

That's for the elegancy.

But for your context, I'd advise you to totally separate the game logic from the UI logic, and thus have some start or main function that initializes all your objects, and bind them together. Also, you create a widget that seems to populate itself inside the window, whereas the widget shall not know where it will be used. So here something close to what I'd do:

class GameGUI:
    def __init__(self, game):
        # so you can give all your UI elements a game to play with
        self.game = game
        # start and populate the Ui_Game stuff
        self.app = QtGui.QApplication(sys.argv)

    def main_loop(self):
        # wait for the UI to cease
        return self.app._exec()

def start():
    # here you can argparse your CLI arguments, so you can choose
    # your interface (readline, ncurses, Qt, web, whatever...?)
    # and setup your application (logfile, port to bind to, look
    # of the GUI...)
    game = MyGame()
    game.setup()
    return GameGUI(game).main_loop()

import sys
if __name__ == "__main__":
    sys.exit(start())

So, now the flow is more limpid:

you start in the start() function, which will prepare the environment for your application to run correctly

check arguments if any,

initializes the Game,

give it to the GUI,

build the GUI (through GameGUI that will create the windows and the widgets)

run the GUI (through main_loop())

Always remember that OOP is all about decoupling.

HTH


问:
keeping connection open all time in sql
I have developed a Windows application in c# in which multiple users can add some numbers and their name and can view the data entered. The problem that I have is that the sever is on my laptop and every time I log off or close my laptop, they are losing connection to the DB and can not add or view any more.

It seems that the port is closed or something. Is there a way to keep the port and their connection established all the time even when I'm logging out?

答:
Very probably, the SQL database engine is running from your own local account; when you log off, all the processes running from this account are stopped, including the database engine.

Instead, the database engine should be run using either Local Service or Network Service account, or a dedicated account which will never be logged off. Those accounts are for example used by many Windows Services, which allow them to remain active when there are no active users, and do some tasks on the background, like defragmenting the disks.

This being said and other people have pointed it out, you shouldn't run a database used by other people on your laptop, but use a server instead.

Even if you have a very basic needs (no SLA needed, frequent downtime is acceptable, data loss acceptable, etc.) and don't need real server-level infrastructure with redundancy, backup power, etc., running a database used by several people is rather strange. If you don't need anything provided by real server hardware and infrastructure, then at least build a basic, inexpensive PC that will be always on.

Title: keeping connection open all time in sql


问:
NUnit SetUp and TearDown
I have some experience in MS Test but new to NUnit.

Whether NUnit [Setup] is corresponding to [ClassInitialize] or [TestInitialize] in MS Test?

What is the NUnit attribute corresponding to [TestInitialize]?

REFERENCE:

https://stackoverflow.com/questions/1873191/testinitialize-gets-fired-for-every-test-in-my-visual-studio-unit-tests

https://stackoverflow.com/questions/4602288/nunit-testcontext-currentcontext-test-not-working

答:
NUnit [SetUp] corresponds to [TestInitialize].

For [ClassInitialize], use [TestFixtureSetUp] in NUnit.

The complete list can be found by a simple search. (a little old tho)

Title: NUnit SetUp and TearDown

ContentLicense: CC BY-SA 4.0


问:
What is the aim of software testing?
Having read many books, there is a basic contradiction:

Some say, "the goal of testing is to find bugs" while other say "the goal of the testing is to equalize the quality of the product", meaning that bugs are its by-products.

I would also agree that if testing would be aimed primarily on a bug hunt, who would do the actual verification and actually provide the information that the software is ready?

Even e.g. Kaner changed his original definition of testing goal from bug hunting to quality assessment provision but I still cannot see the clear difference. I perceive both as equally important.

I can verify software by its specification to make sure it works and in that case, bugs found are just by products. But also I perform tests just to break things.

Also what definition is more accurate?

Note above I am primarily referring to software testing as a process.

答:
I believe the book, "The Art of Software Testing" by Glenford J. Myers defines it best:

"Testing is the process of executing a program with the intent of finding errors."

He contrasts this definition with several common definitions:

"Testing is the process of demonstrating that errors are not present."

"The purpose of testing is to show that a program performs its intended functions correctly."

"Testing is the process of establishing confidence that a program does what it is suppose to do."

Rather than trying to prove that a program works, we should assume the program has errors, and the goal of software testing is to find them. In doing so, the quality of the software is raised, which is the ultimate aim of software testing.

Title: What is the aim of software testing?


问:
Creating a Application in Winrt that requires Internet
I am making a paid App for Windows 8, c#. I am wondering which is better?

If my application doesn't need internet connection normally but does requires internet connection for the first time to download content data. --Makes my life easier

Load the default data when installing. Then ask the user if he wants to update in app. -- Making the default data will be pain.

Now my big question is, is it safe to assume user has access to internet now-a-days when using application that shouldn't require internet?

答:
I think you can be safe in 2012 saying that "broadband internet is required to fully use this product" --- many other things people love and use require it.

I would probably undergo creating the default data for demo / testing / refence purposes. The fact that it shows well when a user first opens the app is nice.

As @bytebuster points out, you should certainly consider scenarios where the app is offline -- lots of things can happen to infrastructure. Including your own.


问:
Will an app made for windows store support WindowsRT, windows8 and windows 8 mobile?
I am very much confused about these.

I would like to develop app for windows 8 , Windows RT , and windows mobile.
I have windows 8 OS installed in my laptop.

As far as I know, Windows RT is for ARM based devices.

HERE ARE MY QUESTIONS:

I develop an app, and put in windows store. Will that can be downloaded from a ARM based device ,which runs on Windows RT, AND from a windows 8 laptop , and same from a Windows 8 mobile?

OR should it be different apps ?

答:
No.

Windows RT and Windows Phone are different ecosystems and different APIs.

WinRT is application runtime for running "Modern UI" apps in Windows 8 and Windows RT. It is actually only way to create a 3rd party application for Windows RT. Those apps must always be run from withing "Modern UI" of Windows, eg. it is not possible to use it from desktop application.

For Windows 8 Mobile, you need to use WinPRT. This is derived from WinRT, but is binary incompatible and contains different APIs and UI controls. But it is somehow similliar so you can share pieces of code between them.

More here:

http://channel9.msdn.com/Events/Build/2012/3-043


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答: As many others have stated, blank lines make for easier reading of code. However, there are some languages that enforce this standard. One that I can think of off the top of my head (not so much about blank lines but proper indentation) is Python.</p>

OwnerDisplayName: Skudd


问:
Static DataTable or DataSet in a class - bad idea?
I have several instances of a class. Each instance stores data in a common database. So, I thought "I'll make the DataTable table field static, that way every instance can just add/modify rows to its own table field, but all the data will actually be in one place!"

However, apparently it's a bad idea to do use static fields, especially if it's databases: Don't Use "Static" in C#?

Is this a bad idea? Will I run into problems later on if I use it?

This is a small project so I can accept no testing as a compromise if that is the only drawback. The benefit of using a static database is that there can be many objects of type MyClass, but only one table they all talk to, so a static field seems to be an implementation of exactly this, while keeping syntax concise.

I don't see why I shouldn't use a static field (although I wouldn't really know) but if I had to, the best alternative I can think of is creating one DataTable, and passing a reference to it when creating each instance of MyClass, perhaps as a constructor parameter.

But is this really an improvement? It seems less intuitive than a static field.

答:
You wouldn't get any improvement if you pass an instance of the DataTable to each instance of MyClass, you still have a single DataTable instance every object refer to, and will use a bit more memory because each object will have that instance unlike a static field that is a single reference for the hole class.

For the first view, you shouldn't have any problems using this architecture, the problems can rise if you have multithreading and concurrent acesses to the DataTable.


答:
There is no "should". The goal is to create useful, defect free software. You should do whatever is necessary to attain that goal. For some organizations that means the developer also writes the final acceptance tests. In other organizations there are legions of testers to do the final test.

Certainly, in a perfect world you would have trained acceptance testing professionals, just as you would have build engineers, usability experts, performance testers, etc. Small companies sometimes have to combine roles.

At the end of the day, this is your software. Do you want it released in the wild with bugs?


问:
Use of interfaces to ease rapid development/prototypes
Recently I've started to put almost all of my data structures into interfaces, and many of the classes that contain pieces of logic code as well, depending on how much work they are. I find that this makes development of applications much easier because I can easily swap out parts of my code when they do not work as well as intended without changing the rest of the application and swap them back in when I have corrected them, or if I need something simpler for the time being.
I was wondering if I'm developing a bad habit here.<p> Is this a anti-pattern I'm using here, or is it okay to do this?</p>

答:
Well, "Program to an interface, not an implementation" is a long-standing design pattern (Gang of Four 1995:18).  It's generally a good practice, especially where you want to decouple two modules so you can reason about each one independently.

It's mostly used in the form of dependency injection (that is, you inject dependencies that conform to some interface).  I have also used interfaces for my data structures and I find it works well.  If you have a method that takes data and stores it into a database, you might have two different sources of data that get stored... and I've had cases where I have two different concrete classes that implement that interface, one from a data logging source and another from a manual entry.


问:
Learning C++ properly (not C with classes)
The typical reason I hear to why people bash C++ is that they don't actually know C++, they just know "C with classes", which apparently is different. I am just beginning to learn C++, however, I want to actually learn C++ and not simply "C with classes". How can I ensure I learn C++ properly? Some examples would be wonderful.</p>

答:
C with classes with a good organization of source code files you can make your app faster for both compiling and running, while abusing of the later "academic C++" will increase compiling up to 100 times slower and your application will never be able to run properly if performance does matter. In the company I work on (probably the biggest in its sector) they have some tools that take up to 30 minutes or even more to compile, while I wrote the same functionality for myself at home and the compiling times are BELOW THE MINUTE, and it does have many less bugs and is far more maintainable that the spaghetti of templates used at work. So what really matters is if you want to get the job done or if you just want to say you code perfect academic C++.

But to realize this, you have to code a lot and learn how to properly code C with classes. Which probably would require you to learn academic C++ first :), or not, it depends a lot on your skills and will and perseverance, so you don't end up coding terrible either C++ or C with classes.


答:
The classic C string copy routine is known by fewer and fewer people theses days:</p>

```<code>while (*d++ = *s++);
</code>```

Body:
The classic C string copy routine is known by fewer and fewer people theses days:

while (*d++ = *s++);


问:
Is there an open source license with proprietairy-like terms?
Is there any license meeting the following criteria:

source code available (users allowed to browse the source)

users are allowed to modify the code with credits to the original author

not allowed to sell the software itself or any other program using code from it

can be sold by original author

答:
If you wrote the software, then you own the copyright.  Anyone can look at it, but they can not "use" it in any way unless they contact you and get an explicit permission.

if you do not want lots of people to explicitly contact you and get a permission, you can make your and their job easier, by providing your permission with your rules over the "usage" of the code in what is called a "license".

It will be better if there was already a license template that provided usage rules exactly the same way that you want. In your case, there isn't, so you have to spell out your terms yourself.  That is then your "license".

your terms can be written in complex, lawyery, format.  Or you can write it in simple terms the way you have explained it.  The former is expensive, but makes sure you cover every eventuality, loop hole, and withstands a court challenge if you have to.  The latter costs less to write up (30 minutes of your time?) but could be full of legal holes.

Now choose your pick!


问:
What is the correct UI interface to learn for creating Windows phone 8 apps?
I am a veteran Delphi 6 programmer transitioning to C# development.  My first project is a open source library that will have a minimal user interface since it is meant to be used as a Component primarily on desktop PCs running Visual Studio.  My next project is going to be a Windows 8 phone app and I intend for that platform to be my primary focus for future C# development, not the desktop.

My concern is that I waste as little time as possible learning a presentation framework that will benefit or distract me from writing Windows 8 phone apps.  The plethora of framework names I have already encountered include, WinForms, WPF (Windows Presentation Framework), Silverlight, Silverlight Mobile, Metro and there may be others.

Given my goal outlined in the first paragraph above, which is the correct framework to study for developing Windows 8 phone apps?

I read about the Portable Library Tools on this Stack Overflow thread:

https://stackoverflow.com/questions/5522355/windows-phone-7-wpf-sharing-a-codebase

But the reply by Simon Guindon seemed to indicate to me that it's not the best solution for writing a competitive Windows 8 phone app.

答:
You probably won't use Windows Forms anymore for Windows 8 development.

Try VS 2012. Check: visual-studio-express-for-windows-phone. Quote from that page:

"Windows Phone SDK provides Visual Studio Express 2012 for Windows Phone and the assets to build epic apps faster using what you know. Use .NET to build your apps or take full advantage of the platform for your games with DirectX/C++. .NET apps and games can reuse their business logic across Windows 8, the web (ASP.NET), and Windows Azure so developers can move faster."

A Microsoft (free) book that may help you know more about Windows 8 development is at: Programming MS Windows 8 Apps with HTML, CSS and JavaScript. I am not sure about the free part it may have restrictions or the offer may have expired.


问:
WPF more dynamic views and DataAnnotations
Comparing WPF and Asp.Net Razor/HtmlHelper I find WPF/Xaml to be somewhat lacking in creating views.

With HtmlHelpers you could define in one place how you wan't to represent specific type of data and include elements set from the DataAnnotations of the property.

In WPF you can also define DataTemplates for data but it seems much more limited then EditorTemplates. It doesn't use information from DataAnnotations.

Also the layout of elements can be bothersome. I hate having to constantly add RowDefinitions and update the Grid.Row attribute of lot of elements when I add a new property somewhere in line.

I understand that GUI programming can be a lot of grunt work like this but as Asp.Net MVC has shown there are ways around that.

What solutions are out there to make view creation in WPF a little bit cleaner, maintainable and more dynamic?

答:
Some random thoughts from the decent-sized project I worked on in WPF:

MVVM (cf. http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx) helps. It does not do all the work for you, but it gets you a little closer to feeling like you are in MVC. When properly implemented, it enforces a separation of concerns that makes everything a lot more maintainable.

When working with WPF, it is best to use explicit row/column definitions for your grids. All of the time. Yes, it is a lot of work, but when you do it, WPF ends up working the way it was really meant to (the visual designer, IMHO, should not exist or should be hidden--it just creates a cesspool in the XAML). Your views will then dynamically resize and be far more robust.

WPF is about as close as you can get to writing web apps while still writing desktop apps (of course, Microsoft is poised to change all that...). For all of its warts, it is a far more declarative and maintainable way to write GUI apps than straight winforms or Win32 calls.


问:
Design for a plugin based application
I am working on application, details of which I cannot discuss here. We have core framework and the rest is designed as plug in. In the core framework we have a domain object. This domain object is updated by the plugins.
I have defined an interface in which I have function as

DomainObject doProcessing(DomainObject object)

My intention here is I pass the domain object, the plug in will update it and return it. This updated object is then passed again to different plugin to be updated.

I am not sure if this is a good approach. I don't like passing the DomainObject to plugin. Is there a better way I can achieve this? Should I just request data from plugin and update the domain object myself?

答: You could use Data Transfer Objects that get filled by the plugins. Or pass around (deep) copies of your domain objects. And then let your core implementation verify the changes to those objects before applying them to the real instances.

Title: Design for a plugin based application


答:
This sounds a bit more like a pipeline / pipes and filters approach than a plug-in architecture.

There is nothing wrong with the approach.  You need to be careful not to go for a too generic approach.

You may want to have a look at Udi Dahan's excellent presentation around making roles explicit:

http://www.infoq.com/presentations/Making-Roles-Explicit-Udi-Dahan

Title: Design for a plugin based application

Body:
I am working on application, details of which I cannot discuss here. We have core framework and the rest is designed as plug in. In the core framework we have a domain object. This domain object is updated by the plugins.
I have defined an interface in which I have function as

DomainObject doProcessing(DomainObject object)

My intention here is I pass the domain object, the plug in will update it and return it. This updated object is then passed again to different plugin to be updated.

I am not sure if this is a good approach. I don't like passing the DomainObject to plugin. Is there a better way I can achieve this? Should I just request data from plugin and update the domain object myself?


问:
Why are source control systems still mostly backed with files?
It seems that more source control systems still use files as the means of storing the version data.  Vault and TFS use Sql Server as their data store, which I would think would be better for data consistency as well as speed.

So why is it that SVN, I believe GIT, CVS, etc still use the file system as essentially a database,  (I ask this question as we had our SVN server just corrupt itself during a normal commit) instead of using actual database software (MSSQL, Oracle, Postgre, etc)?

EDIT:  I think another way of asking my question is "why do VCS developers roll their own structured data storage system instead of using an exisiting one?"

答:
Better disaster recovery (worst case scenario: we'll parse it by eye, like in the old times)

Making tracking and debugging such disasters, possibly caused by faults in the VCS system, easier.

Lowering the number of dependencies. (let's not forget one of those systems is handling the kernel, and the other was supposed to)

A text-editor is always available. (MS SQL Server licenses... not so much)


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
Because you mention equations, this one belongs on your list:

```<code>e^{i\pi}+1=0
</code>```

(Wolfram Alpha rendering: )

Body:
Because you mention equations, this one belongs on your list:

e^{i\pi}+1=0

(Wolfram Alpha rendering: )


问:
How do I avoid GPL violations?
When I'm releasing a program, I like to license it under the GPL or LGPL. I also want to stay compliant with that license. I'm not good at reading legal documents, and the GPL3 is about 10 pages long. How do I avoid GPL violations in my code?</p>

答:
If you wrote the entire code, then you own it, and you can release it under GPL- the question "How do I avoid GPL violations in my code" does not really apply here.

If you used code from other open source projects in your code, you can still release your code under GPL as long as you identify what pieces come from where, and satisfy the license obligations coming from the other open source projects.  Check the licenses of the code you have used to see what their obligations are (eg you may have to add their license.txt into your package).

If you used code from non-open source projects in your code, then you need to contact the owners (copyright or license holders) of those proprietary projects and get their permission.

Title: How do I avoid GPL violations?


答:
Few things I do know from this weekend:

1) You need Visual Studio 2012.

2) You need Windows 8.

This is the list of project templates you get with the Windows Phone 8 SDK installed:

That's from a post I made at the weekend. It's not a complete answer I know, but I'm still feeling around the edges, so I'd be glad of some more input from others too.

Title: What is the correct UI interface to learn for creating Windows phone 8 apps?

Body:
I am a veteran Delphi 6 programmer transitioning to C# development.  My first project is a open source library that will have a minimal user interface since it is meant to be used as a Component primarily on desktop PCs running Visual Studio.  My next project is going to be a Windows 8 phone app and I intend for that platform to be my primary focus for future C# development, not the desktop.

My concern is that I waste as little time as possible learning a presentation framework that will benefit or distract me from writing Windows 8 phone apps.  The plethora of framework names I have already encountered include, WinForms, WPF (Windows Presentation Framework), Silverlight, Silverlight Mobile, Metro and there may be others.

Given my goal outlined in the first paragraph above, which is the correct framework to study for developing Windows 8 phone apps?

I read about the Portable Library Tools on this Stack Overflow thread:

https://stackoverflow.com/questions/5522355/windows-phone-7-wpf-sharing-a-codebase

But the reply by Simon Guindon seemed to indicate to me that it's not the best solution for writing a competitive Windows 8 phone app.


问:
Can I trust the Basic Schedule Equation?
I've been reading Steve McConnell's Software Estimation: Demystifying the Black Art book, and he gives an equation for estimating nominal schedule based on Person-months of effort:

```ScheduleInMonths = 3.0 x EffortInMonths<sup>1/3</sup>```

Per the book, this is very accurate (within 25%), although the 3.0 factor above varies depending on your organization (typically between 2 and 4).  It is supposedly easy to use historical projects in your organization to derive an appropriate factor for your use.

I am trying to reconcile the equation against Agile methods, using 2-6 week cycles which are often mini-projects that have a working deliverable at the end.  If I have a team of 5 developers over 4 weeks (1 month), then EffortInMonths = 5 Person Months.  The algorithm then outputs a schedule of 3.0 x 51/3 = 5 months.

5 months is much more than 25% different than 1 month.  If I lower the 3.0 factor to 0.6, then the algorthim works (outputs a schedule of approx 1 month).  The lowest possible factor mentioned in the book through is 2.0.

Whats going on here?  I want to trust this equation for estimating a "traditional" non-agile project, but I cannot trust it when it does not reconcile with my (agile) experience.  Can someone help me understand?

答:
I don't think there is going to be an answer to this from someone else, so I'm going to put my own answer here:

I think that @Ryanthal is right - Agile iterations just don't follow the same schedule estimating equation as waterfall projects.  I suspected that when I asked the question - I just needed an explanation as to why.

The equation basically says that there is a hard-limit to how many people can work on the same thing at the same time, and the less work there is, the more difficult it is to scale the work across the team.  We've all experienced this on small projects - splitting the work between 2 people is a challenge, and has some degree of inefficiency.  Splitting more work between 3 people is a little more manageable, but still hard.

I think this still applies to Agile projects, but Agile projects make a concerted effort every 2-4 weeks to address this challenge by planning the way they break the work up for the iteration, with the constraint of delivering working software, and working in a collaborative environment.  Doing so allows Agile more freedom to scale the team (at least within the agile sweet spot of 3-10 developers).

Its like a traditional waterfall project is a monolithic server application that can only be scaled up.  You can add more memory, but then you bang up against a CPU constraint.  You improve CPU, and memory or disk is the new constraint.  Its just difficult to scale, and you can run up against some hard limits.  Traditional projects are constrained in how effectively they can use the available developer resources, because the work is treated as one monolithic chunk.

(In terms of resourcing and schedules), Agile is more like server-component architecture where each of the pieces can be scaled individually, across multiple servers.  If the authorization component is a bottleneck, spin up another instance.  You can still run into hard limits, but within the capabilities of the infrastructure you have a lot of flexibility.