问:
How to deal with data on the model specific to the technology being used?
There are some cases where some of the data on a class of the domain model of an application seems to be dependent on the technology being used. One example of this is the following: suppose we are building one application in .NET such that there's the need of an Employee class. Suppose further that we are going to implement relational database, then the Employee has a primary key right? So that the classe would be something like

```<code>public class Employee
{
     public int EmployeeID { get; set; }
     public string Name { get; set; }
     ...
}
</code>```

Now, that EmployeeID is dependent on the technology right? That's something that has to do with the way we've choose to persist our data. Should we write down a class independent of such things? If we do it this way, how should we work? I think I would need to map all the time between domain model and persistence specific types, but I'm not sure.

答:
No. You need an ID whenever you want to uniquely identify something. My id card/passport has an ID that uniquely identifies me as a specific citizen. This has nothing to do with it being a piece of laminated paper.

Likewise, you will probably need an employee ID for organizational purposes. I encourage you to re-use this existing ID in a database schema, but this has nothing to do with databases. Your confusion may have arisen by implicitly using a memory location as an ID for most of your objects. However, memory locations are only unique at a certain point in time, on one single system. Therefore, they cant be used for serializations.


问:
Is an event loop just a for/while loop with optimized polling?
I'm trying to understand what an event loop is. Often the explanation is that in an event loop, you do something until you're notified that an event has occurred. You then handle the event and continue doing what you were doing before.

To map the above definition with an example. I have a server which 'listens' in a event loop, and when a socket connection is detected, the data from it gets read and displayed, after which the server resumes/starts listening as it did before.

However, this event happening and us getting notified 'just like that' are to much for me to handle. You can say: "It's not 'just like that' you have to register an event listener". But what's an event listener but a function which for some reason isn't returning. Is it in it's own loop, waiting to be notified when an event happens? Should the event listener also register an event listener? Where does it end?

Events are a nice abstraction to work with, however just an abstraction. I believe that in the end, polling is unavoidable. Perhaps we are not doing it in our code, but the lower levels (the programming language implementation or the OS) are doing it for us.

It basically comes down to the following pseudo code which is running somewhere low enough so it doesn't result in busy waiting:

```<code>while(True):
    do stuff
    check if event has happened (poll)
    do other stuff
</code>```

This is my understanding of the whole idea, and I would like to hear if this is correct. I'm open in accepting that the whole idea is fundamentally wrong, in which case I would like the correct explanation.

答:
Most event loops will suspend if there are no events ready, which means the operating system will not give the task any execution time until an event happens.

Say the event is a key being pressed.  You might ask if there's a loop somewhere in the operating system checking for keypresses.  The answer is no.  Keys being pressed generate an interrupt, which is handled asynchronously by the hardware.  Likewise for timers, mouse movements, a packet arriving, etc.

In fact, for most operating systems, polling for events is the abstraction.  The hardware and OS handle events asynchronously and put them in a queue that can be polled by applications.  You only really see true polling at the hardware level in embedded systems, and even there not always.

ContentLicense: CC BY-SA 4.0


答: Typically the answer is hardware, the OS and background threads you don't control conspire to make it look effortless.  The network card receives some data it raises an interrupt to let the CPU know.  The OS's interrupt handler handles it.  Then a background thread you don't control (that was created by registering for the event and has been sleeping ever since you registered for the event) is woken up by the OS as part of handling the event and runs your event handler. </p>

Title: Is an event loop just a for/while loop with optimized polling?

Body:
I'm trying to understand what an event loop is. Often the explanation is that in an event loop, you do something until you're notified that an event has occurred. You then handle the event and continue doing what you were doing before.

To map the above definition with an example. I have a server which 'listens' in a event loop, and when a socket connection is detected, the data from it gets read and displayed, after which the server resumes/starts listening as it did before.

However, this event happening and us getting notified 'just like that' are to much for me to handle. You can say: "It's not 'just like that' you have to register an event listener". But what's an event listener but a function which for some reason isn't returning. Is it in it's own loop, waiting to be notified when an event happens? Should the event listener also register an event listener? Where does it end?

Events are a nice abstraction to work with, however just an abstraction. I believe that in the end, polling is unavoidable. Perhaps we are not doing it in our code, but the lower levels (the programming language implementation or the OS) are doing it for us.

It basically comes down to the following pseudo code which is running somewhere low enough so it doesn't result in busy waiting:

```<code>while(True):
    do stuff
    check if event has happened (poll)
    do other stuff
</code>```

This is my understanding of the whole idea, and I would like to hear if this is correct. I'm open in accepting that the whole idea is fundamentally wrong, in which case I would like the correct explanation.

ContentLicense: CC BY-SA 3.0


答:
I think of an event listener not as a function running its own loop, but as a relay race with the first runner waiting for the starting gun.  A significant reason for using events instead of polling is that they are more efficient with CPU cycles.  Why?  Look at it from the hardware up (rather than the source code down).

Consider a Web server.  When your server calls listen() and blocks, your code is taking its place as a relay runner.  When the first packet of a new connection arrives, the network card starts the race by interrupting the operating system.  The OS runs an interrupt service routine (ISR) that grabs the packet.  The ISR passes the baton to a higher-level routine that establishes the connection.  Once the connection is alive, that routine passes the baton to listen(), which passes the baton up to your code.  At that point, you can do what you want with the connection.  For all we know, between races each relay runner could be going to the pub.  A strength of the event abstraction is that your code doesn't have to know or care.

Some operating systems include event-handling code that runs its portion of the race, hands off the baton, then loops back to its starting point to wait for the next race to start.  In that sense, event handling is optimized polling in lots of concurrent loops.  However, there is always an outside trigger that kicks off the process.  The event listener is not a function that isn't returning, but a function that is waiting for that external trigger before it runs.  Rather than:

```<code>while(True):
    do stuff
    check if event has happened (poll)
    do other stuff
</code>```

I think of this as:

```<code>on(some event):    //I got the baton
     do stuff
     signal the next level up    //Pass the baton
</code>```

and between the signal and the next time the handler runs, there is conceptually no code running or looping.

Body:
I think of an event listener not as a function running its own loop, but as a relay race with the first runner waiting for the starting gun.  A significant reason for using events instead of polling is that they are more efficient with CPU cycles.  Why?  Look at it from the hardware up (rather than the source code down).

Consider a Web server.  When your server calls listen() and blocks, your code is taking its place as a relay runner.  When the first packet of a new connection arrives, the network card starts the race by interrupting the operating system.  The OS runs an interrupt service routine (ISR) that grabs the packet.  The ISR passes the baton to a higher-level routine that establishes the connection.  Once the connection is alive, that routine passes the baton to listen(), which passes the baton up to your code.  At that point, you can do what you want with the connection.  For all we know, between races each relay runner could be going to the pub.  A strength of the event abstraction is that your code doesn't have to know or care.

Some operating systems include event-handling code that runs its portion of the race, hands off the baton, then loops back to its starting point to wait for the next race to start.  In that sense, event handling is optimized polling in lots of concurrent loops.  However, there is always an outside trigger that kicks off the process.  The event listener is not a function that isn't returning, but a function that is waiting for that external trigger before it runs.  Rather than:

while(True):
    do stuff
    check if event has happened (poll)
    do other stuff

I think of this as:

on(some event):    //I got the baton
     do stuff
     signal the next level up    //Pass the baton

and between the signal and the next time the handler runs, there is conceptually no code running or looping.


问:
Why do large IT projects tend to fail or have big cost/schedule overruns?
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?

答:
Cost does not preclude schedule in the eyes of 'management' which is an important distinction to make. As we know, "nine women can't make a baby in one month", yet you'd be surprised at how many people think that problems decrease in depth in relation to the amount of money that is thrown at them. Bad project management, often manifesting itself in the form of micro management is the leading cause of most projects tanking (in my experience). Micro management kicks in when 'management' realizes that something is getting out of control and they are clueless as to why.

When that isn't the cause, the expected outcome of the project was probably not tenable to begin with. In my experience, if the time frame of a project is too short, people will be so afraid of making mistakes that result in 'double work' that they don't get much of anything done at all.

This is why management should be populated with seasoned programmers who have a history of leading teams that produced successful projects. Such a person might say "No way could we do that responsibly" despite the possible revenue, and would not be in management for long, which is why many of us (ultimately) answer to MBA's instead of PHD's.

I lost count of the number of companies that I've worked for where a non-programmer was in charge of hiring programmers. I had an interview once where the hiring manager wanted to do nothing but discuss a recent sporting event (I think it was a football game). If the person you have in charge draws more inspiration from an NFL coach than Knuth, the project is going to tank.

Once in a while, you run into something that was well planned, well understood, realistic and seemingly straight forward. For whatever reason, six months into development, everything reversed itself. It happens. Rarely, however is that the underlying cause of a project becoming a glorified pork barrel.

Still, I have to admit .. if you watch the news, you might see an occasional motorcycle accident or train wreck. You never hear about the millions of motorcycles or trains that arrive on time every day without incident. The same goes with projects. Sure, it's interesting to see a public autopsy of something that went really, really bad, but you almost never hear about stuff that went really, really well. I think that tanked projects are still the exception, not the norm.

ContentLicense: CC BY-SA 2.5


问:
How can I introduce QA and break it into parts for various people?
I was recently asked how to do this, specifically:

How to introduce QA into an organization?

How to break up QA into parts that others can do ?

How to prioritize what needs QA?

How to determine what to buy? code? etc.

The organization uses Rails on Rails extensively as the development platform

Note:  I am posting a lengthy answer myself but I will also upvote additional good answers (and probably incorporate them into my answer).

答:
Your assignment1 is not a good one because it doesn't have any specific or measurable goals for success2. Once you've defined your goals the rest of the process falls into place.

1. How to introduce QA into an organization? [Choose Metrics]

Here's the process to follow:

Choose your goals (an improvement in some metric).

Before you change anything, do some measurements and see how you're currently performing3.

For demonstration purposes pick a couple sample metrics4:

Down-time

Regression bugs introduced

1. I'm assuming this question is about adopting new QA processes into an existing department.

2. What does it mean for quality to be "baked-in"?

3. Oddly enough you may find out that measuring something, paying explicit attention to it, solves the problem.

4. I picked these at random to show how the process works.

2. How to break up QA into parts that others can do? [Implement Changes]

This is the step when you make a single change, per goal, and then measure the results.

You have lots of options here. You might choose to pick a single person to champion each change and try to prove its effectiveness.

For reducing down-time you could implement:

System monitoring (AlertSite)

Testing of critical infrastructure

For reducing regression bugs you could implement:

unit testing

code reviews

3. How to prioritize what needs QA?

This should be the first step. What needs QA is something that has an associated metric that you're trying to improve.

4. How to determine what to buy? code? etc. [Automate What's Proven to Work]

Don't start thinking about what you can buy when the process starts. Only after you make a change and see that some metric has improved, should you consider automating that change.

For anyone who is better than I am at formatting posts feel free to change anything above


问:
Prefer examples over documentation. Is it a behavioral problem?
Whenever I come across a new API or programming language or even simple Linux man pages, I always (ever since I remember) avoided them and instead lazily relied on examples for gaining understanding of new concepts.

Subconsciously, I avoid documentation/APIs whenever it is not straightforward or cryptic or just plain boring. It's been years since I began programming and now I feel like I need to mend my ways as I now realize that I'm causing more damage by refraining from reading cryptic/difficult documentation as it is still a million times better than examples as the official documentation has more coverage than any example out there. Even after realizing that examples should be treated as "added" value instead of the "primary" source for learning.

How do I break this bad habit as a programmer or am I overthinking?

答: Different people learn better in different ways. Some people are like you and learn better from examples. Some people are like me and learn better from detailed documentation. Having both in the documentation seems to cover most developers pretty well. Talk to a teacher, they can tell you half a dozen ways people learn.</p>


问:
Is "Free for non-commercial use" license compatible with GNU GPLv3 license?
I want to ask whether any materials that has "Free for non-commercial use" license can be used in a GNU GPLv3 licensed software.

In my opinion, it is "free for non-commericial use", and GNU GPLv3 is also non-commericial, so it can be used in the software,  is it?

I'm asking this question because there are no explicit or clear declaration about "FREE FOR NON-COMMERCIAL USE" license out there....

答:
Definitely not.  GPLv3 allows for both commercial and non-commercial use.  Other than the license itself, which does not restrict commercial use, see this GPL FAQ answer:

Q: If I use a piece of software that has been obtained under the GNU GPL,
  am I allowed to modify the original code into a new program, then
  distribute and sell that new program commercially?

A: You are allowed to sell copies of the modified program commercially,
  but only under the terms of the GNU GPL. Thus, for instance, you must
  make the source code available to the users of the program as
  described in the GPL, and they must be allowed to redistribute and
  modify it as described in the GPL.

Also there is this page about selling free software, which is not talking about the GPL specifically.

OwnerDisplayName: Jewel


答:
I am going to go against all of the other answers I see so far and say "yes". I think the other answers are complicating things too much. From a conceptual point of view, all event loops are essentially:

```<code>while <the_program_is_running> {
    event=wait_for_next_event()
    process_event(event)
}
</code>```

If you are trying to understand event loops for the first time, thinking of them as a simple loop will do no harm. Some underlying framework is waiting for the OS to deliver an event, it then routes the event to one or more handlers, then waits for the next event, and so on. That's really all there is to it from an application software perspective.

Body:
I am going to go against all of the other answers I see so far and say "yes". I think the other answers are complicating things too much. From a conceptual point of view, all event loops are essentially:

while <the_program_is_running> {
    event=wait_for_next_event()
    process_event(event)
}

If you are trying to understand event loops for the first time, thinking of them as a simple loop will do no harm. Some underlying framework is waiting for the OS to deliver an event, it then routes the event to one or more handlers, then waits for the next event, and so on. That's really all there is to it from an application software perspective.


问:
Why does a proportional controller have a steady state error?
I've read about feedback loops, how much this steady state error is for a given gain and what to do to remove this steady state error (add integral and/or derivative gains to the controller), but I don't understand at all why this steady state error occurs in the first place.

If I understand how a proportional control works correctly, the output is equal to the current output plus the error, multiplied by the proportional gain (Kp).  However, wouldn't the error slowly diminish over time as it is added (reaching 0 at infinite time), not have a steady state error?  From my confusion, it seems I'm completely misunderstanding how it works - a proper explanation of how this steady state error eventuates would be fantastic.

答:
The controller you are describing where you keep adding the error times a constant to the current output value is an Integrator.  You are clearly integrating the error.  A proportional controller would be setting the output to P times the error.  It also matters what the output controls, e.g. whether it's torque, or position, or velocity for a motor control system.  (something proportional in velocity is integral in torque...)

The reason for a steady state error with P only is that as your system approaches the set-point the error signal gets smaller and smaller.  Your control is Kp times that error signal and eventually the error will be small enough that Kp times the error won't be enough to force it all the way to zero.

An Integrator "saves the day" by accumulating the error over time and therefore even the tiniest error will eventually accumulate to something large enough to force the controller to correct for it.

As an example let's look at a P temperature controller for an oven.  We have a heating element and we control the current to that element.  Our set-point is 100 degrees.  The oven is constantly losing heat to the outside environment (which is lets say at 0 degrees).  We start up at an error of 100 and let's say our P is set such that this is 10A.  If P is set too large the system is going to be unstable but if we assume stability at some point the error will be so small such that P*error isn't going to be enough to overcome the heat loss of the oven to the environment.  You will reach equilibrium away from your set-point.


问:
Pushing complete notifications to client
So with cqrs, we accept that consistency is eventual.

However, that doesn't mean that the user has to continually poll, or that eventual means an update has to take more then 500ms to sync.

For the sake of UX, we want to at least give the illusion of consistency, or if not possible, be as transparent as possible.

With that in mind, I have this setup:

angularjs web client, consumes

webapi restful services, sends commands to

nservicebus command handlers, saves to

neventstore, dispatches events to

nservicebus event handlers, sends message to

signalr hub, sends notifications to

angularjs web client

so with that setup, theoretically

some initiates a request

the server validates the request

sends out the necessary commands

In the mean time

the client gets a 200 response

updates the view: working on it

gets message sometime later: done, here's the updated data

Here's where things get interesting, each command could spawn multiple events. Not sure if this is a serious no, no, or not, but that's how it is  currently. For example, a new customer spawns CustomerIDCreated, CustomerNameUpdated, CustomerAddressUpdated, etc...

Which event handler needs to notify the client? Should all of them in a progress bar style update?

答:
Broadly speaking, an event handler should notify the client if the client is (or might be) interested in the information.

However, the granularity of the message is important.

Remember that whenever you end up passing information over the network you move from the realm of sub-microsecond processing to multi-milliseconds of elapsed time.

For this reason, I'm not convinced the fine granularity of events that you described is appropriate.

Jim Webber has a fair bit to say on the subject, recommending that the granularity should be similar to what you'd use if the service was an actual person in a mid to large size business. In your case, a single CustomerUpdated message instead of multiple smaller messages.


问:
Name of the Countdown Numbers round problem - and algorithmic solutions?
For the non-Brits in the audience, there's a segment of a daytime game-show where contestants have a set of 6 numbers and a randomly generated target number. They have to reach the target number using any (but not necessarily all) of the 6 numbers using only arithmetic operators. All calculations must result in positive integers.

An example: Youtube: Countdown - The Most Extraordinary Numbers Game Ever?

A detailed description is given on Wikipedia: Countdown (Game Show)

For example:

The contentant selects 6 numbers - two large (possibilities include 25, 50, 75, 100) and four small (numbers 1 .. 10, each included twice in the pool).

The numbers picked are 75, 50, 2, 3, 8, 7 are given with a target number of 812.

One attempt is (75 + 50 - 8) * 7 - (3 * 2) = 813 (This scores 7 points for a solution within 5 of the target)

An exact answer would be (50 + 8) * 7 * 2 = 812 (This would have scored 10 points exactly matching the target).

Obviously this problem has existed before the advent of TV, but the Wikipedia article doesn't give it a name. I've also saw this game at a primary school I attended where the game was called "Crypto" as an inter-class competition - but searching for it now reveals nothing.

I took part in it a few times and my dad wrote an Excel spreadsheet that attempted to brute-force the problem, I don't remember how it worked (only that it didn't work, what with Excel's 65535 row limit), but surely there must be an algorithmic solution for the problem. Maybe there's a solution that works the way human cognition does (e.g. in-parallel to find numbers 'close enough', then taking candidates and performing 'smaller' operations).

答:
Disclaimer: This answer does not answer the question that completely. But it's too long for a comment.

NP-hard? I believe, this problem could be NP-hard.

Consider a special case of the Knapsack problem:

Given a set of positive integers and a positive integer b, does there exist a subset of the set such that the sum of all integers in that subset equals b?

This sounds somewhat similar to our Countdown problem, and it seems to be much simpler. However, Knapsack (and this special case of Knapsack) is NP-hard (and NP-complete, of course).

I did not manage to use this for a proof that Countdown is NP-hard. I could not get rid of the division. Consider we have a thousand 2, and b = 7. This will never be solvable with Knapsack, but always (?) with Countdown, at least in all the ways I tried to transfer the problem.

Now, if Countdown really was NP-hard, we could deduce that there with very high probability is no algorithm that is significantly more efficient than brute-force trying all possibilities. (And if we should find such an algorithm, we will become very famous.)

No, I don't think there must be an efficient algorithm.

Heuristics. The Youtube video linked in the question has a nice example: The contestant found an exact answer 952 = ((100 + 6) * 3 * 75 - 50) / 25. That is completely against my intuition, I would never have tried it that way in the first time: Produce a very large number, then divide it and yield the result.

On the other, we humans feel that we do not need to try (arbitrary example) 50 * 75 * 100 / 2 / 3 / 7 to reach a three-digit-number. But computers do not feel anything, they simple calculate.

After all, if we implemented some heuristics, and this heuristics does not find an exact solution, we still will have to try all other solutions to make sure there really is none.

What the contestant in the Youtube video does is, I think, to very quickly check a large number of possibilities and to quickly discard those that will not (or likely will not) give a solution.

Conclusion. When implementing an algorithm, one could take care to strip equal calculations such as a / b / c = a / (b * c), but I think this is quite hard to do and I do not know whether this improves the runtime significantly.

Computers of course are faster than humans in checking a large number of possibilities. And nowadays, even smartphones are so fast they can solve this problem, I think, within a second by simply trying all possibilities. (I did not test this.) There are only six numbers, it would be different if there were e.g. 60 of them.


问:
C programming multiple storage backends
I am starting a side project in C which requires multiple storage backends to be driven by a particular piece of logic. These storage backends would each be linked with the decision of which one to use specified at runtime.

So for example if I invoke my program with one set of parameters it will perform the operations in memory but if I change the program configuration it would write to disk.

The underlying idea is that each storage backend should implement the same protocol. In other words the logic for performing operations should need to know which backend it is operating on.

Currently the way I have thought to provide this indirection is to have a struct of function pointers with the logic calling these function pointers. Essentially the struct would contain all the operations needed to implement the higher level logic E.g.

```<code>struct Context {
    void (* doPartOfDoOp)(void)
    int (* getResult)(void);
}

//logic.h
void doOp(Context * context) {
    //bunch of stuff
    context->doPartOfDoOp();
}

int getResult(Context * context) {
    //bunch of stuff
    return context->getResult();
}
</code>```

My questions is if this way of solving the problem is one a C programmer would understand? I am a Java developer by trade but enjoy using C/++. Essentially the Context struct provides an interface like level of indirection. However I would like to know if there is a more idiomatic way of achieving this.

答:
Yes, a seasoned C programmer would certainly understand such constructs. Using function pointers is just about the only way you have in C to select at runtime which of a set of functions to execute.

Ans storing function pointers in a struct gives a very clear signal that those functions belong together and is a very common way to emulate methods/member-functions in C.

One change I would advise is to pass the Context struct also as a 'this pointer' to the function pointers, like this:

```<code>struct Context {
    void (* doPartOfDoOp)(struct Context*)
    int (* getResult)(struct Context*);
};

//logic.h
void doOp(Context * context) {
    //bunch of stuff
    context->doPartOfDoOp(context);
}

int getResult(Context * context) {
    //bunch of stuff
    return context->getResult(context);
}
</code>```

In C, if you have a pointer to the first member of a struct, then you can cast that pointer to the struct type itself and use it to access the other members. This allows you to build a kind of inheritance tree and makes it possible to give your back-ends "member variables", like this:

```<code>struct FileBackend {
    struct Context interface;
    FILE* file;
}

void doPartOfDoOpFileBackend(struct Context* context)
{
    struct FileBackend* this = (struct FileBackend)context;
    // do stuff, accessing the file through this->file.
}
</code>```

Title: C programming multiple storage backends

Body:
Yes, a seasoned C programmer would certainly understand such constructs. Using function pointers is just about the only way you have in C to select at runtime which of a set of functions to execute.

Ans storing function pointers in a struct gives a very clear signal that those functions belong together and is a very common way to emulate methods/member-functions in C.

One change I would advise is to pass the Context struct also as a 'this pointer' to the function pointers, like this:

struct Context {
    void (* doPartOfDoOp)(struct Context*)
    int (* getResult)(struct Context*);
};

//logic.h
void doOp(Context * context) {
    //bunch of stuff
    context->doPartOfDoOp(context);
}

int getResult(Context * context) {
    //bunch of stuff
    return context->getResult(context);
}

In C, if you have a pointer to the first member of a struct, then you can cast that pointer to the struct type itself and use it to access the other members. This allows you to build a kind of inheritance tree and makes it possible to give your back-ends "member variables", like this:

struct FileBackend {
    struct Context interface;
    FILE* file;
}

void doPartOfDoOpFileBackend(struct Context* context)
{
    struct FileBackend* this = (struct FileBackend)context;
    // do stuff, accessing the file through this->file.
}


问:
How do I decide to which class a method should belong
I have TopicBusiness.class and PostBusiness.class. I have no problem with deciding into which class methods such as addPostToDatabase() or getAllPostsFromDatabase() should go. But what about getAllPostsFromTopic(TopicEntity topic) or getNumberOfPostsInTopic(TopicEntity topic)?

Should the parameter be the deciding factor? So when the method takes TopicEntity as parameter it should belong to TopicBusiness.class? I am quite puzzled by this.

EDIT:

Some more info as requested. TopicBusiness.class and PostBusiness.class are classes holding all the business logic of the application concerning topics and posts respectively - that is fetching the data from database and/or performing some operations on them.

TopicEntity is data (in this case representing single topic) fetched from database. getAllPostFromTopic(TopicEntity topic) gets all posts from database that belong to particular topic, while getNumberOfPostsInTopic(TopicEntity topic) performs database query and returns the number of posts that topic passed as parameter consists of.

答:
These isn't an answer, but is too long for a comment.

At first sight, it looks like you've run into the multiple dispatch problem.

In non-object-oriented languages, you have functions and procedures, each of which can have multiple parameters. There is no "this object" because there are no objects.

In OOP as implemented in C++, Java etc, classes have methods. Excluding static methods, when you call a method, you specify the object that you're calling it for. The object is really a parameter, like the others - writing it before the method name and dot instead of within parentheses doesn't change that. However, it's specified in a special way because it has special properties...

It's often implicit within the method. You don't include a this parameter in the method signature, and you don't have to use this (or any other name) to reference the object.

This one special parameter is used for "dispatch" - to decide which implementation of the method to use in late-binding calls.

This approach is called "single dispatch" because there is one special parameter which is used for the dispatch decision. There is also something called "multiple dispatch" where the dispatch decision can be based on any/all parameters.

EDIT - sorry, I wrote "multiple inheritance" below earlier, that's a different thing.

With multiple dispatch, you don't need to nominate one particular parameter to be special - at least not for dispatch. All parameters are "special" in that way, therefore none of them are special. You might still want a special "this object" for reasons of abstraction, but you don't need it just to support calling.

Multiple dispatch is rare to non-existent in OOP, but it exists in a few languages - I believe it's in Common Lisp, though I don't know for sure. The way I know about it is more for domain-specific languages such as treecc - actually I've written a tool based on treecc, but designed for working with C++.

Without multiple dispatch as a language feature, you have two issues...

Which parameter to make into the special "this object" parameter for a method.

How to implement multiple dispatch as a design pattern where needed.

The first issue is all about abstractions, and doesn't always have a good answer. In C++, it's commonly pointed out that sometimes using non-member functions can even improve encapsulation. Maybe your method shouldn't be a method at all?

I'd add that just because you're defining a function separate from one class doesn't mean you can't put it in another class - you could define a third class with "tools" that manipulate objects of the other two class types. There's a common claim in OOP that "the shape draws itself", due to the teaching example, but it's wrong to infer that a class must always encapsulate the data it works with. It encapsulates the implementation of its own abstraction, but the nail is a separate object - not a part of the hammer implementation. Some kinds of objects are designed to work together - to interact via a shared interface - and are therefore somewhat coupled. That's not a goal to seek, but it's an unavoidable fact of life, and you get better encapsulation by having hammer and nail as separate classes than by having one combined hammer-and-nails class.

The other issue is how to handle a multiple-dispatch decision. There are lots of options because it is, after all, just a run-time decision you're making - the compiler didn't handle it for you so you have to code it yourself. However, for maintainability, a particularly good solution is "redispatch" - using a sequence of single-dispatch decisions to implement multiple dispatch. Each method calls another method (with a different parameter taken as special) until the dispatch is fully resolved. I don't have a good link for this. I got the term from the Ada95 reference manual, but Ada wrongly claims to support multiple dispatch just because redispatch is possible (a design pattern is not a built-in language feature).

This is a heavy-weight pattern - there's a fair amount of code to write. But it normally gives good error messages. Not perfect - it can fail to see a problem if you have non-abstract base classes - but it's still a lot better than e.g. a switch.

One place that redispatch is used is in the visitor pattern. Some people say that the visitor pattern is only needed because OOP languages lack multiple dispatch. I'm not entirely convinced. Certainly, a big part of the visitor is doing redispatch to solve the double-dispatch (two special parameters) case of multiple dispatch, but there's also an abstraction with clear roles - visitor and visitee - and other details that are separate from multiple dispatch.


问:
How to audit an Android application (not rooted) without having access to its source?
How can I check if an Android application running on a not rooted device is "secure" without knowing its source?

I would look for:

Plain text in Web-Requests (wireshark and emulator)

SQL-injection (in EditTexts...)

Doing stuff, that isn't always expected (i.e. fast clicking to check for race conditions)

Question: What else could be interesting for auditing Android apps?

答:
One thing you might want to do is use a packet capture application to find out what the app is doing with the network. Is everything encrypted? What could a man-in-the-middle do?

http://mobile.tutsplus.com/tutorials/android/analyzing-android-network-traffic/


问:
moore's law and quadratic algorithm
I was going thru a video (from coursera - by sedgewick) in which he argues that you cannot sustain Moore's law using a quadratic algorithm.He elaborates like this

In year 197* you build a computer of power X ,and need to count N objects.This takes M days

According to Moore's law,you have a computer of power 2X after 1.5 years.But now you have 2N objects to count.

If you use a quadratic algorithm,

In year 197*+1.5 ,it takes (4M)/2 = 2M days

4M because the algorithm is quadratic,and division by 2 because of doubling computer power.

I find this hard to understand.I tried to work thru this as below

```<code>To count N objects using comp=X , it takes M days.
-> N/X = M

After 1.5 yrs ,you need to count 2N objects using comp=2X
-> 2N/(2X) -> N/X -> M days
</code>```

where do I go wrong? can someone please help me understand?

答:
When Sedgwick talks of a "quadratic" algorithm, he means one where the effort is not proportional to the size of the input. For instance, if you have ten letters in your alphabet, there are 100 possible two-letter words, but if you have twenty letters, it's 400 possible words, not just 200. In other words, the algorithm does something more than just "do something with every object" - usually, "do something to every combination of k objects". Therefore, if you assume that input size grows proportionally with time, and your algorithm is super-linear (e.g. quadratic) then a simple growth of computing power in proportion with time is not sufficient to keep up with the problem growth.

I should note that this is an oversimplification of both sides of the problem. There is no general rule that input size of real-world problems grows in proportion with time - very often it will grow much slower or much faster (although usually not for very long). And Moore's law is not a law but just an empirical observation, and it wasn't about CPU speeds but about the number of transistor components per chip, which has little to do with them. In fact, for quite some time the mainstream CPUs have not increased their clock speeds the way they did in the 90s, although the transistor count keeps rising. So all this is a very high-level abstract view of the question. In practice, you almost always need to look more closely at your problem to decide whether it will remain feasible or not.

Title: moore's law and quadratic algorithm


答:
Let T(N) the time (in days) needed to execute an algorithm for N objects on a computer of "power 1", then the number of days needed is first

```<code>T(N)/X
</code>```

and second

```<code>T(2N)/2X
</code>```

Now set T(N)=N in your first case and T(2N)=4N in your second case, and I think you can do the remaining math by yourself.

Honestly, "counting of objects" is not a really good example, because it gives the notion of a running time of O(N). Perhaps you had seen your error more easily if you had replaced "counting" by "sorting".

Title: moore's law and quadratic algorithm

Body:
I was going thru a video (from coursera - by sedgewick) in which he argues that you cannot sustain Moore's law using a quadratic algorithm.He elaborates like this

In year 197* you build a computer of power X ,and need to count N objects.This takes M days

According to Moore's law,you have a computer of power 2X after 1.5 years.But now you have 2N objects to count.

If you use a quadratic algorithm,

In year 197*+1.5 ,it takes (4M)/2 = 2M days

4M because the algorithm is quadratic,and division by 2 because of doubling computer power.

I find this hard to understand.I tried to work thru this as below

```<code>To count N objects using comp=X , it takes M days.
-> N/X = M

After 1.5 yrs ,you need to count 2N objects using comp=2X
-> 2N/(2X) -> N/X -> M days
</code>```

where do I go wrong? can someone please help me understand?

Body:
Let T(N) the time (in days) needed to execute an algorithm for N objects on a computer of "power 1", then the number of days needed is first

T(N)/X

and second

T(2N)/2X

Now set T(N)=N in your first case and T(2N)=4N in your second case, and I think you can do the remaining math by yourself.

Honestly, "counting of objects" is not a really good example, because it gives the notion of a running time of O(N). Perhaps you had seen your error more easily if you had replaced "counting" by "sorting".


问:
Perfomance of 8 bit operations on 64 bit architechture
I am usually a Python / Database programmer, and I am considering using C for a problem.

I have a set of sequences, 8 characters long with 4 possible characters. My problem involves combining sets of these sequences and filtering which sets match a criteria. The combinations of 5 run into billions of rows and takes around an hour to run.

So I can represent each sequence as 2 bytes.

If I am working on a 64 bit architechture will I gain any advantage by keeping these data structures as 2 bytes when I generate the combinations, or will I be as well storing them as 8 bytes / double ? (64 bit = 8 x 8)

If I am on a 64 bit architecture, all registers will be 64 bit, so in terms of operations that shouldn´t be any faster (please correct me if I am wrong).

Will I gain anything from the smaller storage requirements - can I fit more combinations in memory, or will they all take up 64 bits anyway?

And finally, am I likley to gain anything coding in C. I have a first version, which stores the sequence as a small int in a MySQL database. It then self joins the tabe to itself a number of times in order to generate all the possible combinations. The performance is acceptable, depending on how many combinations are generated. I assume the database must involve some overhead.

答:
If I am working on a 64 bit architechture will I gain any advantage by keeping these data structures as 2 bytes when I generate the combinations, or will I be as well storing them as 8 bytes / double ? (64 bit = 8 x 8)

Squeezing your data into 2 bytes instead of 8 will obviously reduce the amount of memory needed for large arrays of these sequences to ~1/4. This fact is mostly independent of your processor architecure, regardless of beeing 64, 32, 16 or just 8 bit.

If this will result in any measurable performance improvement, depends if the packed representation of the amount of data you are going to process "in a whole" will fit completely into faster memory (for example, main memory), while the unpacked representation does not (for example, you will need external hard disk space for it).

Honestly, since you did not provide any details about how your "filtering" does look like, it is unclear if you need to unpack the data first before you can process it further, which may use up additional computing time. Or the difference in your case may show up beeing so small that the packing is fully unnecessary. So, what you have to do here is: try and measure, measure, measure!


答:
You have to remember, you're dealing with real devices.  In a perfect world, a control signal will have an effect, no matter how small.  In the real world, control signals smaller than some threshold value don't do anything at all.  (Imagine a chihuahua trying to pull a Mack truck.)

In a proportional control system, the control signal is the error multiplied by the control gain.  To prevent overshoot, instability, and other Bad Things, you make the gain small.

As your plant (controlled system) gets closer and closer to the desired value, the error gets smaller and smaller.  When you multiply a smaller and smaller error by a small gain, eventually the product gets too small to have any effect, and is truncated to zero.

That's your steady state error, the region around the desired output where the product of the error and the gain is too small to register.

After whatsisname's downvote, I thought back.  He's right.  I was confusing "dead band" with "steady state error".

If you have a constant perturbing force (for lack of a better term), and you are using a PI controller, there will be some point at which the control signal (product of error and gain) exactly balances the perturbing force.  At this point, the plant (system being controlled) experiences zero net force: the perturbing force and the correction cancel each other, and the plant just sits there, with a constant error, the error generating the signal to cancel out the perturbing force.

The first-level fix is to go to a PI controller, one that not only produces a correction based on the error, but also based in the integral over time of the error.  The integral term is what "notices" the steady state error and moves to correct it.

The catch is that a PI controller can have overshoot problems.  There are no silver bullets.

Title: Why does a proportional controller have a steady state error?

Body:
I've read about feedback loops, how much this steady state error is for a given gain and what to do to remove this steady state error (add integral and/or derivative gains to the controller), but I don't understand at all why this steady state error occurs in the first place.

If I understand how a proportional control works correctly, the output is equal to the current output plus the error, multiplied by the proportional gain (Kp).  However, wouldn't the error slowly diminish over time as it is added (reaching 0 at infinite time), not have a steady state error?  From my confusion, it seems I'm completely misunderstanding how it works - a proper explanation of how this steady state error eventuates would be fantastic.


答:
There can't be. GPL is a Free Software license; a "free for non-commercial use" license is not, because it restricts commercial use, and such a restriction is a violation of the Four Freedoms. (In case you're wondering, here's a definition of Free Software).

GPL (all varieties, really) were designed specifically to ensure that the software is and remains Free; the viral nature of it is a direct consequence of making sure that it is possible to build upon GPL-licensed works without impacting its free-ness. Unfortunately, this also means that if you want to (or have to) release under GPL, you cannot restrict the license to non-commercial use, and you cannot forbid the use of the software for, say, military, espionage, executing death sentences, running nuclear facilities, clubbing seals, hunting whales, or destroying rainforests. By contrast, the MIT license allows reuse as part of a non-free work; while the original work is free, the derived work may not be, and such a derived work can add such restrictions to its license, as long as it adheres to the original work's requirements (typically, attribution).

Title: Is "Free for non-commercial use" license compatible with GNU GPLv3 license?

Body:
I want to ask whether any materials that has "Free for non-commercial use" license can be used in a GNU GPLv3 licensed software.

In my opinion, it is "free for non-commericial use", and GNU GPLv3 is also non-commericial, so it can be used in the software,  is it?

I'm asking this question because there are no explicit or clear declaration about "FREE FOR NON-COMMERCIAL USE" license out there....


问:
design in agile process
Recently I had an interview with dev team in a company. The team uses agile + TDD.
The code exercise implements a video rental store which generates statement to calc total rental fee for each type of video (new release, children, etc) for a customer. The existing code use object like:

Statement to generate statement and calc fee where big switch statement sits to use enum to determine how to calc rental fee

customer holds a list of rentals

movie base class and derived class for each type of movie (NEW, CHILDREN, ACTION, etc)

The code originally doesn't compile as the owner was assumed to be hit by a bus.  So here is what I did:

outlined the improvement over object model to have better responsibility for each class.

use strategy pattern to replace switch statement and weave them in config

But the team says it's waste of time because there is no requirement for it and UAT test suite works and is the only guideline goes into architecture decision. The underlying story is just to get pricing feature out and not saying anything about how to do it. So the discussion is focused on why should time be spent on refactor the switch statement.

In my understanding, agile methodology doesn't mean zero design upfront and such code smell should be avoided at the beginning. Also any unit/UAT test suite won't detect such code smell, otherwise sonar, findbugs won't exist.

Here I want to ask:

is there such a thing called agile design in the agile methodology? Just like agile documentation.

how to define agile design upfront? how to know enough is enough? In my understanding, ballpark architecture and data contract among components should be defined before/when starting project, not the details. Am I right?

anyone can explain what the team is really looking for in this kind of setup? is it design aspect or agile aspect?

how to implement minimum viable product concept in the agile process in the real world project? Is it must that you feel embarrassed to be MVP?

答:
There are many approaches in the real world about this. You are asking a very broad question so my answer will be a bit general.

Of course there is a concept of design in agile. There is normally no concept of up-front design, but systems are designed as you go and, of course, legacy systems have a design.

Strictly speaking, you should do the bare minimum design that you can afford. It's perfectly possible that a web site starts with a static html page hosted somewhere. In fact, many sites do. Of course, sometimes it's necessary to do a bit of upfront work to have a bare bones design implemented, but we should be talking about days of work at most.

That is a question for your team, but I don't think it's correct to make it an up-front question. Teams don't need anything besides networked computers. All that a team needs is determined by what the team needs to achieve.

MVP is the minimum set of stuff you need to ship in order to have any value. It is typically a "sign up for beta page". After that, the minimum amount of features that will allow your product to work. I would like to stress "minimum" here: take the "no-so-minimum" set of features you are likely to come up with initially, and start stripping away all you can while keeping the core working. The whole point is enabling a feedback cycle with early adopters. An MVP should be an alpha version, not a beta.

Title: design in agile process


问:
How to handle status columns in designing tables
How to handle multiple statuses for a table entry, for example an item table may have an active, inactive, fast moving, and/or batch statuses. And I wanted to handle them in single column with VARCHAR type. Also I might set each of those attributes as a boolean with different columns. But I am not sure what consequences this might lead to. So if you have experienced such situations which one would be the best way to handle it?</p>

答:
If you have a status that can be multiple different states, but never more than one at a time, then have one column. Otherwise, separate columns is a must.

You never want to store multiple things in a single column. Querying against it would be nightmare. You may only be thinking about loading the data in one particular way now, but in 3 years time when somebody asks you to run a report in a specific way and you realize there is no real way to do this because there are 10 things all stored in one concatenated column, then you have a heavy redesign on your hands.


答:
The important thing with design in an agile process is that it has to be done within the process. One of the first things to produce is a design, otherwise you've got no idea what you're doing. But that design shouldn't take long to produce, and should thereafter be an artefact that is subject to revision through the agile process just as the code is. Don't assume you're going to get it right first off. Don't be afraid to add to it if necessary and to refactor it if it is too complicated.

Try to keep the design to something that will fit on one page (or one slide) so that people can understand where the piece they are working on fits in the overall picture. Sure, that won't cover all cases, but designing up front to cover everything is not an agile practice; that follows naturally from the founding principle that the requirements are not all known up front (and the obvious point that true design follows from requirements).

To know when you've got too much? Frankly, you probably already have too much. The high-level design — the truly useful bit — shouldn't take too long, and the low-level design is just whatever drops out of the backlog. (Hint: if you're thinking about algorithms in the design, you've already almost certainly got too much detail. Well, unless you're doing something so funky that it is impossible without that specific algorithm…)

What's important for the team is that they get something going and check back with the product owner for the next iteration towards understanding the requirements. As with all agile development. (Re the MVP, remember that it might take a few of iterations to get there, and don't be afraid to not make it look good in the first few revs; customers all too often think that having the CSS applied means that the whole service is finished. You know and I know that that's just not true.)

Title: design in agile process

Body:
Recently I had an interview with dev team in a company. The team uses agile + TDD.
The code exercise implements a video rental store which generates statement to calc total rental fee for each type of video (new release, children, etc) for a customer. The existing code use object like:

Statement to generate statement and calc fee where big switch statement sits to use enum to determine how to calc rental fee

customer holds a list of rentals

movie base class and derived class for each type of movie (NEW, CHILDREN, ACTION, etc)

The code originally doesn't compile as the owner was assumed to be hit by a bus.  So here is what I did:

outlined the improvement over object model to have better responsibility for each class.

use strategy pattern to replace switch statement and weave them in config

But the team says it's waste of time because there is no requirement for it and UAT test suite works and is the only guideline goes into architecture decision. The underlying story is just to get pricing feature out and not saying anything about how to do it. So the discussion is focused on why should time be spent on refactor the switch statement.

In my understanding, agile methodology doesn't mean zero design upfront and such code smell should be avoided at the beginning. Also any unit/UAT test suite won't detect such code smell, otherwise sonar, findbugs won't exist.

Here I want to ask:

is there such a thing called agile design in the agile methodology? Just like agile documentation.

how to define agile design upfront? how to know enough is enough? In my understanding, ballpark architecture and data contract among components should be defined before/when starting project, not the details. Am I right?

anyone can explain what the team is really looking for in this kind of setup? is it design aspect or agile aspect?

how to implement minimum viable product concept in the agile process in the real world project? Is it must that you feel embarrassed to be MVP?


问:
How important is to avoid name collisions between libraries belonging to different domains?
I have written a small open source Java library for facilitating conversions between different types of objects (in the style of Google's gson, but quite more general).

It seems to me that a nice natural name for my library is JConverter, after browsing in the web to see if another library with the same name already exists, I found a library with the same name for Joomla.

My concrete question is:

How important is to avoid naming collisions when creating an open source library if an existing library with the chosen name already exists in a complete different domain ? (in my concrete case, these are libraries even implemented for different languages).

答:
How important is to avoid naming collisions when creating an open source library if an existing library with the chosen name already exists in a complete different domain ?

It's pretty important, as otherwise you get lots of confusion. That particularly comes if you're lucky enough to grow the community of users to the point where there's some overlap between groups. For example, did you know there are several open source systems called Fedora? One's a major Linux distribution, and the other is a digital asset management system (and they used the name first, which led to an awkward trademark dispute a number of years ago). When I encountered a project using both earlier this year, I spent a significant proportion of time trying to grasp just WTF was going on!

So avoid such problems. Pick a more distinctive name. (I don't think that JConverter is very good BTW; it's not saying what it converts. Is it converting images? Or sound formats? Or maybe it's converting weights and measures between metric and imperial.)

Technically, if you're using a system like Maven then you won't have that much trouble as you'll have different groupIds and different package names. If you don't do at least that much separation, you're just asking for trouble!


答:
Considering one library is for Java and the other for Php, and that there are no trademarks involved. I wouldn't break a sweat.

That said, you are going to compete to get the best URLs on GitHub, etc. If this is not a problem, go ahead.

On the other hand, maybe you can figure out a unique name and be done with it? :-)

Title: How important is to avoid name collisions between libraries belonging to different domains?

Body:
I have written a small open source Java library for facilitating conversions between different types of objects (in the style of Google's gson, but quite more general).

It seems to me that a nice natural name for my library is JConverter, after browsing in the web to see if another library with the same name already exists, I found a library with the same name for Joomla.

My concrete question is:

How important is to avoid naming collisions when creating an open source library if an existing library with the chosen name already exists in a complete different domain ? (in my concrete case, these are libraries even implemented for different languages).


答:
For a relational database I would suggest you store these in separate status and item_statuses tables that have their own primary keys.

The 'join' table between item and status, e.g. item_statuses has the keys from each of the two tables, e.g. item_id and status_id.  It also has its own primary key ('id') as my experience says always have a primary key that has no business meaning and both of the other keys have business meaning so the composite of them is not a good primary key.

Storing literal values as varchar can easily leads to dupes, typos and other issues.

Title: How to handle status columns in designing tables

Body: How to handle multiple statuses for a table entry, for example an item table may have an active, inactive, fast moving, and/or batch statuses. And I wanted to handle them in single column with VARCHAR type. Also I might set each of those attributes as a boolean with different columns. But I am not sure what consequences this might lead to. So if you have experienced such situations which one would be the best way to handle it?</p>


答:
Short answer: No.  The GPL requires you to re-use the same license as the cost of making a derivative work.  If you also attach a "no commerical use" rider, you are not re-using the same license.

Longer answer: Yes, but. If you have the right to dictate the terms of license for your entire project -- i.e., you could license it 100% closed source -- you could release your code jointly under both licenses.  The "no commercial source" library would maintain with itself and attach to your program, while the "copyleft" of the GPL would attach to all of your original code and anyone else's derivations thereof.

Be aware that this is NOT what Stallman and the FSF intended the GPL to be used for.  And the license for your "no-commerical use" library might not include "re-license your own project" in their description of "use."  While I am confident enough to say "it's possible", with the condition that you are not compelled to use the GPL, I would be remiss if I did not tell you in no uncertain terms that you should get a professional opinion.

The interplay of licenses is a complicated legal issue.  ASK A LAWYER if you are using anyone else's GPL'd code!!!


问:
What's the recommended control naming convention for XAML markup?
When working with WPF or Silverlight, how should one use control naming conventions? Do you name the controls in XAML markup? I have seen samples of projects at codeplex with control names such  as "selectButton" or "btnSelect". What would you recommend? </p>

答: I usually dont name my controls in XAML, as it would be, most of the time, unused considering everything is set or controlled through bindings. Source : Pete Brown</p>


答:
The other answers here are good. I think it's worth mentioning the GRASP pattern called Information Expert. The GRASP patterns were designed for teaching good OO practices in a university. In brief, the Information Expert pattern says that the class that has the most information about an activity should own that activity.

In this case, I would think that TopicBusiness knows more about topics than PostBusiness, so it should contain the behavior.

Title: How do I decide to which class a method should belong

Body:
I have TopicBusiness.class and PostBusiness.class. I have no problem with deciding into which class methods such as addPostToDatabase() or getAllPostsFromDatabase() should go. But what about getAllPostsFromTopic(TopicEntity topic) or getNumberOfPostsInTopic(TopicEntity topic)?

Should the parameter be the deciding factor? So when the method takes TopicEntity as parameter it should belong to TopicBusiness.class? I am quite puzzled by this.

EDIT:

Some more info as requested. TopicBusiness.class and PostBusiness.class are classes holding all the business logic of the application concerning topics and posts respectively - that is fetching the data from database and/or performing some operations on them.

TopicEntity is data (in this case representing single topic) fetched from database. getAllPostFromTopic(TopicEntity topic) gets all posts from database that belong to particular topic, while getNumberOfPostsInTopic(TopicEntity topic) performs database query and returns the number of posts that topic passed as parameter consists of.


问:
Why "Fork me on GitHub"?
I understand how GitHub works, but one thing I've been confused about is, why almost every OSS project lately has a "Fork me on GitHub" link on their homepage. For example,

http://jqtjs.com/, http://www.daviddurman.com/flexi-color-picker/, and others.

Why is this so common? Is it that they want/need code validation, checking for security/performance improvements that they may not know how to do?

Is it meant to show that this is a collaborative project - you're welcome to add improvements?

Do they work for GitHub, or want to promote their service? Oddly enough, I don't think I've seen a "Fork project on Bitbucket" logo recently.

My first reaction to that logo was that the project probably needs to be modified (forked) in order to integrate it with anything useful - or that they are encouraging fragmented codebase, encouraging everyone to make their own fork of the project. But I don't think that is the intent.

答:
Is it meant to show that this is a collaborative project - you're welcome to add improvements?

Yes: you don't have the right to push a commit directly at their repo.

But you do have the possibility to fork their repo, which makes it your repo, and push commit from there, preparing pull requests.

Title: Why "Fork me on GitHub"?


答: It means they're on github, where forking is cheap, and they want to encourage contributions to improve their software and community.</p>

Title: Why "Fork me on GitHub"?

Body:
I understand how GitHub works, but one thing I've been confused about is, why almost every OSS project lately has a "Fork me on GitHub" link on their homepage. For example,

http://jqtjs.com/, http://www.daviddurman.com/flexi-color-picker/, and others.

Why is this so common? Is it that they want/need code validation, checking for security/performance improvements that they may not know how to do?

Is it meant to show that this is a collaborative project - you're welcome to add improvements?

Do they work for GitHub, or want to promote their service? Oddly enough, I don't think I've seen a "Fork project on Bitbucket" logo recently.

My first reaction to that logo was that the project probably needs to be modified (forked) in order to integrate it with anything useful - or that they are encouraging fragmented codebase, encouraging everyone to make their own fork of the project. But I don't think that is the intent.


答:
Imagine you use your favorite text editor, and after some time you find that you would really love some feature to be implemented (like non-blocking Save file option).

After thinking that for the eleventh time you decide to write one by yourself. After you find the github page of this project you have two options:

Download the source code, modify it and keep it for yourself.

Fork the project on a github and work on your fork.

If you chose the second option, after making your feature well-written and well-tested, you could prepare pull request and then the entire project would benefit from you.

However, if you chose the first path, it is very likely that you will just forget about your modification and nobody except you will benefit from it (yes, you may share the code manually, but some other coder could easily forget that. Using github is forcing you to get more socialized with the other's work).

Saying 'fork me on a github' project's owner just want to make sure that you chose the Fork on github instead downloading the code and publishing it into your home directory.

Title: Why "Fork me on GitHub"?


答:
It's only there to show that this is an open source project and you fork it if you want to, whatever the reason.
Also, check out this blog post on GitHub: https://github.com/blog/273-github-ribbons

Update: Personally, I add these GitHub ribbons so people can find me on GitHub and star my projects ;)

Title: Why "Fork me on GitHub"?


答:
The "Fork me on Github" badge is meant to show that it the project you are granted the right to contribute to the project or use it as a starting point for your own project.

It kinda shows that "it's a collaborative project and that you're welcome to add improvements."

It allows you to play around with the code or make a spin-off of the same project without affecting the original source.

https://help.github.com/articles/fork-a-repo

The same principle applies to all other git hosts.

The main points (among many other) of giving the right to fork a project is to

foster collaboration - by allowing people to work together in improving the project.

add to knowledge - by allowing people to study your code.

Some of the projects you may have encounters may be by Github staff for their own private needs. They do not want to promote github. You can find projects by github here : https://github.com/github

As to why you're not seeing badges from other hosts is because Github is the most popular git hosting and collaboration platform.

Title: Why "Fork me on GitHub"?


答:
Using a single column sounds appropriate, as long as the different status values are legitimately different states of the same thing.  This is basically what razethestray has said as well.

If you create a separate status lookup table like Michael Durrant suggests, then you could optionally add your various Boolean columns to that table.

Adding additional flag columns to a lookup table is not a common technique, in my experience, but I've tried it a bit and like how it lets me keep my application code from magically knowing that status "In Progress" means "cannot add items", for example.  Instead, I could have an AllowsAddingItems column on my status table, and the value in that column for the "In Progress" status would be false.  This way, my application code doesn't have to be as aware of what all of the different possible statuses are; it just checks that AllowsAddingItems attribute associated with the current status.


答:
I'm going to be heretical here and say: homonymy isn't a big problem.

Virtually every word you use in everyday language has more than one meaning. When you bother actually checking things in a dictionary, you'll find that often you know and understand several different meanings of words in a sentence. People are amazingly good at disambiguating such words without even being aware of it. As long as you don't pollute the Java class namespace with a domain you don't own, I see no reason to avoid a name because someone, somewhere has already used it. Virtually every nice name is already in use by that criterion. I would avoid a name only when it's in use for something that fills the same niche, so that contextual disambiguation wouldn't work. (This is largely how trademark law works, in fact.)

The greater problem is, as Donal said, that "JConverter" isn't a very descriptive name. You should either express something about the domain you serve with your library, or find a name that sounds interesting - maybe a proper name.


问:
How to write comments to explain the "why" behind the callback function when the function and parameter names are insufficient for that?
How should I approach writing comments for callback functions?  I want to explain the "why" behind the function when the function and parameter names are insufficient to explain what's going on.

I have always wonder why comments like this can be so ordinary in documents of libraries in dynamic languages:

```<code>/**
 * cb: callback    // where's the arguments & effects?
 */
 func foo( cb )
</code>```

Maybe the common attitude is "you can look into source code on your own after all" which pushes people into leaving minimalist comments like this.

But it seems like there should be a better way to comment callback functions.

I've tried to comment callbacks in Haskell way:

```<code>/**
 * cb: Int -> Char
 */
func foo(cb)
</code>```

And to be fair, it's usually neat enough.

But it gets into trouble when I need to pass some complex structure.  The problem being partly due to the lack of type system:

```<code>/**
 * cb: Int -> { err: String -> (), success: () -> Char }  // too long...
 */
func foo(cb)
</code>```

Or I have tried this too:

```<code>/**
 * cb: Int -> { err: String -> (),
 *              success: () -> Char }  // better ?
 */
func bar(cb)
</code>```

The problem is that you may put the structure in somewhere else, but you must give it a name to reference it.
But then when you name a structure you're about to use immediately looks so redundant:

```<code>// Somewhere else...
// ResultCallback: { err: String -> (), success: () -> Char }

/**
 * cb: Int -> ResultCallback    // better ??
 */
func foo(cb)
</code>```

And it bothers me if I follow the Java-doc like commenting style since it still seems incomplete.  The comments don't tell you anything that you couldn't immediately see from looking at the function.

```<code>/**
 * @param cb {Function}  yeah, it's a function, but you told me nothing about it...
 * @param err {Function} where should I put this callback's argument ??
 *                       Not to mention the err's own arguments...
 */
func foo(cb)
</code>```

These examples are JavaScript like with generic functions and parameter names, but I've encountered similar problems in other dynamic languages which allow complex callbacks.

答:
The fact that you're providing this example with generic function and parameter names, and then complaining about the lack of documentation, indicates a misunderstanding of the point of names.  The name of a thing is itself documentation, and should be descriptive enough to tell you not just the thing's type, but its role as well.

Let's have an example (in JavaScript, cause why not).

```<code>/**
 * cb1:             (this Row) ->
 * optional cb2:    (this Row) -> boolean
 */
RowSet.prototype.foo = function(cb1, cb2) {
    if (!cb2) cb2 = function() { return true; }
    for (var i = 0; i < this.length; ++i) {
        if (cb2.call(this[i]))
            cb1.call(this[i]);
    }
}
</code>```

Even with the doc comment, and even though this is a rather short function, i feel like i'm having to decipher it.  It doesn't say anything about semantics, or when it'd be appropriate to use, or any of that.

But if we use non-crappy names for things:

```<code>RowSet.prototype.withEachRow = function(rowCallback, rowPredicate) {
    if (!rowPredicate) rowPredicate = function() { return true; };
    for (var i = 0; i < this.length; ++i) {
        if (rowPredicate.call(this[i]))
            rowCallback.call(this[i]);
    }
}
</code>```

I find the second far more readable, without comments.  Once you have decent names, the comments that were all but mandatory on the first example become noise; everything they say can just as easily be learned from reading a couple of lines of code.  More reliably, too -- since comments don't affect the functionality of the program, they can say basically anything.  It's harder to tell whether someone updated the comments when they changed the function.  One would have to read through the function to know that.  But wait -- isn't that what the comments were supposed to help us avoid?

What's more, good names become much a more powerful tool the more consistently you use them.  For example, when you use the word "predicate" to always-and-only refer to a function that can be called on some item and returns a boolean determing whether that item matches some condition, suddenly it's no longer just a name -- it's a concept, almost a type in itself.

Body:
The fact that you're providing this example with generic function and parameter names, and then complaining about the lack of documentation, indicates a misunderstanding of the point of names.  The name of a thing is itself documentation, and should be descriptive enough to tell you not just the thing's type, but its role as well.

Let's have an example (in JavaScript, cause why not).

/**
 * cb1:             (this Row) ->
 * optional cb2:    (this Row) -> boolean
 */
RowSet.prototype.foo = function(cb1, cb2) {
    if (!cb2) cb2 = function() { return true; }
    for (var i = 0; i < this.length; ++i) {
        if (cb2.call(this[i]))
            cb1.call(this[i]);
    }
}

Even with the doc comment, and even though this is a rather short function, i feel like i'm having to decipher it.  It doesn't say anything about semantics, or when it'd be appropriate to use, or any of that.

But if we use non-crappy names for things:

RowSet.prototype.withEachRow = function(rowCallback, rowPredicate) {
    if (!rowPredicate) rowPredicate = function() { return true; };
    for (var i = 0; i < this.length; ++i) {
        if (rowPredicate.call(this[i]))
            rowCallback.call(this[i]);
    }
}

I find the second far more readable, without comments.  Once you have decent names, the comments that were all but mandatory on the first example become noise; everything they say can just as easily be learned from reading a couple of lines of code.  More reliably, too -- since comments don't affect the functionality of the program, they can say basically anything.  It's harder to tell whether someone updated the comments when they changed the function.  One would have to read through the function to know that.  But wait -- isn't that what the comments were supposed to help us avoid?

What's more, good names become much a more powerful tool the more consistently you use them.  For example, when you use the word "predicate" to always-and-only refer to a function that can be called on some item and returns a boolean determing whether that item matches some condition, suddenly it's no longer just a name -- it's a concept, almost a type in itself.


问:
Why is C++ predominant in programming contests and competitions?
I understand that C++ is a very fast language, but ain't C just as fast, or faster in some cases?

Then you might say that C++ has OOP, but the amount of OOP you need for most programming puzzles is not that big, and in my opinion C would be able handle that.

Here's why I am asking this: I am very interested in programming contests and competitions, and I am used to coding in C on those. However, I noticed that the vast majority of people use C++ (e.g., 17 out of 25 finalists on Google Code Jam 2011 used it, while no one used C), so I am wondering if I am at a disadvantage going with C.

Apart from the Object Orientation, what makes C++ a more suitable language for programming competitions? What are the features of the language I should learn and use to perform better on the competitions?

For background, I consider myself pretty proficient in C, but I am just starting to learn C++.

答:
Speaking as a previous Code Jam finalist, it's mostly about the libraries rather than the language features. Competition solutions seldom use any OOP design principles, but you're likely to see a tour of most of the standard library containers and algorithms - string, vector, list, stack, queue, deque, priority_queue, set, map, complex, pair, bitset, lower_bound, reverse, sort, find, count, nth_element, min, max, min_element, max_element, unique, next_permutation, ... skilled contestants will be familiar with all of them and gain a lot of time by not having to implement and debug them in C.

Code Jam allows contestants to bring in their own code and use third-party libraries, so in theory a contestant could have this all pre-implemented in C. However, not all contests allow this, and templates and operator overloading make this much more readable than in C.


答:
Here are the 4 possible solutions I can think of

encode everything in one column, using a number type as bitset

pro:

smallest amount of memory needed

easily extendable to the point where you reach n flags, where 2^n is the maximum value of the number type choosen

con:

queries for all items with a specific status are hard, since most sql dialects don't support bit operations

no indexing for a single flag, a query for all items with s specific state will always result in  a full table scan

encode everything in one column, using a string of "0" and "1"

pro:

still very compact in memory

easily extendable, like the first approach, but no inherent limit n

con:

queries are not so hard as above, but will need string operations

still no indexing

use a different column for each status

pro:

indexed queries are easy

query results are easily readable  / don't need specific decoding

con:

only extendable by changing the schema

needs more storage

use a link table (Michael Durrant's solution)

pro:

can be extended at run time, without any schema change

indexed queries are possible

con:

queries are more complicated / need a join

inserts and updates are more complicated, instead of one record you now have to add two or more records for storing the same information

So all of these solutions have different trade-offs, and you should make your decision based on the use cases / queries you expect, and the amount of extensibilty you need.


问:
How to deal with data on the model specific to the technology being used?
There are some cases where some of the data on a class of the domain model of an application seems to be dependent on the technology being used. One example of this is the following: suppose we are building one application in .NET such that there's the need of an Employee class. Suppose further that we are going to implement relational database, then the Employee has a primary key right? So that the classe would be something like

```<code>public class Employee
{
     public int EmployeeID { get; set; }
     public string Name { get; set; }
     ...
}
</code>```

Now, that EmployeeID is dependent on the technology right? That's something that has to do with the way we've choose to persist our data. Should we write down a class independent of such things? If we do it this way, how should we work? I think I would need to map all the time between domain model and persistence specific types, but I'm not sure.

答:
Adding ID fields as primary keys (or also as foreign keys) is indeed a technological choice, since you would not need those for non-persistent data. In all OO languages I know of you can express relationships and references between objects without any artificial IDs, just by the way your programming languages offers references or pointers.

However, such an ID field will be helpful for lots of of different persistence mechanisms, so it is not dependent on a specific technology, only on the fact that you want to persist that data. In fact, using an ID field for relationships will be compatible with almost any persistence mechanism I know of. I remember that there had been some OO database systems in the past which tried to avoid the need of introducing additional ID fields, but using such a system and not introducing an ID field does make your program much more technology dependent than it gets with additional IDs.


答:
Aside from the foster collaboration side of the issue, from a business perspective it will enhance and strengthen GitHub's traffic, user base and market position.  So there is a little bit of a business strategy associated with it too.

Personally I don't mind this because GitHub provides a valuable service to the open source community.

Title: Why "Fork me on GitHub"?


问:
Requring static class setter to be called before constructor, bad design?
I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList.

Since every class instance will share the same List Object, I thought it would be good to make myList static and use a static function to set myList before the constructor is called.

I was wondering if this was bad, because this requires the setter to be called before the constructor? If the person doesn't, the program will crash. Alternative way would be passing myList every time.

答:
In C# you can create the list instance in the static constructor implicitly:

```<code>static List<int> myList = new List<int>();

public Foo()
{
   myList.Add(42); // note: not thread safe!!!
}
</code>```

or explicitly:

```<code>static List<int> myList;

static Foo()
{
   myList = new List<int>();
}

public Foo()
{
   myList.Add(42); // note: not thread safe!!!
}
</code>```

This is better than setting it independently for a number of reasons, but mostly:

static constructors only execute once (useful in multithreaded contexts)

static constructors are run before anything else, so you can assume that the field is always initialized

More in general, it is good practice to make a class "ready to use" in the constructor, and static members in the static constructor. This prevents having an instance with uninitialized fields.

Requiring a particular order of calls is possibly an anti-pattern known as Sequential Coupling and I would avoid doing that unless necessary.

Body:
In C# you can create the list instance in the static constructor implicitly:

static List<int> myList = new List<int>();

public Foo()
{
   myList.Add(42); // note: not thread safe!!!
}

or explicitly:

static List<int> myList;

static Foo()
{
   myList = new List<int>();
}

public Foo()
{
   myList.Add(42); // note: not thread safe!!!
}

This is better than setting it independently for a number of reasons, but mostly:

static constructors only execute once (useful in multithreaded contexts)

static constructors are run before anything else, so you can assume that the field is always initialized

More in general, it is good practice to make a class "ready to use" in the constructor, and static members in the static constructor. This prevents having an instance with uninitialized fields.

Requiring a particular order of calls is possibly an anti-pattern known as Sequential Coupling and I would avoid doing that unless necessary.


问:
Why Use Scala over Java
I am totally into Scala as a language ... and still I struggle with why any company should switch from Java to Scala. Is Scala just syntatic sugar on top of the JVM or are there fundamental improvements in Scala over Java that would improve real world applications? </p>

答:
I've been using Scala for about 3 months now and still can't find anything I wouldn't be able to do in Java. For me literally every literature on Scala seems to mention the same thing boilerplate. If what you are looking for is reducing boilerplate then Scala is for you but IMHO, for example the filter example given above could just as well be solved using apache collections

```<code><T> CollectionUtils.filter(Predicate<T>...)
</code>```

or use closures like so

```<code><T> CollectionUtils.forAllDo(..., Closure<T>)
</code>```

But of-course more verbose. I like the type inference though. As you learn Scala you'll realize that this is probably what is going on anyway under-the-hood. In my opinion, each language comes with +ve and -ve.

Title: Why Use Scala over Java

Body:
I've been using Scala for about 3 months now and still can't find anything I wouldn't be able to do in Java. For me literally every literature on Scala seems to mention the same thing boilerplate. If what you are looking for is reducing boilerplate then Scala is for you but IMHO, for example the filter example given above could just as well be solved using apache collections

<T> CollectionUtils.filter(Predicate<T>...)

or use closures like so

<T> CollectionUtils.forAllDo(..., Closure<T>)

But of-course more verbose. I like the type inference though. As you learn Scala you'll realize that this is probably what is going on anyway under-the-hood. In my opinion, each language comes with +ve and -ve.


问:
How to keep your third party libraries up to date?
Let's say that I have a project that depends on 10 libraries, and within my project's trunk I'm free to use any versions of those libraries. So I start with the most recent versions. Then,  each of those libraries gets an update once a month (on average). Now, keeping my trunk completely up to date would require updating a library reference every three days.

This is obviously too much. Even though usually version 1.2.3 is a drop-in replacement for version 1.2.2, you never know without testing. Unit tests aren't enough; if it's a DB / file engine, you have to ensure that it works properly with files that were created with older versions, and maybe vice versa. If it has something to do with GUI, you have to visually inspect everything. And so on.

How do you handle this? Some possible approaches:

If it ain't broke, don't fix it. Stay with your current version of the library as long as you don't notice anything wrong with it when used in your application, no matter how often the library vendor publishes updates. Small incremental changes are just waste.

Update frequently in order to keep change small. Since you'll have to update some day in any case, it's better to update often so that you notice any problems early when they're easy to fix, instead of jumping over several versions and letting potential problems to accumulate.

Something in between. Is there a sweet spot?

答: Partially, as described in svn vendor branches. The procedure described there is very useful, when you keep using open-source third-party libraries for a long time, and have made changes to adjust it for your needs.</p>


问:
Applications affected by memory performance
I'm writing a paper on the topic of applications affected more by memory performance than processor performance. I've got a lot written regarding the gap between the two, however I can't seem to find anything about the applications that might be affected more by memory performance than by processor speed.

I suppose these are applications that make a large amount of memory references, but I have no idea what kind of applications would make such large number of references to make it stand out? Perhaps databases?

Can you please give me any pointers on how to proceed, some links to papers? I'm really stuck.

答:
Applications that keep either many objects or deep object graphs in their cache may be candidates for your paper.

Speculation about Google's search engine architecture might make for a good paper. Here's why:

Google's search engine crawler may store its results in a massively distributed data store, but when you make a search engine query, your HTTP request does not ultimately query a database (it would be too slow).

Instead, your HTTP request ultimately queries some sort of distributed in-memory cache. There shouldn't be too much to calculate, and therefore not too much for the CPU to do. Querying the cache is the important part, and therefore, performance is heavily based on the way the cache is indexed and, indeed, memory performance.

Note:I'm sure that Google might provision state of the art machines with state of the art CPUs to crawl the web, but they are clustered so they don't have to be. The web crawler algorithm is certainly of a distributed nature, such that adding more machines to to the cluster would improve web crawler performance.

Furthermore, crawling the web could conceivably be a CPU-intensive task, but querying for search results should not be.


答:
Matrix transpose, matrix multiplication, convolution are all examples that come to mind. Many scientific computing problems are numerically quite simple (matrix multiplication is pretty trivial, it's just a few adds and multiplies), but computing a single entry of a matrix requires accessing an entire row of the first operand an entire column of the second operand. The result is that, no matter how the matrix is stored in memory, it is difficult to implement in such a way to keep the relevant parts in cache (or even in memory in some cases).

A considerable amount of research has gone into developing cache-efficient versions of these operations, and the fastest implementations usually require system-dependent cache optimizations. See BLAS and FFTW (http://www.fftw.org/).

Title: Applications affected by memory performance

Body:
I'm writing a paper on the topic of applications affected more by memory performance than processor performance. I've got a lot written regarding the gap between the two, however I can't seem to find anything about the applications that might be affected more by memory performance than by processor speed.

I suppose these are applications that make a large amount of memory references, but I have no idea what kind of applications would make such large number of references to make it stand out? Perhaps databases?

Can you please give me any pointers on how to proceed, some links to papers? I'm really stuck.


问:
Authenticating users for a website
I'm working on a website and I want to validate that an individual is an employee at one of a large number of companies (probably using their company's email address, which I don't know before hand). The idea being some users are the general public and others are from these companies. And I need some way to authenticate that the users claiming to be employees are being honest while still having a friendly enough UI.

I did an informal survey of people I know and the domains and emails will match in a majority of cases but they might not always match exactly so you might have a company with a website foo.com and an email billy@foobar.com (although foobar.com did redirect back to foo.com).

And while I can easily check that I'm not sure what other variations might be out there (maybe fooLA.com and email billy@foolosangeles.com, etc.)

答: I think you may opt for LDAP authentication, I did it for Subversion Control System in my company. Good thing about LDAP authentication is that the company will have certain policy to certain group of people. So you wouldn't mess up with your company's policy by using back the existing authentication. In my company, some projects are outsource to vendor, in order to grant them access to access our's SVN, request the admin to create a separate group of ID for them. These vendor ID will only have access to the SVN and say no to the rest. Since you mention web development, you may opt for Spring Security, this framework done a very good job on authentication, LDAP authentication shouldn't be a problem.</p>

Title: Authenticating users for a website