问:
Third-party repositories in Subversion; local mods?
I'm building a small app as an interface to support functions, monitoring, web-based running of unit tests, etc. This will be checked into Subversion.

I want to include a third-party app which is also available via Subversion. Thus far I prefer to reference the remote repository to ease upgrades, particularly when I have made local modifications.

Now, I want the third-party app to be distributed alongside the parent app. Subversion externals are out, since I can't commit my local mods. git svn seems like it has potential, but I'm not sure on the details. (Seems dirty to have a .git directory with svn metadata stored in an svn repository.)

So how do you handle modifications to Subversion projects you can't commit to? I'm pretty open to any combination of git and svn, preferably allowing the code to live in our existing Subversion repository.

Update: I'm currently exploring vendor branches, which is more convention than feature. There is a tool called svn_load_dirs.pl to assist with the process.

答:
I try to import all "old" repositories (CVS, Subversion) into a local Git or Mercurial repo. That way, I can easily track the official version, merging is much, much, much better in DCVS than in Subversion and I can branch as often as I like without any hazzle.

The only drawback so far is to get used to the idea to keep separate projects separate; don't try to import more than one project into a DCVS.


问:
ID's in resource URLs: database id or per-user id?
For REST interfaces or webapps with nice-looking URLs, I constantly ask myself on what numbers to use if we want to refer to specific resources/pages.

A typical approach seems to be to use the unique database ID of a row representing the resource as an index like http://www.mypage.com/questions/4/answers.

Using the database ID would be straightforward, however, it leaks information for resources of other users. I could also imagine that one might generate custom IDs that are only unique to one user to avoid this leaking.

It there any best practice/advice available?

答:
If your primary concern is preventing user X from accessing a resource A that's unique to user Y, then per-user ids don't solve this. What you really need is authentication, i.e. a secure way of verifying that a request for resource A is actually being made by user Y, not just some other user pretending to by Y.

If you don't have authentication, then per-user ids are merely security through obscurity. As soon as user X finds out what user Y's magic id number for resource A is, he can get resource A. If you do have authentication, then per-user ids are unnecessary, as your server can simply refuse to send resource A to anyone not authenticated as user Y.

The only time per-user ids would help is if the id itself is secret information, or indirectly exposes secret information. I can't really think of a scenario where this would actually be the case, but just to be safe I would generate GUIDs rather than incrementing a sequence number, since the sequence number reveals a little information (the order the resources were created in) while a properly-generated GUID reveals essentially nothing.

tl;dr I don't know of any reason why a per-user id would be beneficial, unless for some inexplicable reason you are unable to implement proper authentication or GUID generation.

ContentLicense: CC BY-SA 3.0


答:
I presume you are talking about guesstimating urls, that is, replacing my "/4/" with a "/42/" to see if someone else has something under http://www.mypage.com/questions/42/answers".

As far as I know the first and foremost best practice is to implement proper security everywhere, so that a user who does not have permission to see something will never be able to see it, even if they guess its url.

Of course this will not work if you want your users to be able to share their stuff with people who do not have an account on your web site.  In these cases, each url has to be public, so you want to make sure it is not discoverable. For this, you can use the second best practice, which is hashing.  So, that "/4/" would be replaced with a "/2klty046vjzm9fy/".  Many big web sites do it, for example dropbox.  Sign up for a free dropbox account, upload a file, ask dropbox to give you its public link, and you will see that its url contains such a hash.  Then, upload another file, ask for its public link, and you will see that the hash of that file is completely different, so it is not your own per-user id, it is something unique.  Google documents does the same thing for docs that you want to be able to show to users who do not have google accounts.

Judging by your reputation, you probably know how to create a hash; if not, that could perhaps be the subject of a different question.

Title: ID's in resource URLs: database id or per-user id?

Body:
For REST interfaces or webapps with nice-looking URLs, I constantly ask myself on what numbers to use if we want to refer to specific resources/pages.

A typical approach seems to be to use the unique database ID of a row representing the resource as an index like http://www.mypage.com/questions/4/answers.

Using the database ID would be straightforward, however, it leaks information for resources of other users. I could also imagine that one might generate custom IDs that are only unique to one user to avoid this leaking.

It there any best practice/advice available?


问:
Do you have any team guidelines regarding exceptions?
My team recently inherited a project from a team where the amount of developers dropped so low they had to offload some work. One of the projects we inherited was a project littered with nested code, and awful exception handling (Exceptions were in effect handled as goto statements and thus used as a part of the normal program flow.).

All in all it was a hairy code ball someone had been coughing up for a few years.

Now we've been having a few team guidelines in place for quite some time, but all of the regards to the structures of objects, coding styles and what not. But we haven't covered exception handling.

So I'm wondering if you have any guidelines in your teams regarding exception handling, and if so how you enforce them?

答:
Currently we don't have explicit guidelines, mostly because nobody in my team does it wrong. (Unlike many other topics, there is a general consensus when and how exceptions should be used)

But I would definitely implement them the same day I see an exception abused as a goto.

ContentLicense: CC BY-SA 2.5


问:
How to make consistent progress towards the goal of becoming better, as opposed to just coding for fun?
I'm in senior year in high school. I enjoy programming (Java) very much and aspire to do it as a career in the future. However this isn't the topic of this question.

My question is: how can I start making consistent progress towards the goal of becoming a great programmer?

What I mean is this:

I work on my own projects, enjoy doing so and feel like I'm slightly improving with every project I finish.

However, I don't feel like I'm consistently moving towards 'the goal of becoming a great programmer'. I want to have a sense of 'working towards the goal'.

What I feel right now is more like "I'm coding stuff which is a lot of fun and I'm improving, but I don't feel like I'm 'making progress towards my goal'".

"Slightly improving over time because I'm coding stuff" doesn't really feel like "making progress towards a goal".

To those of you who are experienced developers: what advice can you give me on making consistent progress towards the goal of becoming great at programming, as opposed to just coding stuff for fun?

答:
Never let your skillset become stagnant - always be pushing into new areas you are unfamiliar with.

Continue making projects, because an active understanding of something is far better than a passive understanding.

Pick up new tools, learn new languages, apply new ideologies, get into new areas. Dive into the deep end.

Make bigger and more complex projects each time.

Write something with one more person, then maybe two or three other people.

Expose yourself to the programming community - read blogs, follow news, check link aggregators.

Write tons of code. One of my favorite quotes about writing applies to programming, too: "Everyone has a million bad words in them. Only once they've written those million words can they start writing well. So get writing!"


问:
Usage of objects in multiple containers in C++
In cases where there is a desire for objects to be "shared" between multiple containers, I would like to know what is the best practice in C++. For example, when implementing some path algorithms (such as A*), I have implemented a 2-dimensional array of Nodes (user-defined class), and I also want to have a Set, where specific Nodes will be added and removed during the execution of the algorithm. However, when adding a Node in the Set, I want to store this specific Node (and not a copy), so that modifications in the objects of the Set are also visible in the 2-dimensional array. I guess there are 2 approaches :

hold different copies of the Nodes in Set and 2-d array, and also create a mechanism that would synchronize the copies, so that modifications are passed from one to the other. However, this would be hard to implement and it would also consume a lot of memory, due to a lot of redundant copies of the nodes.

the 2 containers (the 2-dimensional array and the set) just hold pointers to Nodes. So, when I want to add a specific Node in the set, I retrieve the pointer to this node from the 2-d array and insert the pointer to the Set.

Since, I have concluded that the second solution must be the right one, I would like to ask the following questions :

During learning C++, I have found books recommending to avoid creating containers with pointers. So, should I just accept this case as an exception to the rule ?

How should I optimally design the initialization of the Nodes and the destruction (freeing of resources), since both the 2-d array and the Set will hold pointers ?

答:
During learning C++, I have found books recommending to avoid creating
  containers with pointers. So, should I just accept this case as an
  exception to the rule ?

No, burn the books instead. There's nothing special about T* that makes it unsuitable in a container.

How should I optimally design the initialization of the Nodes and the
  destruction (freeing of resources), since both the 2-d array and the
  Set will hold pointers ?

Use std::shared_ptr, which uses refcounting to handle multiple owners.

Judging by the content of your post, I'm going to posit that you're in a pre-smart-pointer state, so let me give you a core piece of advice. Don't ever use new and delete, because it's almost impossible to write correct programs with them and this is just the tip of the iceberg in the ways in which that completely does not scale from trivial programs at all- for example, exceptions.

Always use a dedicated resource-holding object to handle resources. Never free them yourself.


答:
First off, containers that hold raw pointers are only problematic because those pointers could become invalid/out of date at any time (from the point of view of the pointer container). Same goes for containers of iterators.

Possible solutions I can think of:

1) The slightly-less-dangerous option: Store the objects in a stable, node-based container such as std::list, std::map or std::set so that a pointer/iterator to a single object is guaranteed to remain valid as long as that particular item has not been removed from the container. This still requires a significant amount of synchronization on your part, so it's rarely the best move, but it's almost always an option.

2) One safe option: Use shared pointers in both containers, so that all the resources are guaranteed by the language to get cleaned up correctly in a deterministic fashion.

3) Another safe option: Don't use pointers/iterators at all, and come up with some other way of referencing the 2D array from the set. For instance, the set could contain std::pairs of ints that represent indexes into the 2D array.

4) The ideal option: Refactor your code so you don't need two data structures in the first place. Needing to store a container of pointers/iterators would be a code smell, even if it was

Which of these options is the best depends heavily on your code. For example, if the Set you're talking about exists solely within a doAStar() function that takes a reference to a 2D array, and no concurrency is involved, then I would personally go for #3. In this case the array is guaranteed not to change during the function call so smart pointers are overkill, and the Set is strictly temporary so the "code smell" isn't really there.

Title: Usage of objects in multiple containers in C++

Body:
In cases where there is a desire for objects to be "shared" between multiple containers, I would like to know what is the best practice in C++. For example, when implementing some path algorithms (such as A*), I have implemented a 2-dimensional array of Nodes (user-defined class), and I also want to have a Set, where specific Nodes will be added and removed during the execution of the algorithm. However, when adding a Node in the Set, I want to store this specific Node (and not a copy), so that modifications in the objects of the Set are also visible in the 2-dimensional array. I guess there are 2 approaches :

hold different copies of the Nodes in Set and 2-d array, and also create a mechanism that would synchronize the copies, so that modifications are passed from one to the other. However, this would be hard to implement and it would also consume a lot of memory, due to a lot of redundant copies of the nodes.

the 2 containers (the 2-dimensional array and the set) just hold pointers to Nodes. So, when I want to add a specific Node in the set, I retrieve the pointer to this node from the 2-d array and insert the pointer to the Set.

Since, I have concluded that the second solution must be the right one, I would like to ask the following questions :

During learning C++, I have found books recommending to avoid creating containers with pointers. So, should I just accept this case as an exception to the rule ?

How should I optimally design the initialization of the Nodes and the destruction (freeing of resources), since both the 2-d array and the Set will hold pointers ?


答:
Work on a unix platform.  I worked on Unix for 1 year in 1999 before returning in 2010.  I should have never left.  Compare your skills to others either locally or online to judge your progress.

Use VI and avoid IDE's  They are a knowledge sink that will expire.  This is one of the intangible items

Buy programming books and set goals to read chapters in x days/weeks and make sure you read the books completely.  See

If you could only have one programming related book on your bookshelf what would it be and why? for a good list.  Mark your progress by pages / chapters / books - whatever you prefer to track that helps you keep going.

Buy programming books in an online format, e.g. a Kindle and set goals to complete them.

get good at using your development environment on your OS.  It is your toolset.  Learn how to customize it and use the tools and functions available.  This will pay off constantly, not be a goal in itself.

Use code analysis tools, e.g. Fisheye.  More details at https://stackoverflow.com/q/60394/631619  This will give you feedback on the quality of code and help you improve.

find ways online to work with other programmers to share and compare your self to millions of others.

recognize that this learning will be life long.  Have a mind set for the long term.

consider setting yourself goals on Stack Exchange Sites.  I set a goal of 1,000 badges across the network and I'm at 972 right now.

Title: How to make consistent progress towards the goal of becoming better, as opposed to just coding for fun?

Body:
I'm in senior year in high school. I enjoy programming (Java) very much and aspire to do it as a career in the future. However this isn't the topic of this question.

My question is: how can I start making consistent progress towards the goal of becoming a great programmer?

What I mean is this:

I work on my own projects, enjoy doing so and feel like I'm slightly improving with every project I finish.

However, I don't feel like I'm consistently moving towards 'the goal of becoming a great programmer'. I want to have a sense of 'working towards the goal'.

What I feel right now is more like "I'm coding stuff which is a lot of fun and I'm improving, but I don't feel like I'm 'making progress towards my goal'".

"Slightly improving over time because I'm coding stuff" doesn't really feel like "making progress towards a goal".

To those of you who are experienced developers: what advice can you give me on making consistent progress towards the goal of becoming great at programming, as opposed to just coding stuff for fun?


问:
std::vector Non-Array Implementation?
I've seen some posts on the StackExchange family of sites talking about std::vector implementations. They all seem to indicate that std::vector is implemented strictly as an array (in practice), and that C++ 2003 dictates contiguity of elements - pretty much closing non-array loopholes.

Now I thought that I had read once of a non-array implementation of std::vector - perhaps this predated the 2003 enforcement of contiguity? (Edit: Herb Sutter makes note of this here) I believe it was something like a series of linked arrays with decreasing or increasing sizes under the hood but I can't remember the details. Does anyone know of std::vector implementations (or perhaps, more broadly, non-STL vector implementations) that use a non-array approach like this?

Edit: I'd like to clarify here that the emphasis is less on strict std::vector implementation for C++ and rather more on 1) historical STL implementations prior to C++ 2003 contiguous elements constraints or possibly even 2) "vector" implementations in other languages - that do not use the usual array-like structure. A VList implementation of a vector might be a potential example and I'm looking for others.

答:
StackOverflow would be a somewhat better place for asking programming/algorithm related questions.
In any case, the implementation you must have read would be based on "tables". Here is how such implementation works:

Initialize vector with size n, say n = 16

Address: 0xAAA0 to 0xAAB0  Memory reserved

Insert 17 elements. First 16 inserted fine. Next element requires more memory.

STL Library: Allocate memory for 16 * 2 = 32. Copy 16 elements. (Actual time taken = 16 units). Insert the 17th element.

Insert 16 more elements. First 15 inserted fine. Next element requires more space.

STL Library: Allocate memory for 16 * 2 * 2 = 64. Copy 32 elements. (Actual time taken = 32 units).
Insert the 33rd element.

Insert 32 more elements. First 31 inserted fine. Next requires more space.
STL Library: Allocate memory for 16 * 2 * 2 * 2 = 128. Copy 64 elements. (Actual time taken = 64 units).
Insert the 65th element.

This implementation is O(1) for accessing and O(1) amortized for insertion. How? Over a very large number of operations, the total time of inserts would be:

Time = 2^0 (inserts) + 2^0 (copy) + 2^1 / 2 ( inserts ) + 2^1(copy) + 2^2/2 (inserts) + 2^2 (copy) ... .. + 2^n(copy)

Total number of inserts = 2^n
Time = 2^0 + 2^0 + 2^0 + 2^1 + 2^1 + 2^2 + 2^2 = 1 + 2*2^0 + 2*2^1 +...+2*2^(n-1)
= 1 + 2*(2^n - 1)

Average time per insert = 2 units

Total inserts = 2^n + 1
Time = 2^0 + 2^0 + 2^0 + 2^1 + 2^1 + 2^2 + 2^2 + 2^3 ... = 1 + 2*2^0 + 2*2^1 +...+2*2^(n-1)  + 2^n
= 1 + 2*(2^n - 1) + 2^n

Average time per insert = 3 units

Its not a linked list- but I'm pretty this is what you read:  'increasing/decreasing' sizes. Decrease in size upon deletes is similar. When used size is less than 1/4, free up the rest of memory, free up half of memory. If you're using your own memory allocator, it shouldn't be too hard to free only what you want. But if you want to copy over as well, analysis would tell you deletes still remain O(1)

Title: std::vector Non-Array Implementation?


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答: It fits with how some people think. I don't like them, but I have friends who seem to think in regexps. I guess the pattern matching part of their brain is more exposed than the formal logic one. :-)</p>


问:
What information should go into file-level document block?
I primarily develop for Node.js. I got into a habit of putting a file-level docblock into all of my .js files. It looks something like this:

```<code>/**
 * project-name
 *
 * Licensed under the BSD-3-Clause license
 * For full copyright and license information, please see the LICENSE file
 *
 * @author     Name <email>
 * @copyright  Year Name
 * @link       project-repository-url
 * @license    http://choosealicense.com/licenses/bsd-3-clause  BSD-3-Clause License
 */

// Code starts here...
</code>```

When I started with Node.js, this seemed like a good idea to describe what project the file belonged to, how it was licensed and who was the author. Before Node.js I worked a lot with PHP and some documentation tools even recommended/required such file-level docblock.

Recently, though, I started feeling like a lot of that information is redundant:

Licensing information is available in the LICENSE file

Authorship/copyright information is available in the package.json / composer.json / whatever file

The fact that license information is in LICENSE file is nowadays a well-known fact

And so I am left with maybe the project's name. Since I do not like the feeling of completely removing the file-level docblock (it feels as if something is missing), I ask thee:

What information (if any) should go into file-level docblock?

To make the question a bit more factual than opinion-based:

What was the original motivation/intent that people started writing these file-level docblocks?

I suspect this will be something along the lines "In the early 90s..."

How does that intent translate into current modern software development environment? Are any of those intents still valid/reasonable?

Is there any other information I might consider adding to a file-level docblock that I do not already have there?

答:
Repeating information at the beginning of each source code file makes IMHO only sense to minimize the risk of separation of license & copyright information from the particular file. So if that information is already stored elsewhere, the absolute minimum you should add is a reference to the place where to find that information. If someone sends you a single source code file as an email attachment, the project's name is probably not enough to find out what license the code is under or where to find the license information. So having a hint in the source code file that there is an additional license file gives you the chance to ask the person who send you the mail to add the missing files.

If many people have access to the source code, like in open source projects, the more important it becomes to prevent the separation. And when you have different contributors to a project, there might be different copyrights, different authors, and individual license conditions for individual source code files. For such projects, it seems to be reasonable to provide a bigger, standardized docblock, with placeholders for all the information you listed above.


问:
Understanding Tarjan's Bridge-finding algorithm
Tarjan's algorithm for finding bridges in a graph is found here: http://en.wikipedia.org/wiki/Bridge_(graph_theory)#Tarjan.27s_Bridge-finding_algorithm.

However, I don't understand the condition for checking if an edge is a bridge. I get that L(w) = w is a necessary condition, but I think that the condition for H(w) < w + ND(w) is redundant, since you're always guaranteed for that to be true (when doing the pre-order traversal, all the vertices in the subtree of w are visited consecutively and are numbered consecutively, and H(W) has to be in the subtree of w, making H(W) < w + ND(W) always true).

So I'm curious if the H(W) < w + ND(W) condition is even necessary, and if so, can you provide an example case where it is needed?

答:
The L() test, yes, handles loops or cycles. It also handles cross links in unrelated branches in the spanning tree that are to the left (or have lower preorder number).

But here is why I think you need the H() test. The H() test handles cross links to branches in the spanning tree that are unrelated and to the right (or have higher preorder number).

Here is an example. Suppose your graph is:

```<code>  A
B   C
|   |
D - E
</code>```

Where the spanning tree in list form is [A [B [D]] [C [E]]]. But there is also a cross edge from D to E which is rightward with respect to D.

Note that H(D) will be the preorder value for E, the highest number of the spanning tree. Without that edge A-C would be a bridge. It isn't though because of the test  on H(D).

Body:
The L() test, yes, handles loops or cycles. It also handles cross links in unrelated branches in the spanning tree that are to the left (or have lower preorder number).

But here is why I think you need the H() test. The H() test handles cross links to branches in the spanning tree that are unrelated and to the right (or have higher preorder number).

Here is an example. Suppose your graph is:

  A
B   C
|   |
D - E

Where the spanning tree in list form is [A [B [D]] [C [E]]]. But there is also a cross edge from D to E which is rightward with respect to D.

Note that H(D) will be the preorder value for E, the highest number of the spanning tree. Without that edge A-C would be a bridge. It isn't though because of the test  on H(D).


问:
Advantage in being the first to copyleft a new algorithm?
Say I have created a new (DSP) algorithm. Will I have some advantage if I open source the algorithm under copyleft licence (GPL etc.)? From what I know about licensing this should lock people out from using the exactly same code as closed source, but would they be able to "rewrite" the algorithm as closed source?

Note: I don't really know if the algorithm is new but it has not been released as open source yet. Since I am from the European Union do I need to look for software patents if I wanted to copyleft it?

答:
The restrictions in copyleft licenses like the GPL apply to modified versions of your code as well as your original code. So they can't just tweak the whitespace or brace style and then delete your license statement.

However, you can't patent/copyright/copyleft/whatever an "algorithm" in its most abstract sense. You can put a license on your favorite implementation of quicksort, but you can't license quicksort itself. If someone reads your code just to learn the algorithm, and then rewrites the algorithm from scratch in their own way, that's fine.

As far as I know, there is no "advantage" to being the first one to publish an algorithm other than possibly some fame and (real-world) reputation if it's particularly noteworthy. Being the first to copyleft it definitely doesn't gain you anything, but the fact that someone copylefted it will be seen as a benefit to the free software community.


答:
If you want to prevent a patentable thing from being patented and then "closed off" from the greater community you could do a defensive disclosure. Cuis Smalltalk, for instance, did this with some new anti-aliasing techniques:

http://www.defensivepublications.org/publications/prefiltering-antialiasing-for-general-vector-graphics

https://priorart.ip.com/IPCOM/000232657

Title: Advantage in being the first to copyleft a new algorithm?

Body:
Say I have created a new (DSP) algorithm. Will I have some advantage if I open source the algorithm under copyleft licence (GPL etc.)? From what I know about licensing this should lock people out from using the exactly same code as closed source, but would they be able to "rewrite" the algorithm as closed source?

Note: I don't really know if the algorithm is new but it has not been released as open source yet. Since I am from the European Union do I need to look for software patents if I wanted to copyleft it?


问:
What to do about large svn history when moving to git?
Edit: unlike some similar questions such as Moving a multi-GB SVN repo to Git
or
https://stackoverflow.com/questions/540535/managing-large-binary-files-with-git
My scenario doesn't involve several subprojects that can be easily converted into git submoduels, nor a few very large binary files that are well suited for git-annex. It is a single repository where the binaries are the test suite which tightly coupled to the main source code of the same revision, much like if they were compile time assets such as graphics.

I'm investigating switching an old medium/large sized (50 users, 60k revisions, 80Gb history, 2Gb working copy) code repository from svn. As the number of users have grown, there is a lot of churn in trunk, and features are often spread out on multiple commits making code review hard to do. Also without branching there is no way to "gate" bad code out, reviews can only be done after it is committed to trunk. I'm investigating alternatives. I was hoping we could move to git, but I'm having some problems.

The problem with the current repo as far as git goes is size. There is a lot of old cruft in there, and cleaning it with --filter-branch when converting to git can cut it down in size by an order of magnitude, to around 5-10GB. This is still too big. The biggest reason for the large repository size is that there are a lot of binary documents being inputs to tests. These files vary between .5mb and 30mb, and there are hundreds. They also have quite a lot of changes. I have looked at submodules, git-annex etc, but having the tests in a submodule feels wrong, as does having annex for many files for which you want full history.

So the distributed nature of git is really what's blocking me from adopting it. I don't really care about distributed, I just want the cheap branching and powerful merging features. Like I assume 99.9% of git users do, we will use a blessed, bare central repository.

I'm not sure I understand why each user has to have a full local history when using git? If the workflow isn't decentralized, what is that data doing on the users' disks? I know that in recent versions of git you can use a shallow clone with only recent history. My question is: is it viable to do this as the standard mode of operation for an entire team? Can git be configured to always be shallow so you can have a full history only centrally, but users by default only have 1000 revs of history? The option to that of course would be to just convert 1000 revs to git, and keep the svn repo for archeology. In that scenario however, we'd encounter the same problem again after the next several thousand revisions to the test documents.

What is a good best practice for using git with large repos containing many binary files that you do want history for? Most best practices and tutorials seem to avoid this case. They solve the problem of few huge binaries, or propose dropping the binaries entirely.

Is shallow cloning usable as a normal mode of operation or is it a "hack"?

Could submodules be used for code where you have a tight dependency between the main source revision and the submodule revision (such as in compile time binary dependencies, or a unit test suite)?

How big is "too big" for a git repository (on premises)? Should we avoid switching if we can get it down to 4GB? 2GB?

答:
As the number of users have grown, there is a lot of churn in trunk,
  and features are often spread out on multiple commits making code
  review hard to do. Also without branching there is no way to "gate"
  bad code out, reviews can only be done after it is committed to trunk

Moving to git will not solve these problems, they're issues in how you use the tool and if you use git the same way, the issues will remain.

You can branch in svn just as easily in git, and merging is generally just as easy and has the same pitfalls. Git was designed for working with the kernel source code, so it made some assumptions that may not apply in all cases, such as yours with big binaries and massive histories. The intention behind a DVCS is that every user effectively works alone and only collaborates afterwards - ie they have their own repo (a copy), work how they like and then push the changes to anyone else who wants it. A federated system used in linux kernel development is perfect for this - you push your changes to the next guy up the chain who merges it with his codebase and then pushes it to the next guy until it gets to Linus who puts it in the release. Most teams use git similarly, but with only 1 upstream guy which is often a server-side 'gold' repo, somewhat making git similar to a disconnected CVCS.

So I'd look at changing your workflow first, only migrating to git once you have a better way of working. Implement branching and merging in SVN, if you don't rename files or directories merging goes quite well.


问:
Pick highest score sum, but at least X from each region
Can you think of a solution to the following seemingly simple algorithmic problem?

I am given a list of data points with scores and regions they belong to: [(9, A), (8, B), (7, A), (3, C),  ...]. Scores are floats and each regions can have multiple data points assigned.

For each number N I'd like to select N data points from this list to maximize the total sum of these N scores. Without any restriction, you would chose the top scores, of course.

But now I have the constraint that in each region you have to pick at least X points or none at all. Therefore I cannot have a "sparse" region.

How would you solve this? An algorithm should output for each N the number of points chosen from each region.

答:
I agree with @null's suggestion of having sorted lists for each region.

So how my approach to this problem would be :

Create distinct sorted lists for each region such that they would be sorted based on their scores and you would have a different list for each region. Of course there are several ways of accomplishing this, which way you should use depends on your data set.

For example at the end, you may have something like this:

```<code>regionA = [(9,A),(6,A),(4,A)]
regionB = [(7,B),(6,B),(5,B),(4,B)]
regionC = [(15,C),(4,C)]
</code>```

After you've created your separate sorted lists for each region. Check if any list is shorter than X, if so discard this list.

So for above example, say if X = 3, we would discard regionC.

Now you should have separated sorted lists for regions that have more than X elements. Since they're already sorted by their scores, now all you have to do is; simply take the sums of scores of the highest/first(assuming descending sorting) N elements from each list and compare them. The highest sum you got is the selection you should go for.

Example continued; let's take N = 3. We are left with regionA and regionB left now. For which the first 3 element sums would be  sumA = 19, sumB = 18. In which case we would choose the region A.

Body:
I agree with @null's suggestion of having sorted lists for each region.

So how my approach to this problem would be :

Create distinct sorted lists for each region such that they would be sorted based on their scores and you would have a different list for each region. Of course there are several ways of accomplishing this, which way you should use depends on your data set.

For example at the end, you may have something like this:

regionA = [(9,A),(6,A),(4,A)]
regionB = [(7,B),(6,B),(5,B),(4,B)]
regionC = [(15,C),(4,C)]

After you've created your separate sorted lists for each region. Check if any list is shorter than X, if so discard this list.

So for above example, say if X = 3, we would discard regionC.

Now you should have separated sorted lists for regions that have more than X elements. Since they're already sorted by their scores, now all you have to do is; simply take the sums of scores of the highest/first(assuming descending sorting) N elements from each list and compare them. The highest sum you got is the selection you should go for.

Example continued; let's take N = 3. We are left with regionA and regionB left now. For which the first 3 element sums would be  sumA = 19, sumB = 18. In which case we would choose the region A.


答:
This is tricky. Obviously you ignore all regions with fewer than X scores. If N < X then there is no solution, except the trivial solution when N = 0. If X ≤ N < 2X then you must pick all N scores from the same region, which is either trivial to do optimally, or impossible. If X = 1, that's not a restriction, we just pick the highest scores.

What makes it tricky is that we don't even necessarily use the region where the top X scores added up are highest. Let's say X = 3 and N = 8, and scores (1001,1000,1000), (1000,1000,1000,1000), (1000,1000,1000,1000), (0,0,0,0,0). If we use 3 scores from the first region, we must use the scores from the last region, which is much worse than using the second and third region.

An optimal solution will pick k regions, where kx ≤ N and the total number of scores in these regions is ≥ N, pick the highest X scores from each region, then pick the remaining N - kx scores from those regions.

You might have to do an exhaustive search, excluding as many cases as possible. There are many things to reduce the number of cases in an exhaustive search.

We say that Region A > Region B if the sum of the highest X scores is same or higher, and if B has k scores for k > X then A also has k scores, and the sum of the highest k scores is the same or higher as well, and if all scores are the same then A must come first in your list of regions. With that definition, we don't need to look at solutions that contain B but not A. Depending on the data, that might exclude lots of possibilities.

If region R is less than several regions with a total of n scores then we can ignore region R completely. Region R may be "less than" two regions combined: If whatever scores we take from region R, we can equal or better with scores from A and B according to the rules, then we can ignore R if neither of A and B is part of the solution.

Title: Pick highest score sum, but at least X from each region

Body:
Can you think of a solution to the following seemingly simple algorithmic problem?

I am given a list of data points with scores and regions they belong to: [(9, A), (8, B), (7, A), (3, C),  ...]. Scores are floats and each regions can have multiple data points assigned.

For each number N I'd like to select N data points from this list to maximize the total sum of these N scores. Without any restriction, you would chose the top scores, of course.

But now I have the constraint that in each region you have to pick at least X points or none at all. Therefore I cannot have a "sparse" region.

How would you solve this? An algorithm should output for each N the number of points chosen from each region.


问:
A Factory could be replaced by a key on the web.config? How would be the trade-offs of each approach?
The Problem

We had a Environment class which would choose whether or not to use a webservice (it was set by a web reference) for our authentication methods by reading the host environment and if it was production or the same as the webservice would invoke it, otherwise would run the code before the migration for the webservice.

Bad design, poor testing - when working on authentication we manually forced the webservice to be in the same environment we were testing so the webservice would be called.

The Solution

The Enviroment class was killed

We created another webservice equals to the production but hosted on the same environment that calls it

An interface that is implemented by both webservices was designed

Now we use a factory to return the right webservice for those who want to authenticate, it is possible due to the interface so if we needed to change the webservice we would only change the new interface accordly.

Different Flavours of Wrong

A person said she'd go with a key in the web.config ["I wouldn't use interfaces but the web.config"] to return the right webservice but I fail to see how it solve our problem and I don't feel comfortable to argue with/ask her due to politics and our technical skills (newbie me).

Here are some thoughts on my mind:

Would her key return the correct type for those who seek authentication? If so what would be the "interface" to authenticate?

Would her key be a boolean? In this case I'd need to write an if-else for each authentication method to call the right webservice?

Would her key be a string? I guess it could have the host address so only one webservice would be used and one of its proprieties would be changed on-the-fly before calling its methods (I don't know if it is possible, btw)

Relevant

The webservice were created on the IDE, we'd not change theirs auto-generated code, but as they also are partials we could implement our interfaces in different files.

I didn't find if it's possible to change the entry point of a webreference we generated automatically. The IDE writes methods it has found on that address and it acts as a proxy for the service.

The factory helped us to avoid repetitive and unnecessary code, I don't see it happening with other solutions but the string on a key.

答:
If I understood your colleague's suggestion correctly, the solution proposed was to have a web.config key that contains a type name for the implementation class. You can use this name to retrieve the type, instantiate it (or register in DI container), and use it. I.e.:

```<code>public interface IAuthenticationBlaBla
{
    ...
}

public class WebServiceAuthenticationBlaBla : IAuthenticationBlaBla {...}
public class AnotherAuthenticationBlaBla : IAuthenticationBlaBla {...}
</code>```

web.config:

```<code><add key="AuthenticationType" value="Namespace.WebServiceAuthenticationBlaBla" />
</code>```

somewhere in the initialization code (using DI, Autofac in this case):

```<code>ContainerBuilder builder = new ContainerBuilder();
...
builder.RegisterType(Type.GetType(ConfigurationManager.AppSettings["AuthenticationType"]))
    .As<IAuthenticationBlaBla>();
</code>```

Body:
If I understood your colleague's suggestion correctly, the solution proposed was to have a web.config key that contains a type name for the implementation class. You can use this name to retrieve the type, instantiate it (or register in DI container), and use it. I.e.:

public interface IAuthenticationBlaBla
{
    ...
}

public class WebServiceAuthenticationBlaBla : IAuthenticationBlaBla {...}
public class AnotherAuthenticationBlaBla : IAuthenticationBlaBla {...}

web.config:

<add key="AuthenticationType" value="Namespace.WebServiceAuthenticationBlaBla" />

somewhere in the initialization code (using DI, Autofac in this case):

ContainerBuilder builder = new ContainerBuilder();
...
builder.RegisterType(Type.GetType(ConfigurationManager.AppSettings["AuthenticationType"]))
    .As<IAuthenticationBlaBla>();


Title: Why are regular expressions so morbidly attractive?

Body:
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

Body: When the only tool you have is a regex, every problem looks like ^((?>[a-zA-Z\d!#$%&'*+\-/=?^_{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$


问:
Event Driven Programming?
I have been looking into event driven programming in C and the language doesn't seem to have support for it. This has led me to wonder about the nature of event driven programming. Is it correct to say that an event handler basically spawns a thread that waits for a response from I/O and sets a variable? Or is there something more complicated to the process. </p>

答:
An event loop library could be single-threaded if it uses some multiplexing facility to wait for several events, inputs (and outputs, e.g. ability and readiness to write some bytes on some pipe or socket).

On Linux and POSIX systems, you could use some multiplexing syscall like poll(2) or select(2). So you can have single-threaded event loop libraries, and (at least historically, e.g. in the previous century) several event-looping libraries (like libev, libevent, Glib from GTK) are -or have been- single threaded (so they don't spawn new threads).

Even recent GUI frameworks like Qt5 or GTK3/Gnome still require (on Linux) the graphical user code to be in the main thread.

You could also have some event loop, even in free-standing C programs like those driving microcontrollers. Then they would use some code (perhaps in assembly) to wait for events or interrupts, etc.

Title: Event Driven Programming?


问:
Way to organize repetitive text in Java
Some times I have texts that appears in different places, like comments, messages... For example if I have a custom Exception, probably class doc, messages that passes as parameter to its constructor will have the same phrases (here This exception throws under situation1):

```<code>/**
 * This exception throws under situation1 ...
 *
 */
public class SomeException extends Exception {

    public static class Builder{
        String message = "This exception throws under situation1. So ... ";

        public Builder(String message) {
            this.message = this.message + "\r\n" + message;
        }
        public SomeException build(){
            return new SomeException(this);

        }
    }

    private SomeException(String detailMessage) {
        super(detailMessage);
    }

    public SomeException(Builder builder) {
        this(builder.message);
    }
}
</code>```

And also documents of each method that throw exception will have the same phrase:

```<code>/**
 * @throws SomeException
 *             This exception throws under situation1 ...
 */
private void test() throws SomeException {
    throw new SomeException.Builder("message").build();
}
</code>```

If I copy/paste phrase, maintenance of documents will be hard (it needs finding and updating all repeats on each edit).

To solve this, I can use a constant string that its value and its comment are those repetitive terms

```<code> /**
  * exception throws under situation1
  */
public static final String CONSTANT = "exception throws under situation1";
</code>```

and reference to it (and it's comment):

```<code>/**
 * {@link MyClass#CONSTANT}
 */
String message = MyClass.CONSTANT;
</code>```

But how organize constants when are more than one? With respect to this answer and this one, it seems the best way to organize them is using Enum:

```<code>public enum Meta {
    /**
     * exception throws under situation1
     */
    CONSTANT("exception throws under situation1");

    private String text;

    Meta(String text) {
        this.text = text;
    }

    public String getText() {
        return this.text;
    }

}
</code>```

But is there a better way than this? Especially it complicates code.

答:
Put your strings into a ResourceBundle, as though you were internationalizing the application. There are a number of tutorials out there for doing this sort of thing, but for the most part they boil down to exactly the problem you're describing: putting text into a common location, where you can later refer to it by an identifier of some kind.

People often think of this solely in terms of making it easier to translate an application into other languages, but it is also useful for situations like this, where you have to repeat the same message many times. As an added bonus, when and if you do decide to internationalize the app, the basic infrastructure will already be in place. All you'll have to do is add more languages.

Title: Way to organize repetitive text in Java


问:
Why pointer symbol and multiplication sign are same in C/C++?
I am writing a limited C/C++ code parser. Now, multiplication and pointer signs give me really a tough time, as both are same. For example,

```<code>int main ()
{
  int foo(X * p); // forward declaration
  bar(x * y);  // function call
}
</code>```

I need to apply special rules to sort out if * is indeed a pointer. In above code, I have to find out if foo() is a forward declaration and bar() is a function call. Real world code can be lot more complex. Had there been different symbol like @ for pointers, then it would have been straight forward.

The pointers were introduced in C, then why some different symbol was not chosen for the same ? Was keyboard so limited ?

[It will be an add-on if someone can throw light on how modern day parser deal with this ? Keep in mind that, in one scope X can be typename and another scope it can be a variable name, at the same time.]

答:
I do not know for sure, but I would be willing to bet that the answer is because the inventors of C ran out (or nearly ran out) of characters.

The original intention was that the language should use symbols for operators, and also that the language must be expressable within the so-called "lower" ASCII table, which consists of ASCII values 0 through 127.

The first 31 values are unprintable control characters, so we are left with this:

 !"#$%&'()*+,-./0123456789:;<=>?

@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_

`abcdefghijklmnopqrstuvwxyz{|}~

Remove the space, and all characters needed for identifiers, (which are all letters, all numbers, and the underscore,) and and we are left with this:

!"#$%&'()*+,-./:;<=>?@[\]^{|}~

Remove parentheses, braces, and brackets, as well as the backtick (`), which is not sufficiently dissimilar from the single quote, and we are left with this:

!"#$%&'*+,-./:;<=>?@\^|~

Remove punctuation which is critical for the syntax of the language, ("#',.:;?) and we are left with this:

!$%&*+-/<=>@\^|~

Remove the ampersand (&), which stands for "taking the address of" something, and which must therefore be distinctly different from anything that has to do with pointers, as well as comparisons, (<=>), exclamation (!), plus (+), and minus (-), which are valid operations to perform on pointers, and we are left with this:

$%*/@\^|~

I am not sure why the dollar sign and the at-sign were not considered; perhaps they were thought of as being a bit too bulky to make frequent use of in code.  So, take them out, and we are left with these:

%*/\^|~

As you can see, all of the above characters are used as operators for various arithmetic and logical operations in C, which means that they had to reuse one of them as the character for declaring and dereferencing pointers.

They chose the asterisk (*), which is a decent choice because it somewhat bears the notion of a "point", and because multiplication is not one of the operations which are valid to perform on pointers.

They could have also chosen the caret (^), (which stands for exclusive-OR,) but I do not think that it is such a huge deal, and clearly, their options were very limited.


问:
Audio driver which filters outgoing sound out of incoming
I'm sure this has been asked before but I can't seem to find anything about this, in theory, is it possible to write an audio driver which takes the incoming audio (from microphone), and compares it to outgoing audio (sound played through speakers/headset).

The reason I ask?

I know for a fact lots of gamers would love to be able to play sound through their speakers instead of their headsets, but when they use VoIP programs people tend to complain a lot about echoes & ambient noise.

As for a more tangible example:

User plays music through speakers, but when talking on VoIP (without any volume reduction), the driver then takes that incoming sound & "subtracts" the outgoing audio from it, which leads to the other VoIP users not being able to hear the music/themselves talking, but they will still be able to hear the user.

Note: I'm not entirely sure if this is possible even in theory due to my lack of understanding of the workings of sound (be it digital signals and actual waveforms).

答:
Automatic acoustic echo cancellation is routinely done for cellphones and speakerphones.

It uses a least mean squares adaptive filter.  (Usually, the normalized least mean squares filter is used, along with a pre-whitening filter.)

Wrapping your head around the technology is not all that easy.  The best textbook I've found is Haykin's "Adaptive Filters".  Widrow & Stearns "Adaptive Signal Processing" is not as clear.  Both texts assume a basic understanding of digital signal processing and digital filters.

There's a Wikipedia article.


答:
Your question is very hard to read, But I think I can answer the general question. my understanding of your problem is this:

You have a website which authenticates users via a web service

You need to be able to test the website

You should ensure your setup has these things:

The authservice client code implements an interface.

You have created a Mock auth service implementing the same interface

You inject either the real auth service or the mock via DI

The DI is configured via web.config

The real auth service should read its end point url from web.config

this enables you to set up your test and live environments via the web.config in various different ways

Live : Live endpoint URL, Real Auth service injected

Pre Live/Test : Test endpoint url, real auth service injected

Test/Dev Machine : Mock auth service injected

Title: A Factory could be replaced by a key on the web.config? How would be the trade-offs of each approach?

Body:
The Problem

We had a Environment class which would choose whether or not to use a webservice (it was set by a web reference) for our authentication methods by reading the host environment and if it was production or the same as the webservice would invoke it, otherwise would run the code before the migration for the webservice.

Bad design, poor testing - when working on authentication we manually forced the webservice to be in the same environment we were testing so the webservice would be called.

The Solution

The Enviroment class was killed

We created another webservice equals to the production but hosted on the same environment that calls it

An interface that is implemented by both webservices was designed

Now we use a factory to return the right webservice for those who want to authenticate, it is possible due to the interface so if we needed to change the webservice we would only change the new interface accordly.

Different Flavours of Wrong

A person said she'd go with a key in the web.config ["I wouldn't use interfaces but the web.config"] to return the right webservice but I fail to see how it solve our problem and I don't feel comfortable to argue with/ask her due to politics and our technical skills (newbie me).

Here are some thoughts on my mind:

Would her key return the correct type for those who seek authentication? If so what would be the "interface" to authenticate?

Would her key be a boolean? In this case I'd need to write an if-else for each authentication method to call the right webservice?

Would her key be a string? I guess it could have the host address so only one webservice would be used and one of its proprieties would be changed on-the-fly before calling its methods (I don't know if it is possible, btw)

Relevant

The webservice were created on the IDE, we'd not change theirs auto-generated code, but as they also are partials we could implement our interfaces in different files.

I didn't find if it's possible to change the entry point of a webreference we generated automatically. The IDE writes methods it has found on that address and it acts as a proxy for the service.

The factory helped us to avoid repetitive and unnecessary code, I don't see it happening with other solutions but the string on a key.


问:
How can I write complex validation and business logic that can be reused in both direct data model changes and pending dialog changes?
I was hoping for some advice:

I need to design a software solution for a medium-sized java / Swing application.

The application will have about 200 use cases requiring complex data validation and business logic.

Typically, this is my usual design:

Create a simple POJO for each use case, with a custom constructor and custom validation and business logic within it's execute method. These Operations implment simple and complex data validation such as required fields, unique names and more complex constraints.

Create a single controller that has a method for every use case. Each method takes custom parameters, constructs and executes it's related operation.

For the sake of simplicity, I won't mention details about Data Model notification or Operation queuing mechanism.

This solution has worked will in the past because it encourages all developers to reuse existing controller methods and validation, however:

The new application will use dialogs extensively for data entry;

These dialogs are expected to implement the same complex data validation and business logic that the controller implements, however the dialogs are not expected to update the data model until the OK button is clicked.

I hate the idea of writing multiple versions of the same complex validation and business logic, due to the maintenance nightmare it invites.

How can I perform complex business logic and validation for both standard data model changes and "pending" dialog changes, given that the dialog doesn't commit it's changes until the OK button is clicked?

The data model may be quite large, so creating an in-memory clone of it and the controller doesn't seem viable.

Does anyone have any suggestions? If so, I'll be forever in your debt.

答:
You have a domain model that encapsulates validation and business logic, and that is no bad thing.

Consider what 'hexagonal' architecture would imply for your design. Specifically, it would recommend that you design an interface to your persistence layer, allowing different persistence mechanisms to be plugged in as adapters.

When performing the business logic for real, use the database adapter.

When running the business logic for a dummy run, to check the validation rules, use a dummy adapter that does not write back to the database, just gives an OK if it gets that far, or drops out with some validation exception if it does not.

Now your domain model can be used in both situations, allowing you to re-use the code.


问:
How can I reinforce that security questions answers should not be the same and how to encrypt?
When my users are creating an account they need to fill and set several security questions pertaining to their account. I am wondering, how can I make sure that the answer the user enters for each security question is not the same as an answer for a different question? What's the proper attribute for it?

Also, for the security question answers, should I encrypt the answers so that whoever is sniffing the network won't see the answers? How? What should I look into or lookup for this approach?

答:
can't you just compare the strings the user enters?

To prevent sniffing, you have to encrypt the answers on the client, pass your server's public key to the client and use it to encrypt them before passing them back to the server. Alternatively, just use SSL comms.


答: Finding very old STL documentation may not be as easy as it sounds.  What I do recall from using STL back in 1996 was &vec[0] was already guaranteed to provide the beginning of the vector's array of data.  I doubt there were any non-array implementations that met the original STL specs.</p>

Title: std::vector Non-Array Implementation?

Body:
I've seen some posts on the StackExchange family of sites talking about std::vector implementations. They all seem to indicate that std::vector is implemented strictly as an array (in practice), and that C++ 2003 dictates contiguity of elements - pretty much closing non-array loopholes.

Now I thought that I had read once of a non-array implementation of std::vector - perhaps this predated the 2003 enforcement of contiguity? (Edit: Herb Sutter makes note of this here) I believe it was something like a series of linked arrays with decreasing or increasing sizes under the hood but I can't remember the details. Does anyone know of std::vector implementations (or perhaps, more broadly, non-STL vector implementations) that use a non-array approach like this?

Edit: I'd like to clarify here that the emphasis is less on strict std::vector implementation for C++ and rather more on 1) historical STL implementations prior to C++ 2003 contiguous elements constraints or possibly even 2) "vector" implementations in other languages - that do not use the usual array-like structure. A VList implementation of a vector might be a potential example and I'm looking for others.


答:
I see some valuable information in the other answers and the comments, but also some misinformation, so I try to give a summary and add some additional things.

Will I have some advantage if I open source the algorithm under copyleft licence (GPL etc.)?

By publishing the source code of an implementation of your algorithm under GPL (I assume that is what you meant), you get the advantage of demonstrating your algorithm works as intended, and everyone can inspect your source code to make sure it does not contain anything "unusual" like severe bugs or malware. Maybe you will get some contributors for further improvements. And since you are the copyright holder, you are still free to publish or sell your implementation to others under a different license.

A different question is if it brings you any advantage to be the first publishing that algorithm. By beeing the first you could try to prevent someone else to get a patent on that algorithm, since your implementation will serve as some kind of proof you are the inventor. But as @Snowman has correctly pointed out in a comment, due to the first-to-file (as opposed to first-to-invent) policy of many european patent regulations, that may actually not work.

From what I know about licensing this should lock people out from using the exactly same code as closed source, but would they be able to "rewrite" the algorithm as closed source?

You lock people from publishing your source code or modifications of it in closed source, not from using it inside a commercial organization. You lock people from publishing it as open or closed source under a different license than GPL. However, you do not lock people from publishing a new "clean-room" implementation of your algorithm under an arbitrary license, which is an implementation made only from your description of the algorithm, without actually looking into the source code.

Since I am from the European Union do I need to look for software patents if I wanted to copyleft it?

Though the laws of many european countries formally forbid patents on pure algorithms, lots of companies have circumvented those laws in the past by declaring specific algorithms as "computer-implemented inventions". AFAIK, European patent offices did not accept as many algorithmic patents as US patent offices in the past, nethertheless they have accepted thousands of patents over the years which can be interpreted as patents on algorithms. If those patents would actually hold in court is a different question, but someone who wants to find out will typically have to the put this on trial, with all related risks. Two of the most popular groups of examples were mentioned in the comments, the patents concerning GIF image compression and the patents concerning MP3 compression / decompression, see here for more examples.

So if you want to reduce the risk of getting sued, before publishing a software containing a specific algorithm, you should probably look if there is someone who is holding a patent on it, even in the EU.


答:
It's repetitive because it's redundant.

The right way to "organize it" is by removing it.

```<code>/**
 * This exception throws under situation1 ...
 */
public class SomeException extends Exception {
</code>```

"This"? I know that Javadoc refers to this class, and not some other one.

"Exception"? I can very well see that this is an Exception.

"Throws"? It goes without saying that exceptions are to be thrown.

```<code>/**
 * Stuff went bad as in [situation1]
 */
public class SomeException extends Exception {
</code>```

That's enough. Cut the obvious out.

```<code>/**
 * @throws SomeException
 *             This exception throws under situation1 ...
 */
private void test() throws SomeException {
    throw new SomeException.Builder("message").build();
}
</code>```

And what's the point of copy-pasting the same stuff here?

I can look up the Javadoc for SomeException. That's exactly what it is for.

Don't repeat the general info about it.

If there is something specific about SomeException in the context of your test method, put it in Javadoc, by all means!

But then it would be a unique piece of information, by definition.

And if it's merely copy-pasta, then leave it.

All it does is littering your code with noise.

I know that many programmers think they serve a noble cause by striving for 100% Javadoc coverage, and they take pride to produce code like:

```<code>/**
 * Sets name
 * @param name - name
 */
public void setName(String name) {
    this.name = name;
}
</code>```

Just stop it. It's pointless.

Okay, it's a bit different if you're writing a library (most of the time that's not the case, and nothing in your question indicates this is what you are doing). But anyhow, only a bit different. Redundancy is a red flag. Valuable information is specific. If the information you provide is not, it's probably not that valuable. So it's better to either leave it out altogether, or make it more contextual.

Title: Way to organize repetitive text in Java

Body:
Some times I have texts that appears in different places, like comments, messages... For example if I have a custom Exception, probably class doc, messages that passes as parameter to its constructor will have the same phrases (here This exception throws under situation1):

```<code>/**
 * This exception throws under situation1 ...
 *
 */
public class SomeException extends Exception {

    public static class Builder{
        String message = "This exception throws under situation1. So ... ";

        public Builder(String message) {
            this.message = this.message + "\r\n" + message;
        }
        public SomeException build(){
            return new SomeException(this);

        }
    }

    private SomeException(String detailMessage) {
        super(detailMessage);
    }

    public SomeException(Builder builder) {
        this(builder.message);
    }
}
</code>```

And also documents of each method that throw exception will have the same phrase:

```<code>/**
 * @throws SomeException
 *             This exception throws under situation1 ...
 */
private void test() throws SomeException {
    throw new SomeException.Builder("message").build();
}
</code>```

If I copy/paste phrase, maintenance of documents will be hard (it needs finding and updating all repeats on each edit).

To solve this, I can use a constant string that its value and its comment are those repetitive terms

```<code> /**
  * exception throws under situation1
  */
public static final String CONSTANT = "exception throws under situation1";
</code>```

and reference to it (and it's comment):

```<code>/**
 * {@link MyClass#CONSTANT}
 */
String message = MyClass.CONSTANT;
</code>```

But how organize constants when are more than one? With respect to this answer and this one, it seems the best way to organize them is using Enum:

```<code>public enum Meta {
    /**
     * exception throws under situation1
     */
    CONSTANT("exception throws under situation1");

    private String text;

    Meta(String text) {
        this.text = text;
    }

    public String getText() {
        return this.text;
    }

}
</code>```

But is there a better way than this? Especially it complicates code.

Body:
It's repetitive because it's redundant.

The right way to "organize it" is by removing it.

/**
 * This exception throws under situation1 ...
 */
public class SomeException extends Exception {

"This"? I know that Javadoc refers to this class, and not some other one.

"Exception"? I can very well see that this is an Exception.

"Throws"? It goes without saying that exceptions are to be thrown.

/**
 * Stuff went bad as in [situation1]
 */
public class SomeException extends Exception {

That's enough. Cut the obvious out.

/**
 * @throws SomeException
 *             This exception throws under situation1 ...
 */
private void test() throws SomeException {
    throw new SomeException.Builder("message").build();
}

And what's the point of copy-pasting the same stuff here?

I can look up the Javadoc for SomeException. That's exactly what it is for.

Don't repeat the general info about it.

If there is something specific about SomeException in the context of your test method, put it in Javadoc, by all means!

But then it would be a unique piece of information, by definition.

And if it's merely copy-pasta, then leave it.

All it does is littering your code with noise.

I know that many programmers think they serve a noble cause by striving for 100% Javadoc coverage, and they take pride to produce code like:

/**
 * Sets name
 * @param name - name
 */
public void setName(String name) {
    this.name = name;
}

Just stop it. It's pointless.

Okay, it's a bit different if you're writing a library (most of the time that's not the case, and nothing in your question indicates this is what you are doing). But anyhow, only a bit different. Redundancy is a red flag. Valuable information is specific. If the information you provide is not, it's probably not that valuable. So it's better to either leave it out altogether, or make it more contextual.


问:
Crypto hash in 'a href'?
It seems to me that it would be pretty useful to be able to indicate an expected crypto hash value in file downloads especially since so many application and data downloads rely on mirrored hosting. This could be done as an attribute to an 'a' tag (I'm not sure if there is a better way). In this scenario the browser would of course check the hash and probably remove the file with a warning if the hash didn't match what was downloaded. As far as I know there is no way to achieve something like this today. Is that correct? If that's true is there a good reason that something like that shouldn't be proposed as an addition to the HTML5 spec. And finally, if it is a reasonable thing to suggest, what is the best way to make such a suggestion?</p>

答:
A feature like this would probably provide little to no actual security benefit, especially when compared to something like SSL or any potential solution to XSS attacks that I'm sure the web standards committees are looking at.

The threat models I can think of where you might try using a hash on a file download are:

1) The website shows a hash and sends you a legitimate file, but someone does a MITM attack and turns the file into malware. If the MITM attacker was competent, they would've also edited the site to show you the correct hash for his malware (or perhaps no hash at all), so trying to show you the hash doesn't prevent this attack.

2) The website shows a hash and deliberately sends you a piece of malware. Presumably, they're showing you the correct hash for the malware, so again the hash doesn't help.

3) The website shows a hash and directs you to another site that hosts the file. Now, if the second site deliberately sends you malware, the hash allows you to detect this. This is the only case I know of where the hash actually does help, and it only helps because it's on a completely different site. Note that this assumes the person putting malware on the second site has no control over the first site and is not MITM'ing you.

P.S. I'd recommend reading the very strongly related question over on Security.SE "What security purpose do hashes of files serve?". The answer there covers a lot of the same ground I just did.

Title: Crypto hash in 'a href'?


答:
You can't "copyleft" an algorithm.  "Copyleft" relies upon copyright protection for its enforceability, but algorithms are not copyrightable, so you can't "copyleft" an algorithm.  In other words, your question might be based on a faulty premise.

Copyright can only be used to protect a specific implementation, not the idea of the algorithm.  So, you could protect a specific implementation of an algorithm using copyright-based licenses (such as a "copyleft" style license), but it would not prevent anyone else from building a different implementation of the same algorithm.  Consequently, there is no way to "copyleft an algorithm".

In particular, the GPL license is built upon the foundation of copyright law.  Copyright law says (roughly): no one can copy your copyrighted content without your permission.  The GPL license says: I give permission to copy the copyrighted content (the code) under certain conditions (the conditions of the "copyleft" license).  So, for things that are copyrightable, this allows bootstrapping the "copyleft" license upon existing copyright law.  But, for things that are not copyrightable, this approach is useless.  Copyright law only protects creative expression, not ideas.  In particular, it doesn't protect algorithms.

Patent law is a different matter.  In some jurisdictions, it might be possible to obtain a patent for an algorithm.  This will depend heavily upon the legal jurisdiction and possibly on the specifics of your situation.  Generally speaking, publishing your algorithm might help establish prior art that prevents others from patenting the algorithm, but the details of this are tricky, and best to consult a lawyer.  In general, if you want solid advice on anything relating to algorithm patents, I suggest you contact an IP lawyer, as this is too broad to answer in general without knowledge of that information.


问:
What is Banana split and fusion in functional programming?
These terms got mentioned in my university course. Quick googling pointed me to some university papers, but I am looking for a simple explanation.</p>

答:
Although jozefg provided an answer, I am not sure if it answered the question. The "fusion law" is explained in the following paper:

A tutorial on the universality and
  expressiveness of fold, GRAHAM HUTTON, 1999

Basically it says that under some conditions you can combine ("fuse") the composition of a function and fold into a single fold, so basically

h · fold g w = fold f v

The conditions for this equality are

h w = v

  h (g x y) = f x (h y)

The "banana split" or "banana split law" is from the article

Functional Programming with Bananas, Lenses,
  Envelopes and Barbed Wire, Erik Meijer  Maarten Fokkinga, Ross Paterson, 1991

Unfortunately the article is very hard to decipher as it uses the Bird–Meertens formalism
so I could not make head or tail of it. As far as I understood the "banana split law" it says that if you have 2 folds operating on the same argument, they can be merged into a single fold.


问:
pthread versus boost::thread - need to set the thread priority on an ubuntu box
I wrote a class that basically executes a numerical analysis code in a thread using boost::thread. Now I need to specify the thread priority, since we are running a system with near real-time operations and don't want the OS (ubuntu) to assign a high priority to the thread.

I found that with c++11 you can actually change the priority of a thread (see here). I'm have not found such a thing for boost. Should I change my code to use the standard library option?

It used to be (and I think is valid still) that the boost libraries offered cutting edge stuff. Why in this case is not so? or am I missing something?

答:
Boost may be cutting edge when it is first released.

But it (boost) should also be considered a testing ground for new ideas. The thread ideas introduced in boost were a good idea at the time and the lessons learned helped the standardization committee when they added threads to the standard.

But now that threads are part of the standard you should be using the threads from the std and start migrating your code to use the standard library.


问:
How can Guard Statements and Small Functions coexist?
By Guard Statements I mean something similar to the first part of the function:

```<code>def doSomething(String something)
{
    // Guard Statement
    if(!something)
    {
        return false
    }

    // more stuff
}
</code>```

Say you might have several parameters, maybe you need to log that the method was called with a null parameter, or maybe throw a specific exception.

Clarification: I've read that both Guard Statements and smaller functions are good design choices, but it seems like if you include Guard Statements your functions won't be small.

By smaller functions I'm referencing Robert C. Martin's smaller function suggestions in Clean Code.

I guess what I'm asking is it worth it to include Guard Statements in a function even though it makes the function longer. I understand the answer could very based on if it's a public API or private function, for this purpose it's not a private function but a service in a MVC application, so I guess that makes it public?

答:
A few options:

Don't use guards. Seriously, if a null parameter is going to blow up, just let it blow up. Also, while it's possible for some naughty programmer to call internal functions/services directly with bad data, you maybe don't need to guard everything.

Single line conditionals. This is one place where a single like if(string.IsNullOrWhitespace(something)){ return; } is good. Keeps cruft out of the way.

Sane defaults. something = something ?? string.Empty; (or similar) is much shorter, and in addition, it makes your function less fragile to bad input. Some people hate this though.

Helpers. In C#, you can use expression trees to do something like Guard.Range(()=>x,1,10); which will throw while being more concise and more DRY.

Don't care. "Small functions" can mean "less going on" in addition to "taking less space on the screen". The former is more important than the latter. While big space eating guards are annoying, they're easy to read. If you can get over that annoyance, then you can focus on what really matters - keeping your code easy to maintain by keeping the scope (not size) of functions small.


问:
Background service or handle all at once?
Let's imagine a scenario: When a user posts a message on a blog post, the original author will be notified via a push notification and email.

Should these messages be sent when the user sends the message and let him have a little longer loading time, or should I use a background service to watch the database and do the job without the need of an user? In the case of a background service I would need IAAS instead of PAAS.

答: It sounds like you've set up a false dilemma between slow website responsiveness and fast email notification, but it doesn't have to be that way if you call the background service asynchronously instead of polling the database.</p>


答:
This is dependent on your product requirements and your service expectations.

Generally for blocking services that are not required for a page to be created, I would recommend running a background service.

This is in case the push notification or email service is not able to keep up with the load.

If the service were slow to send the messages then the page that initiated the messages will hang.

This is why (I believe) most applications use a queue to process actions like notifications and emails.

It is relatively simple to setup a queue and then use producers/consumers to manage the actions.

Title: Background service or handle all at once?

Body:
Let's imagine a scenario: When a user posts a message on a blog post, the original author will be notified via a push notification and email.

Should these messages be sent when the user sends the message and let him have a little longer loading time, or should I use a background service to watch the database and do the job without the need of an user? In the case of a background service I would need IAAS instead of PAAS.


问:
Looking for a way to interpolate a base URL that won't conflict with Underscore template code
At my workplace, we have dev and production environments, and a separate server that serves static files for each environment. In my code, I make references to the URL of this static file server. Manually switching the references between servers would be a large chore, so I'm trying to incorporate a gulp task into my automation strategy, but I'm running into an issue.

Some of my code is already using Underscore templates, so using a templating library with gulp creates ambiguity on which code should be compiled through gulp and which code should be ignored.

In our environment, we refer to servers that serve static files as "image servers".

For example, I have a script tag that looks like this:

```<code><script src="<%= image_server_url %>/scripts/iep-alert/alert.js"></script>
</code>```

All I need is simple string interpolation in this case. However, I get errors from other template code in the project that certain variables are not defined because the context in which the gulp template task is operating with is different from the context that I pass the template when it is referenced within a browser.

So, what's the best (or sufficient) way to dynamically set the URL to my static file server throughout my project? Is it with gulp, am I missing a plugin I should be using? If so, how do I tell gulp to ignore certain templates?

I have asked a similar, more code-centric version of this question on StackOverflow.

答:
I ended up using the gulp-preprocess plugin. My code looks like this now and it's working well so far.</p>

```<code><script src="<!-- @echo IMAGE_SERVER_URL -->/scripts/iep-alert/alert.js"></script>
</code>```

Body:
I ended up using the gulp-preprocess plugin. My code looks like this now and it's working well so far.

<script src="<!-- @echo IMAGE_SERVER_URL -->/scripts/iep-alert/alert.js"></script>


问:
NoSQL or MySQL?
I'm developing an app that requires to save data that is not consistent across all rows. These database entries represent different kind of sport activities. Let's take an example: In football the final result is an important field. However, in cycling there's no such field. So it wouldn't be a good idea to create a table that has a score column, would it? This kind of data would be easy to store in a NoSQL database.

All these have some things in common, though: date, time, duration and location, at least.

The app also has functionality that would greatly benefit from typical relational database. Users table, messages etc.

How should I implement a database for such an application? All data is relational in a way that connects everything to a specific user. However, not all data can be organized in a traditional row/column based database.

Should I use MySQL, and for these activities have a data field that contains the relevant data in JSON? What are my options?

Also keep in mind that the database might be holding millions of entries.

答:
Take a look at PostgreSQL. You can store JSON in it in a type-safe way. It supports indexing so you can combine relational data with JSON documents pretty well. It is also fast, there are plenty of benchmarks.

Also, if you never used NoSQL before, please read this: Why You Should Never Use MongoDB (don't mind the title, article is pretty constructive)

As for MySQL, I wouldn't suggest my worst enemy to use it. It has so much bugs it's not even funny. It pretty much doesn't work in a cluster (due to bugs some features become unusable and there are 1001 "workarounds" which make it unmaintainable), for one thing, so it's not a scalable solution.

So, choose between PostgreSQL and NoSQL at least. I definitely would recommend PostgreSQL.

EDIT:

I decided to mention some of MySQL bugs I happened to deal with to make it clear it is not just hate speech:

Incomplete XA support ("For XA START, the JOIN and RESUME clauses are not supported. For XA END the SUSPEND [FOR MIGRATE] clause is not supported.") + bug in official Java driver (this bug may be in MySQL itself, I'm not sure) causes (NUM_CORES*100)% CPU load on DB server, in which case you have to restart it.

Workaround: merging all databases which participate in distributed transactions into one or not using distributed transactions. I participated in merging just 2 DBs, and that was brutal.

Deadlocks on concurrent inserts. Happens when you insert 4 values in 2 transactions, 2 each, in 2 gaps into some indexed field.

Workaround: serialization of inserts. It means that practically you can only insert with one thread, hence no scalability for your application.

Triggers and replication don't go together. There are few bugs, like Bug #45677 related to AUTO_INCREMENT

Workaround: not using triggers or not using replication. There are actually less brutal workarounds for each bug, but in the end of the day it's just what I said: choose either triggers or replication, not both.

Those are not even half of my list, but I want to emphasize that MySQL is bad when you need more than a single database with no replication. And it is especially important since scalability is one of the strongest arguments for using NoSQL solutions, and you mentioned you might have a lot of data.

Title: NoSQL or MySQL?


问:
When should I use event-based programming?
I have been passing callbacks or just triggering the functions from other function in my programs to make things happen once tasks complete. When something finishes, I trigger the function directly:

var ground = 'clean';

function shovelSnow(){
    console.log("Cleaning Snow");
    ground = 'clean';
}

function makeItSnow(){
    console.log("It's snowing");
    ground = 'snowy';
    shovelSnow();
}
```

<p>But I've read about many different strategies in programming, and one that I understand to be powerful, but have not yet practiced, is event-based (I think a method I read about was called <em>"pub-sub"</em>):</p>

<pre class="lang-js prettyprint-override"><code>var ground = 'clean';

function shovelSnow(){
    console.log("Cleaning Snow");
    ground = 'clean';
}

function makeItSnow(){
    console.log("It's snowing");
    ground = 'snowy';
    $(document).trigger('snow');
}

$(document).bind('snow', shovelSnow);
</code>```

I'd like to understand the objective strengths and weaknesses of event-based programming, vs just calling all of your functions from within other functions. In which programming situations does event-based programming make sense to use?

答:
A simple analogy I wanted to add that helped me:

Think of the components (or objects) of your application as a big group of Facebook friends.

When one of your friends wants to tell you something, they can either call you directly or post it to their Facebook wall. When they post it to their Facebook, then anyone could see it and react to it, but a lot of people don't. Sometimes it's something important that people will likely need to react to it, like "We're having a baby!" or "So-and-so band is doing a surprise concert at the Drunkin' Clam bar!". In the last case, then the rest of the friends will likely need to react to it, especially if they are interested in that band.

If your friend wants to keep a secret between you and them, they probably wouldn't post it to their Facebook wall, they would call you directly and tell you. Picture a scenario where you tell a girl you like that you would like to meet her at a restaurant for a date. Instead of calling her directly and asking her, you post it to your Facebook wall for all your friends to see. This works, but if you have a jealous ex, then she could see that and appear at the restaurant to ruin your day.

When deciding whether or not to build in event listeners for implementing something, think about this analogy. Does this component need to put their business out there for anyone to see? Or do they need to call someone directly? Things can get messy pretty easily so be careful.


问:
Should I commit regularly in new projects?
TL:DR; Shall I start comitting regularly small pieces of code in new projects? Even if I'm start from scratch and don't have any experience in what I'm using (framework, programming language, w/e)?

Whenever I've learned something new for myself I did not have commited anything in an early stage. For several reason: Basically beacuse I've no idea what I'm doing and don't know any best practices yet etc. So I just start and try things and rewrite them for like 100 times (at least it always feels like that).

Yet I've got a new job and I'm starting a new complete project in AngularJS with Spring Boot backend. I'm mainly working on the frontend. I'm pretty new to Angular and JS in general. At this moment I'm the only one commiting to the project. The initial commit was like yo jhipster (this set's up a complete app skeleton that is ready to run) and some custom database mappings.

My first commit was like

```<code>Implemented controller X

Sorry for large comment I've just started with Angular. [...]
</code>```

Since I don't have the time to learn things in a sample project and there is a very short deadline for a first presentation I feel like it's better to have some bigger commits. I'll try to keep commits at least related to one topic. Like

```<code>Integrated template X into project

Replaced this with that and [...]
</code>```

Anyway - this commit will be huge. Unlikely that someone will check the whole diff.

I'm working on a seperate local branch themeIntegration. I'll do there smaller commits that are actually just to have some commits where I can fallback if something goes absolutely wrong or I just recognize I've did probably something wrong I'll change a lot now. I'll squash merge it into my develop branch later.

答:
You should commit often.

But @durron597! I'm a beginner programmer! I don't trust my commits!

This is why you are committing on a separate branch!

You can even have many branches that you're committing to for your own use, for different fits and starts and experiments and whatnot.

Don't worry about big fancy commit messages. The only commit messages that really matter are the ones that occur when you finally attempt to merge your changes into trunk. At that time, go through your whole list of smaller commit messages and aggregate them into something someone else will read. In the meantime, your commit messages are only for you, and having a big commit history can only help you to track down problems if you make a mistake.


问:
Advantage in being the first to copyleft a new algorithm?
Say I have created a new (DSP) algorithm. Will I have some advantage if I open source the algorithm under copyleft licence (GPL etc.)? From what I know about licensing this should lock people out from using the exactly same code as closed source, but would they be able to "rewrite" the algorithm as closed source?

Note: I don't really know if the algorithm is new but it has not been released as open source yet. Since I am from the European Union do I need to look for software patents if I wanted to copyleft it?

答:
Copyleft doesn't have anything to do with copyright or patent protection.  It doesn't provide any protection to you, the copyright holder, that you wouldn't otherwise already have.

It has everything to do with distribution, however.  Copyleft protects users of your code by requiring you and anyone else who uses their code to distribute the entire source code of their collective work and any changes they make to it.  It doesn't have anything to say about copyright or patent protections, other than to give your user certain specific rights that they might not otherwise have, such as the freedom to reverse-engineer DRM in GPL3.


问:
How to display/clarify the licence for code in a blog
Let's say I have a blog available under one of the Creative Commons licences.
Such type of licence would be displayed at the bottom of each page with a link
to the actual licence, etc..

However, apparently, the Creative Commons licences are not really suitable for
software nor for distribution of source code, so, what about any code
(e.g. snippet/fragment or even full programs) that can be part of a blog post?

If I would choose to release this code as GPLv3, would it be acceptable and
clear enough to say, at the bottom of the page, something like: "This website
by Mr. Foo is released under a Creative Commons blah blah, except for any source code in the form of code snippets/fragments/samples, which are released
under GPLv3"?

Or are there better/different/more formal ways to clarify such
situation?

答:
Unless you want to forbid it, there is no harm in licensing your code under a Creative Commons license. This would, for example, allow users to include the code in Stack Exchange posts (e.g., when giving an answer on Stack Overflow).

In addition, you may license all code snippets under one or more different (software) licenses, like the GPLv3.

Users that make use of your code snippets could then choose which single license (of those that you’ve granted) they want to follow.

How you communicate/show which licenses are available is up to you. It mostly depends on how eye-catching you want to state it. For example, you could add the info

on the "About" page of your site, and/or

in the footer of each page, and/or

underneath each code snippet, and/or

in the markup (making it machine-readable) using RDFa.


问:
Status Bar Timetracking Design
I'm currently developing an application in ASP.NET using SQL as the backend database. In my header, I have a status bar that displays the current status of the user and a timer that shows how long they've been labeled as that status.

Using an update panel with a timer to refresh the data straight from the database (thus making 1 query/update each second) doesn't seem like the best way to go about this. I would assume you'd want to query the user's "start time" for their status and use a javascript timer to keep track from there, but my problem is this; how would I integrate this method while also making sure that the status itself is updated when it's changed in the database?

答:
SQL Server has a feature called query notification. The application submits a query and some parameters.  This is know as a subscription.  If data changes so the result of this query would be different with the new data, the notification fires.

From BoL:

Query notification subscriptions must be created from a database access interface. Transact-SQL does not provide a mechanism for creating query notification subscriptions.

That link has several options for creating a notification. There are restrictions on what the query may look like.

Query Notifications are processed through Service Broker (SB), so that has to be configured on the instance. When the notification fires a message is inserted into the stated queue.  These queues are no different than other SB queues so all the ACID and authorisation rules apply.

The application listens on this queue and reacts when the message arrives.  The application can poll or have a thread sitting blocked, waiting for a message. When the notification is sent the subscription is dropped. The application must submit a new subscription to receive further notification.  This may cause race conditions, or allow intervening data changes to be missed.

Be careful, if you have many active clients and frequently changing data as it can add a significant load to the server.

Title: Status Bar Timetracking Design