问:
How are effort estimations and duration estimations distinct?
How are effort estimations and duration estimations distinct?

At present my understanding is that effort is related to the amount of work required for one person to complete a task, and duration is the total amount of time required to complete the task, irrespective of resources. Is this the commonly accepted definition?

答:
Yes and no.

Example:
If you calculate a project with four developers and one (purely managerial) project lead, you basically add 25% overhead to the effort. If you then double the number of developers to reduce the duration to 50%, the overhead percentage might increase or decrease depending on the people involved. There are non-linear effects due to communication and "noise"/cooperation between project participants.

So, the equation "duration = effort / full-time-equivalents" is only a very rough estimate. Additionally, you have to take into account public holidays, vacancies, illness, competing projects, resource priorities, etc. to derive the calender duration from the estimated effort.

A related question/discussion is here.


问:
Randomness in Acceptance-Tests
I've got a simple authentication solution, where a user can log in with either email or username.

Since I want to show the little feature in the acceptance tests but don't want to pollute them, I thought I'll introduce some randomness. Do you think this is bad or good?

```<code>step "Fill in my credentials" do
    fill_in :user_login, with: [@user.email, @user.name].sample
    fill_in :user_password, with: @user.password
end
</code>```

答:
I would avoid randomness in your automated tests. You want all of your automated tests to be predictable. Trying random inputs is certainly not predictable. That way if one of your tests fail, you will be able to more quickly determine why.

Instead, spend some time thinking about cases that might deserve testing and test those explicitly. Thinking about your code like this is more effective than using random tests and hoping that they catch cases you didn't think of.

ContentLicense: CC BY-SA 3.0

Title: Randomness in Acceptance-Tests


问:
Best language or tool for automating tedious manual tasks
We all have tasks that come up from time to time that we think we'd be better off scripting or automating than doing manually.

Obviously some tools or languages are better for this than others - no-one (in their right mind) is doing a one off job of cross referencing a bunch of text lists their PM has just given them in assembler for instance.

What one tool or language would you recommend for the sort of general quick and dirty jobs you get asked to do where time (rather than elegance) is of the essence?

Background: I'm a former programmer, now development manager PM, looking to learn a new language for fun.  If I'm going to learn something for fun I'd like it to be useful and this sort of use case is the most likely to come up.

答: Python is great for this and has a larger install base, and Ruby is not any better except it has Why's Poignant Guide to Ruby. Seriously, cartoon foxes.</p>

ContentLicense: CC BY-SA 2.5


答:
Let's suppose that it works for email, but not name.

Now your acceptance test will fail half the time. Just re-running the test will potentially change the result. That'll make it harder to notice errors and track down the problem with it occurs. It'll be way easier if you just write two tests, one for each login method.

Title: Randomness in Acceptance-Tests

Body:
I've got a simple authentication solution, where a user can log in with either email or username.

Since I want to show the little feature in the acceptance tests but don't want to pollute them, I thought I'll introduce some randomness. Do you think this is bad or good?

```<code>step "Fill in my credentials" do
    fill_in :user_login, with: [@user.email, @user.name].sample
    fill_in :user_password, with: @user.password
end
</code>```


答:
"Effort" is measured in man-hours (or man-days, man-weeks, man-months, or even man-years).  "Duration" is measured in hours, days, weeks, months, or years.

You start by estimating the effort required to complete the project.  There are lots and lots of ways to estimate, some better than others, none perfect.  (Strong hint: Linear estimators ("ten lines per man per day") do not scale up well.)

Once you have an effort estimate, you have to estimate the duration.  This is closely related to constructing a draft (strawman) schedule, and inherently involves decisions on how many people you will put on the project.  To a certain extent, headcount can be traded for schedule, but bear in mind that there is still a minimum duration for some things: it is just plain impossible, today, to make a baby in one month by putting nine women on the job.  The better estimating methodologies will give you an "optimum" duration and headcount, given an effort estimate, and give you guidance on adjusting the effort estimate if you need a duration significantly longer or shorter than the optimum.  (Generally, both cases yield higher efforts, and hence higher cost.)

For some duration estimates, you may have to take into account that you need specialists for some tasks, and they don't grow on trees.  If you have three Kalman filters that have to be set up and tuned, and only one Kalman filter expert, you are not going to be able to do those three tasks in parallel.

Recommended reading: "Software Engineering Economics", by Barry Boehm, and "Controlling Software Projects", by Tom DeMarco.  These are the bibles of software estimation.  If you want to read other books, fine, but read these two FIRST.

One more thing: No matter what estimating methodology you use, even if it is "engineering judgment", recognize that you ignore the resulting estimate at your peril.  LOTS of companies have learned this the hard way, and lots more will.  Some have learned it many times over (or, more accurately, refused to learn it, many times over).

Body:
How are effort estimations and duration estimations distinct?

At present my understanding is that effort is related to the amount of work required for one person to complete a task, and duration is the total amount of time required to complete the task, irrespective of resources. Is this the commonly accepted definition?


问:
What features contributed to the evolution of Pascal?
I am compiling a detailed history of the Pascal language, and there are a few details I am missing.

There are so many features today that we take for granted. What features significantly contributed to the evolution of Pascal, and why were they significant?

I'm looking for language features, not platform or framework features. So like operator overloading or default parameters, but not Linux support or new Rich Text widget.

I know there are a few different flavors of Pascal (Delphi, Free Pascal, Oxygene, Quick Pascal, Apple Pascal, etc.) and they introduced the same features at different times and in parallel. That is OK. I'm looking at the Pascal language as whole, and when the significant milestones occurred (dates, versions, etc.)

答:
Start with "Structured Programming", by Dahl, Dijkstra, and Hoare.  Dijkstra's section is fundamental, even today.  Tony Hoare's section on data structuring laid a great deal of the groundwork for PASCAL.  (Dahl's section talked about what eventually became object-oriented programming.  He described what became classes in Simula 67.)

Look into ALGOL-W, Wirth's implementation of a variant of ALGOL-60.

You also need to know about PL/I and the IBM 360 link editor (linker) at the time.  It was a marvel of generality, with the minor issue that it ran slower than molasses in January in Juneau, Alaska.  PASCAL was specifically designed to be compiled and linked in one pass, for speed.  (It did help that the language started life on a CDC 6400 junior supercomputer, with lots of memory, making a one-pass compiler practical.)

There were actually two major versions of PASCAL from ETH Zurich.  The language everyone currently knows as PASCAL was actually PASCAL2, the second version.


问:
Restrictions Calling DLLs Across Technologies?
I want to call a DLL in my programming language of 'choice'. The documentation surrounding this clearly states that it must be a 32-bit DLL written in C, C++ or Delphi. But I wanted to call a DLL written in C#. It goes on to mention that the default calling mode is cdecl.

So my question is: why would this be the case? Is there any way to make it think a C# DLL was written in C, C++ or Delphi?

答:
Your language of choice supports calling any native DLLs written in any language. It's not really limited to those made with C, C++ or Delphi. You could call Fortran DLLs too, for example.

The problem is that the C# DLL is a managed DLL. That's a completely different beast from a native DLL. You will need to put a bridging layer in between the C# and your code. Robert Giesecke's Unmanaged Exports is one simple way to do that.


问:
Memory concerns while plotting escape from DLL Hell in Delphi
I work on a program with about 50 DLLs that are loaded from one executable, it's an old organically grown program where the only rationale for creating a new DLL is that one previously didn't exist to fill a given need. (and namespaces didn't exist in Delphi so it never crossed our mind to make dll1.main.pas, dll2.main.pas or something even more unique)

What we want to do is consolidate all these DLLs into one executable, since none of them are used out of the program, there shouldn't be much of a problem.  The concern my boss has is that if we did this, the memory overhead for terminal server clients would go through the roof.

So, I've stepped through enough initialization code to know that lots of stuff is done every time a DLL is loaded in to memory, but say I've got a project with about 4000 files, and 50 dlls, 10 of which are probably utilized by any one user in any one session of the program. The 50 dlls are about 2/3rds form files, if not more, but beyond that there's not a lot of other resources being loaded (only a few embedded pictures, icons, cursors, etc..). If I loaded all these files in to memory, how much memory is used per unit? how much is used per class? How do I keep the overhead down? and what is the biggest project one can reasonably expect to build with Delphi?

This tidbit won't help answering, but I think it might clarify what my boss is worried about, we currently start our program at about 18megs, normal working conditions are usually less than 40 megs, he thinks it could climb as high as 120 megs.

答: You'll end up using fewer resources by combining all you code in a single image. You'll have one instance of the RTL rather than 50.</p>


答:
I sometimes write tests that depend on random occurrences for whether they succeed or not.  I've learned that there are a few caveats, as described by other answers:

You do not ideally want a test that only fails sometimes.  If you break your code, you want to find out when you integrate your change, so you know which change to undo.

If there are only a small number of inputs that cause failure, you need to know which inputs they are in order to fix the problem.

The former problem can be mostly solved, as long as you are willing to accept a slow test suite, by running the test many times.  The latter problem requires you to log any random factors that may cause the failure.

These techniques also apply to situations where the randomness is unavoidable, e.g. you are testing for potential timing-related conditions in a multithreaded program.

As long as you are careful, it can be done.  But the best thing to do is to isolate potential failure conditions and write a predictable test that always fails for them prior to fixing the problem, IMHO.

Title: Randomness in Acceptance-Tests


问:
Algorithm for tracking progress of controller method running in background
I am using Codeigniter framework for PHP on Windows platform. My problem is I am trying to track progress of a controller method running in background. The controller extracts data from the database(MySQL) then does some processing and then stores the results again in the database. The complete aforesaid process can be considered as a single task. A new task can be assigned while another task is running. The newly assigned task will be added in a queue. So if I can track progress of the controller, I can show status for each of these tasks. Like I can show "Pending" status for tasks in the queue, "In Progress" for tasks running and "Done" for tasks that are completed.

Main Issue:

Now first thing I need to find is an algorithm to track the progress of how much amount of execution the controller method has completed and that means tracking how much amount of method has completed execution. For instance, this PHP script tracks progress of array being counted. Here the current state and state after total execution are known so it is possible to track its progress. But I am not able to devise anything analogous to it in my case.

Maybe what I am trying to achieve is programmtically not possible. If its not possible then suggest me a workaround or a completely new approach. If some details are pending you can mention them. Sorry for my ignorance this is my first post here. I welcome you to point out my mistakes.

EDIT:

Database outline:

The URL(s) and keyword(s) are first entered by user which are stored in a database table called link_master and keyword_master respectively. Then keywords are extracted from all the links present in this table and compared with keywords entered by user and their frequency is calculated which is the final result. And the results are stored in another table called link_result. Now sub-links are extracted from the domain links and stored in a table called sub_link_master. Now again the keywords are extracted from these sub-links and the corresponding results are stored in a table called sub_link_result.

The number of records cannot be defined beforehand as the number of links on any web page can be different. Only the cardinality of link_result table can be known which will be equal to multiplication of number of keyword(s) and URL(s) .

I insert multiple records at a time using this resource.

Controller outline:

The controller extracts keywords from a web page and also extracts keywords from all the links present on that page. There is a method called crawlLink. I used Rolling Curl to extract keywords and web page content. It has callback function which I used for extracting keywords alongwith generating results and extracting valid sub-links. There is a insertResult method which stores results for links and sub-links in the respective tables.

Yes, the processing depends on the number of records. The more the number of records, the more time it takes to execute:

Consider this scenario:

Number of Domain Links = 1

Number of Keywords = 3

Number of Domain Links Result generated = 3 (3 x 1 as described in the question)

Number of Sub Links generated = 41

Number of Sub Links Result = 117 (41 x 3 = 123 but some links are not valid or searchable)

Approximate time taken for above process to complete = 55 seconds.

The above result is for a single link. I want to track the progress of the above results getting stored in database. When all results are stored, the task is complete. If results are getting stored, the task is In Progress. I am not clear how can I track this progress.

答:
Am I just a lazy programmer for suggesting that as the background process knows where it is up to then it could report to the database once per loop cycle?

The reason I ask that is that I once wrote a background process whose job was importing records from other databases. The database, table needed were noted in a table called command_queue and row ID on the old system added to command_queue which the background task would start a new transaction, lock the row representing the command being acted upon, add it's system given ID number (which it got by registering on another table) then start working on and then update the new table adding the old ID to the new row data and then drop the command_queue row as complete and commit the transaction.

That way I could have multiple threads running at once, could cope with a power cut (should it ever happen) and recover from any level of catastrophe. Likewise I could monopolise the box with lots of threads if there was a lot of work to do and especially when we went home and the servers were idle.

In code igniter I had a view that would output the number of commands left to run how many were being processed and what size the tables in the database were that got a mention in the command list. (There was also a stop command for each worker thread).

Using some javascript goodness the view looked quite impressive with speedometers, pie-charts and so forth. Managers liked to see that sort of thing.

I didn't have to figure out what they were doing as I had the process tell me in great detail. Although I could go look as I used (detached) screen instances for each process and could see the output. It helped that I wanted to be the first coder to write a project that even with thousands of users a second there would be a zero crisis, zero data loss, zero disruption ever.

Edit If don't like using screen and you compiled PHP with --enable-pcntl then you can use pcntl_fork to create the background processes and setproctitle to note progress and then when you view the process list there is your process renaming itself to give you a clue.


问:
Is it possible to adopt agile methodologies for outsourced projects?
I've had experience as a developer or team lead on several projects that have been outsourced and have seen less than stellar results in all cases. Most of these projects have employed a waterfall philosophy, with large kickoff meetings, months-long requirements gathering phases, plenty of conference calls, and innumerable emails. One thing that's always frustrated me is an absence of early access to the code. The contracts are setup in a way where the offshore team is responsible for meeting functional requirements, which is what the executives are concerned with. This means, however, that architecture decisions, implementation details, pattern usage, and things that concern other developers are so deeply settled by the time the product is delivered that we're unable to offer feedback or request any real changes. </p>

<p>Has anybody here managed an offshore project that hasn't experienced these problems? Specifically, I'm wondering if there's any way to structure the contracts to compel offshore teams to work in shorter cycles and re-factor or re-design based on feedback from on-shore developers. I haven't had too much experience with agile methodologies (I agree with the general principles, but work in a conservative shop that has it's entrenched methodologies), but wonder whether these could somehow be adapted to help manage offshore development. Overall, I'm looking to minimize the surprises and maintenance nightmares that inevitably arise when a development team is left to work in isolation for months at a time. </p>

答: I have done it and I prefer it. The contract will have to be on a time and materials basis, rather than a fixed bid. The fixed bid theoretically moves some risk to the vendor and may be more competitively priced but in reality it generates a need for so much more work like you describe, not to mention fights over change control definitions etc. So we just hire x number of bodies and work a lot more dynamically with them, assigning work on a task basis. They do not participate in Scrums though - there are onshore leads that will represent them. Essentially the onshore looks like he is doing the work of three people, but he is parceling out tasks to offshore. The onshore/offshore model does cost you some higher rates with the onshore person obviously.</p>


问:
The Service class in MVC
From time to time I find there is a need to build a service class. Something I can't really attach inside a model in order to respected GRASP and SOLID.

So I created a class called AccountTransferService.

 Are service classes good design practice ?

 Do they represent a Model ?

 If a Service is not a Model what are they in a MVC arhitecture ?

答:
Are service classes good design practice ?

As long as they do not contain business logic or state but only orchestrate other components, yes. For additional information, see http://martinfowler.com/eaaCatalog/serviceLayer.html

Do they represent a Model ?

The Model in MVC is your application minus the User Interface (V+C). As such, a Service is part of the Model, but it is not a Model in the sense of a Domain Model. They are also not what frameworks like Code Igniter usually (and incorrectly) mean when they talk about models.

If a Service is not a Model what are they in a MVC arhitecture ?

See above, they part of the Model

OwnerDisplayName: danip

Title: The Service class in MVC


问:
What design pattern should be used for implementing maintainable complex dialogs?
From time to time I implement functionality which requires asking user questions sequentially.

Questions are conditional, that is the answer defines the set of the following questtiongs.

Sure it is Wizzard UI design pattern, but for now I have no clear understanding how it is implemented from the point of view of software architecture.

Screen/question can be a somewhat complex interface but most fo the time it's just a selection of several options.

Nonetheless after any step some calculations can be required, not only to get additional data but to define the set of questions.

I guess Strategy pattern has to do with this but I feel that the with this pattern the code which builds "execution flow" can become ugly.

Thanks in advance.

答:
I could imagine such a system as a composition of components (questions) that can be asked in a random order.

I would design it on the architectural patterns level using namely Pipes and Filters architecture. Questions would represent filters and conditions would by implemented as pipes.

This would result in a system, where you can really ask questions in a random order, because it is well known advantage of this architecture.

To get this working, you need to specify abstract class or interface for filters and pipes. Maybe, there can be only one implementation of pipe that will accept answer from a filter and decides what would be next filter in a pipeline.

Just a thought. Implementation would be probably harder.

OwnerDisplayName: voroninp

OwnerDisplayName: Andrew


答:
I can't really think a a very suiting pattern.
It looks like a mix a both a strategy pattern and chain of responsibility.
The next link in the chain is then decided upon by the selected answer.

But a strategy implementation is defined compile time and I suppose that the question come from a database.

I do can imagine a very straight forward solution:

A Question class has a collection of possible Answers and the Answer class has a next question.
This is actually a tree (directed graph), with the questions being nodes and the Answers the connecting edges.

The user interface navigates the tree using the answers.

This is both lean to develop and easy to maintain.

Title: What design pattern should be used for implementing maintainable complex dialogs?

Body:
From time to time I implement functionality which requires asking user questions sequentially.

Questions are conditional, that is the answer defines the set of the following questtiongs.

Sure it is Wizzard UI design pattern, but for now I have no clear understanding how it is implemented from the point of view of software architecture.

Screen/question can be a somewhat complex interface but most fo the time it's just a selection of several options.

Nonetheless after any step some calculations can be required, not only to get additional data but to define the set of questions.

I guess Strategy pattern has to do with this but I feel that the with this pattern the code which builds "execution flow" can become ugly.

Thanks in advance.


问:
In Scheme, what is formally a program's state?
I think i've understood more or less what a parsed Scheme program looks like (a binary tree with atomic values on the leaves, if i have understood correctly).  Can anybody please define to me, or give a reference, what a state (or a computation) of a Scheme program is?  Is it just the current binding plus a position, or a stack of positions, on the syntax tree?  (In such a case, i would appreciate a reference for a formal definition of Scheme binding as well :).)

Is there some simple description, like the one for the Turing Machine (the program + the current content of the tape + the current position on the tape)?

答:
I'm not aware of any formal definition, but I can speculate a bit.

Basically you can represent any program with a lambda expression in lambda calculus. A binary tree is a simpler view introduced by creators of Scheme, to give a nice idea to newbies in computer science.

Lambda calculus explicitly defines operational semantics for evaluation of lambda expression. Basically this means, in lambda calculus, they define how you will calculate the actual value of any lambda expression, or if we map lambda expressions to programs, how a program will work.

There are different alternatives for defining operational semantics of a programming language.  In lambda calculus world these alternatives involve reduction rules and reduction strategy. They always seem like identical but small variations change how lambda expression is reduced. In programming world this corresponds to how program executes. For example different reduction mechanisms might evaluate the actual parameters of a function before or after function definition is evaluated. This corresponds to eager and lazy parameter evaluation mechanisms of different programming languages.

In Scheme it is possible to represent each expression in a simpler binary tree view. Similar to lambda expressions, binary trees are reduced from leaves to root. So each configuration of a Scheme program running is still a binary tree.

However, function calls complicate this. When you call a new function, you have a new Scheme expression to evaluate. It is semantically possible to attach the new expression to the binary tree by replacing the function call. But practically it is not a nice method. I know that List does not use that approach, instead use a stack of configurations, each corresponding to a function. I wouldn't be surprised if Scheme follows this faction.

Moreover, bindings complicate that issue further. Scheme is not purely functional, it is possible to define bindings and their semantic should be included in the program by obeying scope rules. Even when there are simple scope rules, it is difficult to combine bindings with binary expression trees. Simplest way is using virtual links to bindings (like pointers).

These are only based on my observations from the times I've used Scheme, and some of them might false. But I guess it's clear that a very simple model such as Turing Machine is not purely applicable when factors such as function call and binding go into the picture. Programming language and compiler design is a complex puzzle with many sub-problems inside.

There is book available on web, called An Introduction to Scheme and its Implementations. It might provide more insight and real facts about the Scheme implementation. If you want to learn more on this subject I recommend reading a programming languages book on lambda calculus and a compiler design book (probably the famous dragon book).

OwnerDisplayName: Alexey

OwnerDisplayName: utkuerd


答:
State and meaning are two very different things, and your question sort of conflates them.

To the question "What does this Scheme program mean?", one can look at a semantics, either an informal one (a specification written in English, say), or a formal one (usually an operational semantics, but occasionally a denotational semantics, etc.). However, the semantics of a real-world programming language like Scheme is going to be extremely complicated.

Now, if you've chosen an operational semantics (as opposed to a denotational semantics), it will have something that looks like a state (you described the state of the operational semantics of a Turing Machine in your question). This may be a reasonably simple object... however, there are many different operational semanticses you can come up with for Scheme (or any real-world language), and each of them will have their state look like something different!

So, essentially, there are infinitely many answers to your question, none of them is going to be illuminating without its corresponding semantics.

The Turing Machine, because the way it's usually presented is so close to an operational semantics anyways (because it's so low-level and "state-y"), doesn't really have this problem, because there's only one good choice, which you described well in your question.

Title: In Scheme, what is formally a program's state?

Body:
I think i've understood more or less what a parsed Scheme program looks like (a binary tree with atomic values on the leaves, if i have understood correctly).  Can anybody please define to me, or give a reference, what a state (or a computation) of a Scheme program is?  Is it just the current binding plus a position, or a stack of positions, on the syntax tree?  (In such a case, i would appreciate a reference for a formal definition of Scheme binding as well :).)

Is there some simple description, like the one for the Turing Machine (the program + the current content of the tape + the current position on the tape)?

OwnerDisplayName: Paul Stansifer


答:
Both of the other answers look excellent to me.

I would add the following: the state of a scheme program is... a scheme program!  That is, you can define a "meaning" function for scheme programs by showing how programs reduce to other programs. This is called a "small-step" semantics.  To show you what I mean: what are the "steps"--in a seventh grade sense--in evaluating

```<code>3 * (4 + 5)
</code>```

? According to the small-step rules provided by most teachers, the first step in evaluating this program is to reduce it to

```<code>3 * 20
</code>```

In exactly the same way, you can define a small-step semantics for Scheme that reduces a program to an answer by taking a series of reduction steps.

Body:
Both of the other answers look excellent to me.

I would add the following: the state of a scheme program is... a scheme program!  That is, you can define a "meaning" function for scheme programs by showing how programs reduce to other programs. This is called a "small-step" semantics.  To show you what I mean: what are the "steps"--in a seventh grade sense--in evaluating

3 * (4 + 5)

? According to the small-step rules provided by most teachers, the first step in evaluating this program is to reduce it to

3 * 20

In exactly the same way, you can define a small-step semantics for Scheme that reduces a program to an answer by taking a series of reduction steps.

OwnerDisplayName: John Clements


问:
What are some current opinions on WPF?
We are trying to make a decision about if we should create a program in WPF w/ a WCF server, and I was wondering what the current opinions are of WPF. I was looking around online but most of the arguments I saw for/against WPF were dated a year or two ago, and about WPF3.5. I was wondering if those opinions have changed in the past year or two with the release of WPF4.0.

Some notes....

The program we are making is for use by a single-company in a controlled enviornment. With the exception of one or two Vista laptops, most users are on Terminal Servers or WindowsXP. It is not media-heavy and doesn't need a pretty UI (although it won't hurt). It needs to be extensible and allow for easy additions later on. Security and Performance are our key concerns.

EDIT

Primary concern about WPF is Support (MS and community), memory/cpu usage on terminal servers, and finding people to work on the project now and maintain it in the future. Some smaller things of concern are lack of library controls, development time, and learning curve.

The primary alternative we were considering is ASP.Net/jQuery.

答:
I like it.

IMO it is good.

WPF is just presentation, so it won't affect security, unless there are some security issues I've not heard about.

I've not seen any metrics comparing WPF to WinForms performance-wise. I'm guessing they're comparable. This SO question is about the performance of WPF v WinForms: https://stackoverflow.com/questions/368371/performance-comparison-of-winforms-and-wpf

I like  WPF because XAML is declarative and makes saying how I want the UI to look and act easier than with WinForms. This is only true after I have learned the basics of MVVM.

Title: What are some current opinions on WPF?


问:
Best practices for sharing tiny snippets of code across projects
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.

答:
The second solution you describe is not that bad. In .NET you also reference an assembly from the GAC even if you just use one single class of it. 'Dragging irrelevant code' is not that a problem as you might think. In this case it is vital to at least keep related methods and classes cleanly organized in different namespaces. Additionally good practices for API design should be applied to prevent this solution becoming a mess.

If it comes to very small bits of code, I think following approach is a good supplement to a common project: Allow them to be duplicated in different solutions. Deal with them like best practices: document and communicate them to the team.


答:
If they really are reusable methods / classes, you could write them into a small number of 'Swiss Army Knife' libraries. We do this quite often at my company; we call them framework libraries:

Framework.Data - Utilities for working with database queries.

Framework.ESB - Standard methods for interacting with our enterprise service bus

Framework.Logging - Unified loging system

Framework.Services - Utilities for interacting with web services

Framework.Strings - Utilities for advanced string manipulation / fuzzy string searching etc.

...

In all, there are about a dozen or so libraries. You can really distribute the code however you see fit, so you don't have to end up with hundreds or dump everything into one giant assembly. I find this approach fits because only some of our projects will need Framework.Data and only a few  will ever need Framework.Strings, so consumers can select only those parts of the framework that are relevant to their particular project.

If they're really just snippets, and not actual methods / classes that can be easily reused, you could try just distributing them as code snippets into the IDE (e.g. Visual Studio Code Snippets). Teams I've worked with in the past had a common snippet library that made it easier for everyone to follow our standard coding practices with internal code as well.

Title: Best practices for sharing tiny snippets of code across projects

Body:
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.


问:
Best practise is not to poll...but isn't polling happening internally anyway when a thread calls wait()?
Say we have some thread that wants to check when another thread is finished its task. I have read that we should call a wait() type function that will make this thread wait until it receives a notification that the other thread is finished. And that this is good because it means we aren't performing expensive polling.

But isn't polling happening internally at a lower level anyway? I.e. if we make the thread wait() isn't the kernal performing polling anyway to check when the other thread is finished so that it can then notify the first thread?

I presume I a missing out on something here, can someone enlighten me?

答:
The operating system provides certain primitives for this kind of interprocess communication that don't require polling.

If process A is waiting on mutex M, the OS knows A can't be run and puts it aside in a bucket of processes waiting for something to happen.  When the process holding M releases it, the OS looks at the list of processes waiting for it.  The first process on the list, maybe A, gets removed from the idle bucket and put on the run queue.  The next time A gets a time slice, the wait() it called will return and the program continues.


问:
When is Java a good choice for web development?
When is Java a good choice for web development?

Please do not say "When you have a development team that knows only Java."

答:
It's simple: use Java when back end performance is a major concern. There is more overhead when coding but the code will execute in 1/200th to 1/500th of the time- literally. Php, Ruby, and other dynamically typed languages are always going to be way slower than java or .net servers. </p>

<p>Most solutions for the web won't need this. Twitter didn't abandon Rails until they started peaking in popularity for example. </p>

Body:
It's simple: use Java when back end performance is a major concern. There is more overhead when coding but the code will execute in 1/200th to 1/500th of the time- literally. Php, Ruby, and other dynamically typed languages are always going to be way slower than java or .net servers.

Most solutions for the web won't need this. Twitter didn't abandon Rails until they started peaking in popularity for example.


答:
Depending on the size of the team/project/company this will be rather hard thing to do efficintly, unless it is already built into your environment somehow, and every solution you will find (if you implement it) will cost some money. (It may safe you more, but that you will not be able to measure easily). You'll have to check whether it's worth the price. Keep in mind, too, that reusable solutions tend to become abstract and often will fit many situations but without being optimal.

In any case, if you want to do this for the code produced by more than one person, at first you'll need awareness of everybody and cooperation. This includes developers and managers.

Then you'll need to make sure you know the scope in which you want to do this. Team? Project? Department? Company? Depending on the answer the kind of code you'll put into such solutions will vary, as will the granularity with which you tailor the dlls. Once you decided on this someone (preferrably with some enthusiasm for the idea - you?) should sit down and start to put some structure into this.

Just creating such dlls will not be sufficient to do the trick, though. In order to make them useful you'll need to advertise them (to users and contributors) and maintain them like any other piece of software, which usually means that you need to put someone in charge for them for a long time. You'll need reliable documentation, as well, which will then need maintenance, too. With some luck and cooperation you may end up with some best practices, but it can as well easily evolve into a project of it's own, depending on the size and number of teams involved. And for that you'll still need management support.


答:
I've only ever worked in "enterprise" environments where this sort of thing has been an issue and each time it's been the second option that's been adopted. For the most part it's worked okay because there hasn't been any constraint on application footprint.

However, having spent the last week with a start-up who are running their own Nuget server I'm inclined to suggest this as a viable alternative. Of course the issues I expect to emerge will be around discover-ability.

If the projects are suitably granular and the namespaces are sensible then I can see this becoming a popular approach in places.


答:
AutoHotKey

AutoHotkey is a free, open-source utility for Windows. With it, you can:

Very friendly and helpful community.

C like syntax.

Automate almost anything by sending keystrokes and mouse clicks.

You can write a mouse or keyboard macro by hand or use the macro recorder.

Create hotkeys for keyboard, joystick, and mouse. Virtually any key, button, or combination can become a hotkey.

Manipulate windows and processes.

Interact with all standard windows controls.

Expand abbreviations as you type them. For example, typing "btw" can automatically produce "by the way".

Create custom data-entry forms, user interfaces, and menu bars. See GUI for details.

Remap keys and buttons on your keyboard, joystick, and mouse.

Create Graphical User Interfaces (GUIs).

COM support.

Regular expressions.

Directly call external DLL and Windows API functions.

Unicode, x32 and x64 support.

Respond to signals from hand-held remote controls via the WinLIRC client script.

Convert any script into an EXE file that can be run on computers that don't have AutoHotkey installed.

http://ahkscript.org/

I've saved several companies a large sum of money by using this tool.

Title: Best language or tool for automating tedious manual tasks

Body:
We all have tasks that come up from time to time that we think we'd be better off scripting or automating than doing manually.

Obviously some tools or languages are better for this than others - no-one (in their right mind) is doing a one off job of cross referencing a bunch of text lists their PM has just given them in assembler for instance.

What one tool or language would you recommend for the sort of general quick and dirty jobs you get asked to do where time (rather than elegance) is of the essence?

Background: I'm a former programmer, now development manager PM, looking to learn a new language for fun.  If I'm going to learn something for fun I'd like it to be useful and this sort of use case is the most likely to come up.


问:
The best way to store dictionary from file
I'm working on a translator in C++. Basically I want to parse the file with translations and store it in my program, so I can perform search through the words and simply access the corresponding word. My file will look like that:

```<code>word|translation
second word|second translation
</code>```

etc. It doesn't have to be | as delimiter and the word can contain spaces. So after I store it in my program I want to search for a word and get the corresponding word easily.

The question is, what is 'the best' way to store this dictionary? Should I use dynamic structures and link them? Maybe vectors? Or should I use two-dimensional array to store the 2 strings? Could you please propose to me how the structure will look like?

答:
Since you're going to search by the first word, I'd suggest using a Hashmap.

A Hashmap is designed to solve exactly this issue: Search for a complicated key; It's also sometimes referred to as "Dictionary," so you know it's about this.
It works by defining a function (Which is called "hash function") from the key-domain ("word" in your dictionary) to int, and then use these ints as the position in an array, where it stores both original key and value ("word" and "translation").
If your input is identical to some key, then the result of the hash function will give you the right int key, and you can complete your search very fast.

For more information: http://en.wikipedia.org/wiki/Hashmap

Good luck :)


答:
One solution to consider is a SQLite database.  SQLite, in contrast to most other databases, works well as a self-contained database within an application.  It gives you immediate support for serializing your dictionary to disk, querying your dictionary in many ways, etc.

SQLite is a higher level construct than a Hashmap; it comes with more of the functionality your application will need, thus reducing the amount of implementation work in your application.

If you are already familiar with SQL, SQLite is generally an immediate win as an alternative to ad-hoc file formats.

Title: The best way to store dictionary from file

Body:
I'm working on a translator in C++. Basically I want to parse the file with translations and store it in my program, so I can perform search through the words and simply access the corresponding word. My file will look like that:

```<code>word|translation
second word|second translation
</code>```

etc. It doesn't have to be | as delimiter and the word can contain spaces. So after I store it in my program I want to search for a word and get the corresponding word easily.

The question is, what is 'the best' way to store this dictionary? Should I use dynamic structures and link them? Maybe vectors? Or should I use two-dimensional array to store the 2 strings? Could you please propose to me how the structure will look like?


问:
Best practice for handling asynchronous inter communication?
Recently completed a project for handling credit card processing. One of the difficulties I faced was handling the delay / possible failure of notification messages. The most complex example was:

an external system sending the request for payment

my system turning that request into a request to the payment gateway

sending the user to the gateway

waiting for the user to perform payment

the user returning back to my system but being held until the system receives notification of success/failure

Sending the user back to the external system depending on failure

Even more difficult was the fact that upon failure to send the notification the gateway attempts to send the notification every 15 minutes for a number of hours.

I solved it using a database record of pending transactions and then detecting success and failure from the return plus a timed delay listener for the notification and transaction handling...

Reasonably difficult!

But this must have been solved a gazillion times before so what is the best practice?

I can see my future is going to be writing the handling between all of these systems and managing the time delays and possible network failures so I want to be following the best practices.

Book / article recommendations would be great.

Thanks in advance!

答:
When building distributed systems, the difference between a 'synchronous' system and an 'asynchronous' system is this: A synchronous system has known upper bounds on computation and message delivery times. So: you have an asynchronous system where certain events do not have these known upper bounds. How do you handle it?

If these asynchronous processes have probabilistic upper bounds then you can use timeouts to make your system act like a partially synchronous system. If the payment gateway's 98th percentile response time is 5 seconds then a 5 second timout will make 98% of your requests succeed and the other 2% will just fail. This means that you now have a known upper bound on how long this process will take to either succeed or fail. This probabilistic failure detection is a critical tool for turning asynchronous systems into synchronous systems.

Keep a durable record of these events so that you can recover your system state in the event of system failure. If your payment gateway handler is keeping these events in volatile memory and it crashes then you're screwed.

Each complex transaction is essentially a series of state transformations based on the sending and receiving of messages (events) within the system. It sounds like you are informally modeling this using your "record of pending transactions" but I would suggest that you go further: For each transaction you need to manage, create a formal state machine that describes it and keep a durable record of its current state. You will find that these state machines are easy to understand, easy to test, and give much-needed visibility into these processes both for you and your users.

The more asynchronous your system, the more formal and explicit you need to be when managing these complex evented state transformations. Timeouts, durable event logging, and state machines are the best practice here. This is why Erlang OTP bases much of its application behavior on the state machine model, for instance.

For reference, I haven't found anything better than Introduction to Reliable and Secure Distributed Programming. It will give you a strong algorithmic basis for understanding both synchronous and asynchronous systems from first principles.


问:
What stage of development do activity network diagrams belong to?
Activity network diagrams are used to determine the forward and backward paths for a project, and consequently to determine the critical path or maximum time to development.

I'm already familiar with using work breakdown structures which break down functional requirements into necessary and sufficient deliverables, but I'm unsure of what stage of project planning activity network diagrams fit into.

for clarity my interpretation of the planning cycle.:  https://docs.google.com/file/d/0B6m1-u6HxISZeGNCQ2JudXNyZ1U/edit?usp=sharing

Please could someone help me clarify this matter?

答:
Network analysis is between WBS and Gantt Chart:

Managing Information Technology Projects ¹ discusses Network Analysis in the second chapter: The Foundations of Project Management, just after the WBS and before the Gantt Chart.

The same is true for Project Management: A Systems Approach to Planning, Scheduling, and Controlling ², where WBS is discussed in chapter 11: Planning, Network scheduling - in chapter 12, and Gantt Chart in chapter 13: Project Graphics.

In fact, in practice, the activity network is planned just after planning the WBS. It can hardly be done before, since it requires the elements which figure in WBS, and is required to do Gantt Chart with is based on the network analysis itself.

Project-wise, it is at the same stage as the WBS.

On the diagram from your question, if WBS is Define/Decompose stage, Gantt Chart would be at the very end (Develop schedule), and network analysis - somewhere behind the two, probably after estimating resources (in order to get a good idea of possible paths).

¹ Managing information technology projects: applying project management strategies to software, hardware, and integration initiatives by James Taylor, 2004, ISBN 0814408117

² Project Management: A Systems Approach to Planning, Scheduling, and Controlling by Harold Kerzner, 8th Ed., 2003, ISBN 0471225770


问:
How does the ETVDX model fit in with project management?
In a lecture, the lecturer described the following model :

E - entry (the preconditions to a task).

T - task - doing the task

V - verifying the tasks quality

D - Delivering the tasks

X - Exit.

or ETVDX

If anyone is familiar with this 'generic compliance model', how does it fit into software development exactly? I presume it's equivalent to the waterfall model of negotiating requirements > defining/decompose stage > estimating effort > estimating resources > developing schedule.

答:
Important note: there is no such a thing as ETVDX model in software industry. I checked three books on project management, Wikipedia and Google, and none have relevant references about ETVDX. Thus, the following is just pure speculation without solid references. If you want to have a definitive answer, ask your lecturer.

Having said that and considering the context of your recent questions, I would suppose that ETVDX is about the tasks which can be considered autonomous and evaluated in terms of time and cost, i.e. level four of the Work Breakdown Structure (WBS). Putting those tasks at level four, and not level five, enables to attribute the task itself to one person or team, while the quality verification will be done by another one.

Once one finishes the WBS, separate work packages can be assigned to different people, given that those work packages are combined into tasks. ETVDX are the different aspects of every task.

Let's take an example of a product of an e-commerce website which also has a desktop client. A sample task Tn would consist of creating the part of the desktop application which enables the user to search for the products.

Entry would represent tasks required to be done in order to start Tn. This will include:

The task T1 of defining the interface of the web service which allows the desktop application to retrieve products,

The task T2 of defining the framework of the desktop application,

The task T3 of creating the component which displays a list of products in desktop application.

In other words, E(Tn) = {T1, T2, T3 }.

Task will be the task itself, i.e. the management required to do the search part, the unit testing, the coding and the documentation. This is what is actually done by a developer of a team of developers who are assigned to Tn. The work of this developer or this team will be based on both the requirements, the overall architecture of the project and the interfaces with the dependencies like T1.

Verification would be what QA department does: checking that:

The component works without crashing every two minutes.

The component may match the requirements, but if it makes the application crash, it wouldn't be very useful nor appreciated by the end users.

The component matches exactly the original requirements.

If those requirements describe that the border of the search bar is blue, and the actual border is gray, it wouldn't make the end users scream and throw away the application, but would still be a gap between what requirements ask and what is actually done.

Delivery represents the moment when Tn is fully tested by QA department and can be delivered to the customer. It belongs then to the customer to confirm that this part of the product matches exactly the business needs originally expressed in SOW and translated into technical terms inside the WBS.

There are two possibilities:

Either the customer confirms that what was done in Tn is exactly what was originally asked. This results in moving the task to the Exit step.

Or the customer points out a gap between the original needs and the final result. This gap may result from a misunderstanding, a misinterpretation of the business needs, the fact that the requirements weren't detailed enough, that it wasn't originally possible to predict a certain case, etc.

Exit would represent the moment when Tn is considered finished, confirmed by the stakeholders and ready for production. It doesn't mean that the product itself can be released, but only that the task is tested, considered conform to the requirements, and ready to be used by other tasks which rely on Tn.

In the same way, Entry step would have ensured that T1, T2 and T3 were exited before starting Tn itself.

For example, starting Tn while T1 is still pending would increase the risk of going out of schedule. Imagine that the developers' team actually finished the task Tn, and QA department was currently testing this task, when T1 was invalidated by the customer: it appeared that the interface of the web service was based on requirements which were wrongly interpreted by the company, and the customer insist on changing the interface. Not only T1 would change, but Tn would require to change as well.

For me, ETVDX is not the same as the Waterfall model. In Waterfall, chronologically, one:

Gathers the requirements,

Does the architecture and design,

Implements the product, ← ETVDX is here

Verifies it,

And maintains it.

ETVDX would be involved repeatedly during the implementation phase of the Waterfall model. ETVDX expects WBS and Gantt Chart to be done, and is based on them. It is also what enables the project to flow according to the Network Analysis (and Gantt Chart): for example if the precedence diagram shows that Tn relies upon T1, T2 and T3, while TA and TB rely upon Tn, then you know that:

The Entry of Tn would follow the Exit of T1, T2 and T3,

The Entries of both TA and TB would follow the Exit of Tn.

Note: if Agile methods are used, Waterfall flow will coincide with the task itself. In this case, ETVDX corresponds, chronologically, to the Requirements → Verification step, i.e. the whole Waterfall flow. Both would still signify different things as they are about different aspects of project management.


问:
I'm not sure what this license allows me to do
I'm using the BigRational class from bcl.codeplex.com. It will be opensourced when it's finished, and it's modified. However, I don't get legal jargon, so even though it's quite short, could someone explain to me what it does/doesn't allow you to do?</p>

答:
2. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.

(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations

(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.

(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.

(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.

(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.

(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.

TDLR; you can use our source code but not any of are trademarks. If you use any of our source code you need to licence it under the above terms. If it breaks, tough shit, not our fault.


问:
Can a strategy be implemented as a nested member class?
Is it okay to have a strategy implemented as a non-static inner class or is it considered a bad practice?

```<code>public class SomeClass{

  private final Strategy strategy;

  public void someMethod(){
   this.strategy = new Strategy();
   //call some strategy method to run an algorithm
    strategy.doSomeWork();
  }

  private class Strategy(){
    private doWork(){};
  }
}
</code>```

P.S: Strategy does need access to the state of the SomeClass. So can't make it static.Another option is to have Strategy as an interface and then inject a concrete Strategy inside the SomeClass constructor but at the moment I do not see this particular Strategy interface being used by another class. So thought of the first approach. However,if I do take the first approach how would I have my class work seamlessly with multiple strategies?

答:
I think your inner class strategy should be static because it must not work directly with the state of your class. This is how I think it should be done.</p>

```<code>public class ExampleClass
{
    private final ExampleStrategy strategy;
    private int state;

    public ExampleClass(final int initialState, final ExampleStrategy strategy)
    {
        this.state = initialState;
        this.strategy = strategy;
    }

    public void useStrategy()
    {
        this.state = this.strategy.modifyState(this.state);
    }

    public static interface ExampleStrategy
    {
        int modifyState(final int state);
    }

    public static class IncrementStrategy implements ExampleStrategy
    {

        @Override
        public int modifyState(final int state)
        {
            return state + 1;
        }

    }

    public static void main(final String[] args)
    {
        ExampleClass eClass = new ExampleClass(10, new IncrementStrategy());

        eClass.useStrategy();

    }
}
</code>```

OwnerDisplayName: Subhra

Body:
I think your inner class strategy should be static because it must not work directly with the state of your class. This is how I think it should be done.

public class ExampleClass
{
    private final ExampleStrategy strategy;
    private int state;

    public ExampleClass(final int initialState, final ExampleStrategy strategy)
    {
        this.state = initialState;
        this.strategy = strategy;
    }

    public void useStrategy()
    {
        this.state = this.strategy.modifyState(this.state);
    }

    public static interface ExampleStrategy
    {
        int modifyState(final int state);
    }

    public static class IncrementStrategy implements ExampleStrategy
    {

        @Override
        public int modifyState(final int state)
        {
            return state + 1;
        }

    }

    public static void main(final String[] args)
    {
        ExampleClass eClass = new ExampleClass(10, new IncrementStrategy());

        eClass.useStrategy();

    }
}


问:
Format text in a generic and reusable way
I would like to write some long text in some structure to allow a set of operations on that text. The question is which structure or format should I use, which suits best the use that I plan to do of that text?

Next I describe that use:

I would like to write text in natural language, possibly with translations to several languages. Translations would simply be the same structure with different data (text).

I would like to keep that text in a VCS, check diffs, branch and merge, etc. The structure should fit well this use.

I would like to keep the text free of as much clutter as possible so that it is human-readable.

I would like to easily convert the text to other formats, not necessarily many but at least html and pdf would be fine.

I would like to be able to manipulate that text easily, for instance changing the order of some elements, filtering them, etc. based on metadata in that text.

Metadata is data, that means it may be printed or not, or it may be printed in different ways.

Here are the main options I have considered so far:

Latex: basically it is a language designed for this task. The problems I see are that it is not as readable as other options, for instance Markdown, and it is not really structured text. The text is there and the metadata about formatting options and so on can be separated with a set of macros, but the text is not really structured, changing the order requires either parsing it or defining all the text as macros so that only the order of the macro invocation needs to be changed. It's great for what it does, but becomes clumsy when it falls short in some feature, as structuring the text. I don't see a good separation between control information and data to be printed. It is a very good option to convert to pdf.

XML: The structure in this case is fairly good, but in the current context, I see no advantage in using XML when HTML could be used instead, it provides the same features and some more.

HTML: the conversion to HTML would be immediate in this case but the conversion to pdf is not so clear. In terms of human readability maybe markdown could be better, but HTML is probably the most widespread and used language for the task at hand, there are supporting languages like CSS (Less, Sass, too many options) that can make life easier, Javascript can handle it, anyone with a browser can easily read it, etc. Maybe some special HTML could be converted to quality Latex and there to pdf, I don't know.

Markdown: a very good option in terms of readability, but I'm uncertain about how could it be manipulated, maybe through conversion to HTML and then using DOM manipulations or any other processing that could be done on XML and thus on proper HTML. I'm uncertain about how flexible may be for defining metadata (for instance a paragraph that is a summary of other paragraphs) when this could be easily done with XML or HTML via classes or other attributes.

JSON: most languages include a parser for JSON thus it is very friendly for programming languages and easy manipulation  m. Obviously some standard should be defined for JSON, but the same holds for the rest of the options, including latex (macros).

CoffeeScript: this removes some clutter from the usual JSON, it may be more readable and can be converted into JSON easily.

Mixing: the problem with JSON and CoffeeScript is that the structure to hold the contents is very flexible (maybe too much) but it doesn't support in a natural way inline annotations. A possible solution is to use Markdown or HTML for these fragments of text, including bold text or what may be needed.

The objective is to write a manifesto, or something that looks like a manifesto and evolves. This is based on some ideas that recommend using VCS systems. The point is to have a structure that allows to write once and publish as many times as may be needed and in different ways, maybe blog posts, pdfs, etc., because a lot of effort to reach the consensus has to be put to write the text, rewriting and rewording does not seem a good idea. This discards some other nice options, like a wiki, but it would be nice to be able to have it structured in some way such that a set of pages like a wiki could be built from the source data.

In the end the technology may not be there yet, but I think it is not too far. There are actually so many options that a clever use of some of them should be enough.

答:
One thing that I notice about the options you mention is that most of these are easily converted to each other (assuming you follow some predefined rules before writing the document).

Whereas LaTeX is easily compiled to PDF I would advice against it, as it contains too much information on the actual presentation and too little structure.

In many cases HTML also reflects the presentation too much I would say (although it is possible to minimize this of course).

I would probably define an XML schema and create the document as XML. In this way it is easily converted to all the remaining formats (especially HTML). Depending on the complexity of your documents, you might want to use some predefined schema such as DocBook (although I have little experience in using it):

http://en.wikipedia.org/wiki/DocBook

Further, you can use tools such as XML transformations (XSLT) to handle some of the conversions (if you like). This makes it really easy to convert a well structured XML document to HTML for instance.

All that being said, many of the remaining choices would be viable as well. In the end it depends on your own taste (personally, I don't find JSON very interesting for such job, for instance - others might) and on the complexity you want to represent (Markdown might not be good if you need very fine grained control).

As long as you actually structure the document, conversion to many other formats should be rather trivial.


问:
Is what someone publishes on the Internet fair game when considering them for employment as a programmer?
(Originally posted on Stack Overflow but closed there and more relevant for here)

So we first interviewed a guy for a technical role and he was pretty good. Before the second interview we googled him and found his MySpace page which could, to put it mildly, be regarded as inappropriate.  Just to be clear there was no doubt that it was his page (name, photos, matching biographical information and so on).

The content was entirely personal and in no way related to his professional abilities or attitude.

Is it fair to consider this when thinking about whether to offer them a job?

In most situations my response would be what goes on in someone's private life is their own doing. However for anyone technical who professes (implicitly or explicitly) to understand the Internet and the possibilities it offers, is posting things in a way which can so obviously be discovered a significant error of judgement?

EDIT: Clarification - essentially it was a fairly graphic commentary on porn (but of, shall we say, a non-academic nature).  I'm actually more interested in the general concept than the specific incident as it's something we're likely to see more in the future as people put more and more of themselves on-line.

My concerns are not primarily about him and how he feels about such things (he's white, straight, male and about the last possible victim of discrimination on the planet in that sense), more how it reflects on the company that a very simple search (basically his name) returns these things and that clients may also do it.  We work in a relatively conservative industry.

答:
For the most part, it is up to you. You would have some legal exposure if you considered factors that are protected such as marital status or religion after seeing information about those online. For the most part, you get to decide on personality. </p>

<p>Speaking for myself, I don't put anything on a blog or my Facebook page that I wouldn't want the entire world to know about me. I find people who make private details so public to be a little odd but wouldn't normally be biased against them from a hiring perspective. </p>

Body:
For the most part, it is up to you. You would have some legal exposure if you considered factors that are protected such as marital status or religion after seeing information about those online. For the most part, you get to decide on personality.

Speaking for myself, I don't put anything on a blog or my Facebook page that I wouldn't want the entire world to know about me. I find people who make private details so public to be a little odd but wouldn't normally be biased against them from a hiring perspective.


答:
The three main approaches to this have fundamentally different approaches and it really depends upon what your requirements are.

You've got a dictionary of some sort.  In many languages, dictionary is synonymous with Map and that will lead us down the different paths.

The first approach is to use a database of some sort.  You could store this in an actual database external to the system - Oracle, MSSQL, MySQL, PostgreSQL just being the big names that come to mind.  With this approach, the database engine does all the work looking up things and completely external to your application.  This has the benefit that it is possible to work with it with external tools, but has the side bit that it itself is an external tool.

Next is the simpler embedded databases.  Berkley Database, optionally through SQLLite as a layer to make accessing the data a bit more familiar to the SQL family.  The Berkley Database itself will fill the role of key value pairs (its a simple hash map behind the scenes).  This means getting other libraries (but not tools) to store your data.

Realizing that this is a dictionary of text there are specific data structures that are optimized to processing text structures.  The trie is a specialized tree for working with text.  This is just one of many data structures - the specifics of it really depend on what you are doing with your data once you have it.  The hash map is another way to store the data after it has been read (and there are many forms of the hash map too).

You may find that something else works better - it depends on what you are doing, how much data you have, the ratio of reads to writes (are there any writes at all?), knowing the size of the data before hand or not, if you want to be able to search on partial data, etc...  All of these things should come into play in choosing the correct data structure.


问:
How can you provide a public writeable API and not get spammed?
So say you had a site like StackExchange. Now imagine you created a machine-writeable API capable of posting questions and comments and doing everything your browser can do.

Of course, about 5 minutes after launching, you'd have so much spam that you would probably have ran out of room on your database servers and will have been permanently blacklisted from every search engine(except for maybe Ask :) )

So, how can you avoid that spam, while allowing a machine to actually use your API(and/or have automation involved? Is it possible in this day and age? I'd expect there is a human moderator at the end of it, but how do you cut down on the majority of spam to measures capable of being handled by human moderators?

答: There are a number of approaches.  First and foremost is requiring (human) signup and an API key; this allows you to require requests be signed, and that allows you to take the next step, which is throttling. Ever notice that Twitter has a limit on the number of calls you can make in an hour?  That's the most basic form of throttling.  You can also use rate-based throttling, which can return error messages if you're calling a service too quickly.  If someone persists in attempting to call the service after they've been throttled, they can be banned for an increasing amount of time--1 minute for the first offense, 2 minutes for the second, 4 for the third, and so on; a form of exponential back-off.  Audit trails mean that if someone is ultimately determined to be a spammer, you can just nuke their "contributions" all at once.</p>


答:
I ended up writing my own "proposal" for this, but I'm not sure how good of a solution it would actually be.

Anyway, take the concept of bitcoins and apply it to an API. Use a "difficulty" and a provided user-nonce value and require them to return with a hash value that includes the user-nonce and matches the difficulty/condition required.  You can take this concept and make it "difficult" to make API keys, and "easier" to make comments and such with your pre-made API key.

It's definitely not perfect, but would appear to be a method of allowing pure machine registration and "writing" to your API. And it's doubles as being accessible. No visual or audio captcha required.

I wrote a blog post about this idea that goes a bit more in-depth

Title: How can you provide a public writeable API and not get spammed?

Body:
So say you had a site like StackExchange. Now imagine you created a machine-writeable API capable of posting questions and comments and doing everything your browser can do.

Of course, about 5 minutes after launching, you'd have so much spam that you would probably have ran out of room on your database servers and will have been permanently blacklisted from every search engine(except for maybe Ask :) )

So, how can you avoid that spam, while allowing a machine to actually use your API(and/or have automation involved? Is it possible in this day and age? I'd expect there is a human moderator at the end of it, but how do you cut down on the majority of spam to measures capable of being handled by human moderators?


问:
Negative test cases confusion
In the Software testing book from Koirala, Sheihk, they say:

A positive test is when you put in a valid input and expect some
  action to be completed in accordance with the specification.

  A
  negative test is when you put in an invalid input and receive errors.

Part of my question:

Let's say there is a requirement: If the customer name=="James Bond", do something.

Is name<>"James Bond" negative or still positive test, verifying the requirement?

Or a login function:

Is correct login positive test case and incorrect negative?

Or Login failed is just confirmation of requirement that a password must be correct ->confirming invalid pass will not work.

For example, if the program is supposed to give an error when the person types in "101" on a field that should be between 1 and 100, then that is positive then if an error shows up. If, however, the application does not give an error when user types 101, then you have a negative test.

答:
Let me try to resolve your confusion in simple words.

Negative Test is a test designed to determine the response of the system outside of what is defined. So any kind of input which is not as per the design or requirement of the system is a part of negative test and your system should be capable enough to handle it. it should not crash or throw an unexpected error.

Title: Negative test cases confusion

ContentLicense: CC BY-SA 4.0


答:
We have a separate project "utilities" where we store all these small methods together with tests.

When a project need some utility it just adds the source file with the required method with "add as link".

This means that there are no run time dependencies added (unless the included file need one).

The system has worked well but like all others it needs diciplin on what is a utility. Requiering high test coverage has worked well for us and tests are also good usage documentation. Discovery is still an unsolved issue for us.

One complexity with the utility project is to decide visibility level on items.  A rule of thumb is that methods should be internal and data structures public.


问:
Ambiguous use of "Controller" in MVC
I have heard two separate uses for the term controller when speaking of the Model View Controller methodology.

An intermediary section of code that communicates between the Model and View, tying them together.

The module that deals with input, similarly to how the view deals with output.

For starters, which definition is correct?  I have read more that use the first definition than the second, with the second being the first one I learned.

In addition, it seems to me that both of those things are useful - indeed, when I've used MVC-like designs, I've used both of those things in some way (even if I only ever called one of them the controller).  Should MVC really be defined in a way that includes both of these things?  That would mean that the architecture contains the model, an input module, an output module, and an intermediate module to connect them all, and that just makes sense to me.

答:
If you go to the origin of the MVC methodology, which lies with Smalltalk 80 about 20 years ago, then the second definition is the correct one.

In that time the OS support for user interfaces was still rather limited and most of it had to be done by the applications themselves. Within MVC, a collection of views would be responsible for updating the correct portions of the screen, while a collection of controllers (one for each view) figured out what to do with each key press.

In modern days, the OS takes most of the burden of figuring out what to do with a key press and the application only gets to know about it through the view components when the user confirms their data entry.
This means that the controller of old has no place any more in a modern application, because its role is taken up by a combination of the view and the OS.

At the same time, the view classes get provided more and more by the OS or generig frameworks and thus they become more and more generic. This is where the first definition of controller fits in: To deal with the changing demands and responsibilities, the controller morphed into more of a glue component that ties the generic view classes with the application-specific (and GUI-agnostic) model.

To sum it all up, both definitions of controller are (in historic perspective) correct, but the first one is the more relevant nowadays.

Title: Ambiguous use of "Controller" in MVC


问:
What tools can I use for professional document-creation and -printing in PHP?
I'm in the process of building a new pledge management system for one of my clients, a charity foundation. I have already built one for them (it was done using Delphi), but its feature-set is a little limited.

Now, I have decided to move to PHP and use the Laravel framework to manage the database for the new system - its Eloquent ORM allows me to easily implement new features that are needed at present. This is good and well – I know everything that I need to do there. However, I am not sure which direction to take for when it comes to creating, saving, and printing documents that will be hand-delivered to donors.

At the moment, it used Word to process documents - i.e. creating invoices, letters of appreciation, and any other templates that may be selected during a pledge submission. The thing is, I am not extremely happy with the implementation, and don’t believe this is the best route to take. There have been times where the documents did not print correctly, or multiple documents where printed (where only one was needed).

Nonetheless, I could stick to Word, provided that PHP can handle it properly and show me progress as it goes along (i.e. Opening Word -> Opening Invoice Template (companies) -> Replacing Variables -> Saving -> Printing -> Closing -> Opening Food Project Mission Statement -> Replacing Variables - > Saving -> Printing -> Closing … etc.). I guess that progress notifications are not necessary, but I would like to have them there - just in case it freezes, the user would be able to see whatever it may be struggling with.

I would assume that I could do this using a jQuery script (with AJAX) that interfaces with a PHP script, but I honestly have no idea how to do it. (Note: I’d have to use AJAX as Laravel uses buffered output.)

I also know that I could pass the information about a pledge to an EXE which would handle the printing on its own, but I don’t think I want to use this implementation as I have plans to make the system cross-platform.

Question 1: Is there a package for PHP that allows me to create documents, save them, and then print them? If not, is there a suitable package that handles Word without difficulty, and with a large array of features?

If it is the latter, I would need to be able to access the full COM API so that I can prevent dialogs from popping up in the background and pausing the procedure.

Question 2: Is there a package (jQuery, AJAX) available that would allow me to track the progress of the document-creation procedure?

EDIT

Having reconsidered everything, and weighed the pro's and con's, I would like to put emphasis on printing here. When the user submits a pledge to the database, I need the document to print immediately. I do not necessarily want to focus on a document creation tool only. The reason I asked my question as I did is because I would, ideally, like to find something that can do both the creation and printing of each document. In addition, I do not want to make it too difficult for myself. This is why I originally chose Word - and, it was a lot easier to manage from a Delphi application.

Because of this, I will be leaving the question open (just in case something very interesting is proposed), but will be asking a new question that is a little more specific to the problem that this question originated from.

(To those who have answered so far, thank you for your help and showing me the various options.)

答:
I dont believe PHP alone is well-suited for that task and would suggest looking at LaTex, as long as you can work with PDFs, instead of Word-files.

Latex is primarily used for scientific essay typesetting, but it can do anything related to typesetting and text layout. In science, it commonly replaces word. The .tex-documents are text files that are mostly written by hand, but as its a text file, using php is straightforward.

In your case, the workflow is the following:

Use PHP to load the data you want to print

Have a PHP script to generate a .tex-file

compile the latex file to a pdf.'


问:
Communication between View and Model
I have a basic issue with the MVC architecture. I am aware that the View usually listens to the Model. But how are user requests propagated to the Model?

Currently I do it like this, when the user clicks e.g. the update Button in the GUI. So the ActionListener calls a method of the View. The View calls a method of the Controller. And the Controller calls a method of the Model.

But I have three concedrns about this.

The View must be aware of the Controller.

The long call chain seem to be not the right way

With the number of user actions, the number of those call chains increase.

What are the best practises here?

答:
You're not using MVC correctly. The ActionListener for that button is (part of) the controller in this case.

When a button is clicked, you want to update your model with your new data. The View will automatically update itself.

I suggest you read this:

http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller#Dependency_hierarchy

"The View however, knows about the Model. It will poll the Model about the state, to know what to display. That way, the View can display something that is based on what the Model has done. But the View knows nothing about the Controller."

Title: Communication between View and Model


答: You can use what best suits your needs, but in MVC architecture the Controller send information to the View. The View never use the Model but what the Controller gives him. </p>

Title: Communication between View and Model

Body:
I have a basic issue with the MVC architecture. I am aware that the View usually listens to the Model. But how are user requests propagated to the Model?

Currently I do it like this, when the user clicks e.g. the update Button in the GUI. So the ActionListener calls a method of the View. The View calls a method of the Controller. And the Controller calls a method of the Model.

But I have three concedrns about this.

The View must be aware of the Controller.

The long call chain seem to be not the right way

With the number of user actions, the number of those call chains increase.

What are the best practises here?


答: LaTex will do it, but you could try ASCIIdoc or ReStructuredText instead, both are lightweight formatting systems. Using docUtils, most will produce output in different formats, including .odt which is as good as .doc and can be loaded in Word or LibreOffice if that matters to you more than pdf.</p>

Title: What tools can I use for professional document-creation and -printing in PHP?

Body:
I'm in the process of building a new pledge management system for one of my clients, a charity foundation. I have already built one for them (it was done using Delphi), but its feature-set is a little limited.

Now, I have decided to move to PHP and use the Laravel framework to manage the database for the new system - its Eloquent ORM allows me to easily implement new features that are needed at present. This is good and well – I know everything that I need to do there. However, I am not sure which direction to take for when it comes to creating, saving, and printing documents that will be hand-delivered to donors.

At the moment, it used Word to process documents - i.e. creating invoices, letters of appreciation, and any other templates that may be selected during a pledge submission. The thing is, I am not extremely happy with the implementation, and don’t believe this is the best route to take. There have been times where the documents did not print correctly, or multiple documents where printed (where only one was needed).

Nonetheless, I could stick to Word, provided that PHP can handle it properly and show me progress as it goes along (i.e. Opening Word -> Opening Invoice Template (companies) -> Replacing Variables -> Saving -> Printing -> Closing -> Opening Food Project Mission Statement -> Replacing Variables - > Saving -> Printing -> Closing … etc.). I guess that progress notifications are not necessary, but I would like to have them there - just in case it freezes, the user would be able to see whatever it may be struggling with.

I would assume that I could do this using a jQuery script (with AJAX) that interfaces with a PHP script, but I honestly have no idea how to do it. (Note: I’d have to use AJAX as Laravel uses buffered output.)

I also know that I could pass the information about a pledge to an EXE which would handle the printing on its own, but I don’t think I want to use this implementation as I have plans to make the system cross-platform.

Question 1: Is there a package for PHP that allows me to create documents, save them, and then print them? If not, is there a suitable package that handles Word without difficulty, and with a large array of features?

If it is the latter, I would need to be able to access the full COM API so that I can prevent dialogs from popping up in the background and pausing the procedure.

Question 2: Is there a package (jQuery, AJAX) available that would allow me to track the progress of the document-creation procedure?

EDIT

Having reconsidered everything, and weighed the pro's and con's, I would like to put emphasis on printing here. When the user submits a pledge to the database, I need the document to print immediately. I do not necessarily want to focus on a document creation tool only. The reason I asked my question as I did is because I would, ideally, like to find something that can do both the creation and printing of each document. In addition, I do not want to make it too difficult for myself. This is why I originally chose Word - and, it was a lot easier to manage from a Delphi application.

Because of this, I will be leaving the question open (just in case something very interesting is proposed), but will be asking a new question that is a little more specific to the problem that this question originated from.

(To those who have answered so far, thank you for your help and showing me the various options.)


问:
JavaScript codes complexity and maintainability
I am trying to make my way back to JavaScript (been there last time some 7 years ago) with the help of lovely "Eloquent JavaScript" book.

While I admire author's capabilities and approach, I have also began being concerned. I am from C/C++ background and there I learnt it rather hard way that funky constructs often undermine project survival.

Experience with the Perl proved different. Being capable of cool tricks seemed a valuable perk.

So, what is the common view upon JavaScript code complexity. Does using it at "full speed" (OOP done own way, higher order functions everywhere etc) help having maintainable projects? Thanks for your answers

答:
in my opinion is hard to maintain  js code of a project by using pure java script code. I recommend to use java script libraries like jQuery. Also you may take note that js code can be written in OOP manner. Some documentation you can find here.

So, my common view upon JavaScript code complexity and maintainability is to use java script libraries/frameworks in order to reduce/handle complexity, and also it help you to standardize the code, from where it results a easier way to maintain it. You may also consider to use OOP paradigm in your java script code.


问:
Efficient way to create a code estimation/technical specification in a fast-moving environment
To better understand my question, let me elaborate the background of the subject matter.

I work in a financial institution where the business module (credit finance) is constantly changing. In the IT world, however, the developers have a 6 week cycle taking list of projects/enhancements, put it in a timeline and business expect delivery on those projects.

During each cycle, each developer gets assigned work that needs to be completed by a certain date. That date is already finalized by IT Change Managers and codes must be done by then. The code will then be synced, built to create a package and deployed to the test environment for QC (Quality Centre) team to test.

The problem, however, is that developers get given the code 3 weeks before the code cycle ends. We are then told to do a technical specification and work estimation for each project/enhancements/bug fixes we are going to do. I have constantly talked to my managers that that is a backward mentality having to do estimations knowing when we need to deliver the finished code.

My challenge: Is there a better estimation/technical specification model that cater for this kind of environment? If not, how can I tackle this issue such that it doesn't conflict with the deadline.

Thanks.

PS: I totally disagree in providing a business requirement to developers and expecting them to do a technical specification document as well as estimations during a code cycle. I do believe that technical specification document should be done before-hand and completed as well with functional/non-functional document and signed off by business. This is not happening currently.

答:
Is there a better estimation/technical specification model that cater
for this kind of environment?

Try using Steps of the Scientific Method

Try Evidence Based Scheduling


答:
There are a number of choices available to you here.

If Word output is a hard requirement, look into docx - it's basically zipped up XML, so generating it in PHP should be fairly straightforward - collect your data, throw it in an XML format, and convert it to Word XML with XSLT, then zip it up.

If PDF is acceptable, LaTeX is your tool of choice - it produces beautiful output, and its automated typesetting is much, much better than anything Word can ever hope for. Generating TeX source directly from PHP can be a bit daunting, especially if you are not familiar with it, but you can go through an intermediate format. DocBook is one option; there is an excellent docbook-to-latex converter called dblatex. Another option is Pandoc, a tool that can convert from a dozen markup languages (including HTML, markdown, ReStructured Text and Textile) into two dozen or so output formats, including LaTeX. Incidentally, Pandoc can also output .odt and .docx directly, so that might also be an option.

Finally, there are some PDF libraries for PHP that would allow you to output PDF directly, but they are either limited in functionality, or proprietary and expensive, or both. Almost all of them require you to do your own text flowing, and you absolutely don't want that, because, frankly, it is really really hard to get right.


答:
Some people may not like javascript frameworks, but the fact that such frameworks are popular means that they really help to structure your code and make it more maintainable.

The most popular framework seems to be backbone.js, they even explicitlly say that Backbone.js gives structure to web applications.
It looks like some kind of a MVC framework, i.e. data are stored in models, they are rendered by views and also there is a router (like controller) that makes http requests.

Some people prefer knockout.js which uses different pattern which is called Model-View-ViewModel instead of MVC. Promoted by Microsoft.

Angular.js is popular too, but it isn't a pure javascript framework and it uses lot of HTML annotations. Promoted by Google.

Also there are lot of frameworks that look like backbone.js but slightly different, for example ember.js.

In conclusion I can say that javascript frameworks became very popular recently and maintenability isn't an issue anymore.

Title: JavaScript codes complexity and maintainability

Body:
I am trying to make my way back to JavaScript (been there last time some 7 years ago) with the help of lovely "Eloquent JavaScript" book.

While I admire author's capabilities and approach, I have also began being concerned. I am from C/C++ background and there I learnt it rather hard way that funky constructs often undermine project survival.

Experience with the Perl proved different. Being capable of cool tricks seemed a valuable perk.

So, what is the common view upon JavaScript code complexity. Does using it at "full speed" (OOP done own way, higher order functions everywhere etc) help having maintainable projects? Thanks for your answers