答:
What you should test

General, ordinary case. Just to be sure it works. This is the simplest case:

A name which contains only letters and has its length between 4 and 14.

A name which contains only letters and has its length between 1 and 4.

A name which contains only letters and has its length between 14 and the maximum authorized length.

A name which contains only letters and has exactly 4 characters.

A name which contains only letters and has exactly 14 characters.

A name which contains letters and something else and has its length between 4 and 14.

Edge cases

An empty string.

A null (if your language makes a difference between an empty string and null).

A bunch of unicode strings with different normalization and different characters. Those tests should match your documentation explaining what do you mean by "letters only". Is щ a letter? Is ᴴ a letter? What about Ẁ and its two possible unicode representations (combined and normalized)?

What you shouldn't test

You shouldn't test repetitive things. If you tested both "test" and "Travis", testing also "John" brings nothing useful, since it contains only lowercase and uppercase letters, just like "Travis", and is 4-characters long, just like "test".

In the same way, %, Sam1 are redundant.

As for random strings, you shouldn't use them, since if your code is not working as expected, they might in some cases give you random results: sometimes the test will pass, the next time it will fail for the exact same code.

Title: How do I test my validation without being too much perfectionist, yet to leave most part of logic tested?

Body:
For example I would like to validate that name is letters only and is between 4 and 14 letters length. I have the following code in model:

```<code>validates: name, :format => { :with => /^[a-zA-Z]+$/,
                              :message => 'Name should be letters only. },
                 :length => { :minimum => 4, :maximum => 14 }
</code>```

So it clearly lets me do what I want.

But as for unit tests, I have a bit too much perfectionism so I set something like

```<code>invalid_names = ['1234',
                 'qwe',
                 '1%#$#$',
                 'Sam1',
                 '%',
                 random_string(15)] #I also have a test method to create random string with parametrized length

valid_names = %w['test',
                 'Travis',
                 'John',
                 random_string(5),
                 random_string(14),
                 random_string(4)]
</code>```

and test each of them in a loop with asserts, like

```<code>invalid_names.each do |name|
    user = User.new(:name => name)
    user.save
    assert user.errors[:name].any?, "#{name} is valid."
end
</code>```

So it definitely works great. But it is too verbose (because of valid/invalid names arrays, and added random_string method), also I can't be sure my test actually tests all symbols and their combinations possible and all lengths and stuff, even though I am definitely sure it works as expected.

So what is acceptable way to test my validation without being too much perfectionist, yet to leave most part of logic tested?

Am I just set in a mind trick of trying to write a perfect code just to write a perfect code and forgetting about main finish goal: working product?


问:
How do I test my validation without being too much perfectionist, yet to leave most part of logic tested?
For example I would like to validate that name is letters only and is between 4 and 14 letters length. I have the following code in model:

```<code>validates: name, :format => { :with => /^[a-zA-Z]+$/,
                              :message => 'Name should be letters only. },
                 :length => { :minimum => 4, :maximum => 14 }
</code>```

So it clearly lets me do what I want.

But as for unit tests, I have a bit too much perfectionism so I set something like

```<code>invalid_names = ['1234',
                 'qwe',
                 '1%#$#$',
                 'Sam1',
                 '%',
                 random_string(15)] #I also have a test method to create random string with parametrized length

valid_names = %w['test',
                 'Travis',
                 'John',
                 random_string(5),
                 random_string(14),
                 random_string(4)]
</code>```

and test each of them in a loop with asserts, like

```<code>invalid_names.each do |name|
    user = User.new(:name => name)
    user.save
    assert user.errors[:name].any?, "#{name} is valid."
end
</code>```

So it definitely works great. But it is too verbose (because of valid/invalid names arrays, and added random_string method), also I can't be sure my test actually tests all symbols and their combinations possible and all lengths and stuff, even though I am definitely sure it works as expected.

So what is acceptable way to test my validation without being too much perfectionist, yet to leave most part of logic tested?

Am I just set in a mind trick of trying to write a perfect code just to write a perfect code and forgetting about main finish goal: working product?

答:
So what is acceptable way to test my validation without being too much perfectionist, yet to leave most part of logic tested?

That depends. Different people consider different things to be "enough testing". In some cases, some types of tests are imposed by the nature or boundaries of the project itself.

Examples:

We had one project where we had to offer clients a performance guarantee (min. X messages processed per minute). This was tested throughout the development, in nightly tests. Performance bottlenecks were identified and we designed/implemented around them.

We had one project that did XML parsing and had to provide security guarantees (won't crash on invalid inputs). We ended up implementing a fuzzing library (that took each API, corrupted one of it's parameters in a predefined way and called the API in a loop, for each corruption).

Normally, I want to see that the default trivial cases are implemented, corner cases are implemented, generic cases are implemented and maybe a negative case or two (check that correct data is in the generated exception, when the inputs are wrong). In my current project though, such a level of testing is not realistic.

We also had a project where (by agreement) solving a defect also implied adding a new unit test. When running the test suite, full regression would run automatically (i.e. we were able to guarantee that we didn't re-create any of the old issues found in the application).

Am I just set in a mind trick of trying to write a perfect code just to write a perfect code and forgetting about main finish goal: working product?

Not from what I could tell.

Edit: a few other points:

If you need randomness in your tests, make sure it is repeatable (for example, initialize your random number generator with a constant seed)

At the very least, test for the most common case;

Adding unit tests for most corner cases is beneficial when the code changes (in your code, that would be lengths 4 and 14; not sure about the formats). When updating an algorithm, we tend to think (naturally) at the general case; These tests check things that you (the developer) tend not to think about at every edit.

ContentLicense: CC BY-SA 3.0


答:
Your code should meet a use case and it should do it in a way that is relative to the risk created by missing something. Is it illegal in the context of your application to allow numbers/characters in a name (Maybe this is a database for the Names with Letters Only Society)? Then test it as much as possible.

Not that you want to invite someone to micro-manage you, but take into consideration how much of your time the people paying for this software want you to spend. They may not share your level perfection and won't want to pay for it either.


问:
Visiting points on a number line while minimizing a cost not related to distance
I need some help on this ACM ICPC problem. My current idea is to model this as a shortest path problem, which is described under the problem statement.

Problem

There are N = 1000 nuclear waste containers located along a 1-D number line at distinct positions from -500,000 to 500,000, except x=0. A person is tasked with collecting all the waste bins. Each second that a waste container isn't collected, it emits 1 unit of radiation. The person starts at x = 0 and can move 1 unit every second, and collecting the waste takes a negligible amount of time. We want to find the minimum amount of radiation released while collecting all of the containers.

Sample Input:

4 Containers located at [-12, -2, 3, 7].

The best order to collect these containers is [-2, 3, 7, -12], for a minimum emitting of 50 units. Explanation: the person goes to -2 in 2 seconds and during that time 2 units of radiation are emitted. He then goes to 3 (distance: 5) so that barrel has released 2 + 5 = 7 units of radiation. He takes 4 more seconds to get to x = 7 where that barrel has emitted 2 + 5 + 4 = 11 units. He takes 19 seconds to get to x = -12 where that barrel has emitted 2 + 5 + 4 + 19 = 30 units. 2 + 7 + 11 + 30 = 50, which is the answer.

Notes

There is an obvious O(N!) solution. However, I've explored greedy methods such as moving to the closest one, or moving to the closest cluster but those haven't worked.

I've thought about this problem for quite a while, and have kind of modeled it as a graph search problem:

We insert 0 in as a baseline position (This will be the initial state)

Then, we sort the positions from least to greatest.

We then do a BFS/PFS, where the state consists of

Two integers l and r that represent a contiguous range in the sorted position array that we have visited already

An integer loc that tells us whether we're on the left or right endpoint of the range

An integer time that tells us the elapsed time

An integer 'cost' that tells us the total cost so far (based on nodes we've visited)

From each state we can move to [l - 1, r] and [l, r + 1], tweaking the other 3 integers accordingly

Final state is [0, N], checking both ending positions.

However, it seems that [L, R, loc] does not uniquely define a state, and we have to store L, R, loc, and time, while minimizing cost at each of these. This leads to an exponential algorithm, which is still way too slow for any good.

Can anyone help me expand on my idea or push my into the right direction?

Edit: Maybe this can be modeled as a dynamic programming optimization problem? Thinking about it, it has the same issues as the graph search solution - just because the current cost is low doesn't mean it is the optimal answer for that sub problem, since the time also affects the answer greatly.

Greedy doesn't work: I have a greedy selection algorithm that estimates the cost of moving to a certain place (e.g. if we move right, we double the distances to the left barrels and such).

Could you do a Priority-first search, with a heuristic? The heuristic could combine the cost of the current trip with the amount of time elapsed.

答:
Shortest Distance

I wrote a Java application yesterday to solve the problem.  The problem is basically a shortest distance problem, as SRJ said in his comment.  The radiation just shows that you can accumulate a value along with the shortest distance.

Basically, here's what I did.

Put the container numbers in a List<Integer>

While the List contains elements;

Find the element(s) that are closest

If there's one element, walk there and remove the element.

If there's two elements, copy the path and walk to both elements

Find the path with the smallest radiation value.

Here's some output from the application

```<code>10 containers are located at [-90, -75, -47, -9, 9, 26, 48, 50, 64, 79].

You walk to position -9 and pick up the container.  The total radiation emitted is 90 units.
You walk to position 9 and pick up the container.  The total radiation emitted is 252 units.
You walk to position 26 and pick up the container.  The total radiation emitted is 388 units.
You walk to position 48 and pick up the container.  The total radiation emitted is 542 units.
You walk to position 50 and pick up the container.  The total radiation emitted is 554 units.
You walk to position 64 and pick up the container.  The total radiation emitted is 624 units.
You walk to position 79 and pick up the container.  The total radiation emitted is 684 units.
You walk to position -47 and pick up the container.  The total radiation emitted is 1,062 units.
You walk to position -75 and pick up the container.  The total radiation emitted is 1,118 units.
You walk to position -90 and pick up the container.  The total radiation emitted is 1,133 units.
</code>```

I didn't optimize the algorithm in any way.  I didn't even notice that the input list of numbers was sorted.  (I'm a doofus.)

When I ran my code with the maximum values, 1,000 containers and a range from -500,000 to 500,000, my code took 3 seconds to execute.  Most of that time was writing the 1,000 print lines to the console.

I'm not a big O person, but I think my brute force walking the shortest path algorithm is O(N squared), not O(N!).

If I took advantage of the fact that the input numbers are sorted, so that I only had to check the two numbers on either side of where I'm presently located, I could get the application down close to O(N).  I only have to check 2 numbers because I'm removing the elements from the List as I get to them.

You used different algorithms, like the greedy algorithm, to find an approximate solution.

If my program had taken 3 hours to run instead of 3 seconds, then you'd have a choice to make.

Is the good enough solution good enough?

In other words, am I willing to trade processing speed for a good enough answer?

If a good enough answer is good enough, then you use approximation algorithms.

If you want the perfect answer, you have to walk all the shortest paths.  There is no shortcut.

If anyone wants me to post my code, I will.  I'm sure there are still bugs, as I wanted to see if I could implement a shortest walk algorithm.

Body:
Shortest Distance

I wrote a Java application yesterday to solve the problem.  The problem is basically a shortest distance problem, as SRJ said in his comment.  The radiation just shows that you can accumulate a value along with the shortest distance.

Basically, here's what I did.

Put the container numbers in a List<Integer>

While the List contains elements;

Find the element(s) that are closest

If there's one element, walk there and remove the element.

If there's two elements, copy the path and walk to both elements

Find the path with the smallest radiation value.

Here's some output from the application

10 containers are located at [-90, -75, -47, -9, 9, 26, 48, 50, 64, 79].

You walk to position -9 and pick up the container.  The total radiation emitted is 90 units.
You walk to position 9 and pick up the container.  The total radiation emitted is 252 units.
You walk to position 26 and pick up the container.  The total radiation emitted is 388 units.
You walk to position 48 and pick up the container.  The total radiation emitted is 542 units.
You walk to position 50 and pick up the container.  The total radiation emitted is 554 units.
You walk to position 64 and pick up the container.  The total radiation emitted is 624 units.
You walk to position 79 and pick up the container.  The total radiation emitted is 684 units.
You walk to position -47 and pick up the container.  The total radiation emitted is 1,062 units.
You walk to position -75 and pick up the container.  The total radiation emitted is 1,118 units.
You walk to position -90 and pick up the container.  The total radiation emitted is 1,133 units.

I didn't optimize the algorithm in any way.  I didn't even notice that the input list of numbers was sorted.  (I'm a doofus.)

When I ran my code with the maximum values, 1,000 containers and a range from -500,000 to 500,000, my code took 3 seconds to execute.  Most of that time was writing the 1,000 print lines to the console.

I'm not a big O person, but I think my brute force walking the shortest path algorithm is O(N squared), not O(N!).

If I took advantage of the fact that the input numbers are sorted, so that I only had to check the two numbers on either side of where I'm presently located, I could get the application down close to O(N).  I only have to check 2 numbers because I'm removing the elements from the List as I get to them.

You used different algorithms, like the greedy algorithm, to find an approximate solution.

If my program had taken 3 hours to run instead of 3 seconds, then you'd have a choice to make.

Is the good enough solution good enough?

In other words, am I willing to trade processing speed for a good enough answer?

If a good enough answer is good enough, then you use approximation algorithms.

If you want the perfect answer, you have to walk all the shortest paths.  There is no shortcut.

If anyone wants me to post my code, I will.  I'm sure there are still bugs, as I wanted to see if I could implement a shortest walk algorithm.


问:
I want to publish an android app, but I'm afraid of software patents
I wrote an application that helps you to save energy. Actually it is very simple. I check the current location of the phone and I make some changes to the configuration like "sound off, dark display, wifi off...", depending on the location of the user. Sony just released a new phone including one of my apps features (actually they have an extra entry in the options menue for this). I have no idea whether there is a patent for this function.

Can I even release this app without risking to be sued some day?

I'm very confused about the whole "patent" situation.

I'm about 20 years old and I can't even write a simple app, without investing lots of money for a lawyer.

Edit: I don't ask for legal advice. I wanted to receive an overview about how developers see or handle the whole situation.

答:
(It is customary to preface legal advice on the internet with a disclaimer that one is not a lawyer and you should consult a professional. So here it is: I am not a lawyer. You should consult a real lawyer to be sure.)

Anybody can bring suit against anyone else, for pretty much anything. Winning such a lawsuit eventually is a different matter, but where the litigant has much, much more money than you, in practice they can force you to negotiate a settlement because you can't afford the cost of keeping your legal defense going. (Yes, this is blatantly unfair, which is why tort reform is such a big issue nowadays.)

As for patents: yes, there can be patents on the feature you have built, and if you infringed them, you could be sued. Since large companies usually patent features left and right before introducing a new gadget, it is probable that there are such patents. Unfortunately, searching for patents in order to determine whether something infringes or not is very difficult and time-consuming - neither the patent office nor honest private inventors are usually able to say with any certainty whether a proposed new product infringes. In fact, an inventor has an incentive not to search too hard, since having had knowledge of related patents can be interpreted as willful infringement and cause even higher damages. (This is also a very broken area of law, and unsurprisingly, patent reform is also a hot issue.)

In practice, as long as you publish one little app and make a modest income from it, it is possible in principle, but not exactly to be expected that you will be sued. If you ever make it really big, then the risk goes up dramatically, as any trade publication will show you.


问:
What is the difference of the add and offer methods of Java's PriorityQueue?
In java.util.PriorityQueue we have the methods add(E e) and offer(E e). Both methods are documented as:

Inserts the specified element into this priority queue.

What are the differences between these two methods?

答:
The difference is that offer() will return false if it fails to insert the element on a size restricted Queue, whereas add() will throw an IllegalStateException.

You should use offer() when failure to insert an element would be normal, and add() when failure would be an exceptional occurrence (that needs to be handled).


答:
To find out the difference, one needs to follow PriorityQueue API javadocs which in turn have "Specified By" sections that refer reader to respective methods in Queue interface:

Queue.add

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available...

  Returns: true (as specified by Collection.add(E))

  Throws: IllegalStateException - if the element cannot be added at this time due to capacity restrictions...

Queue.offer

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception...

  Returns: true if the element was added to this queue, else false...

Both methods are present because these are required to be implemented by declared interface.

Note that since PriorityQueue is unbounded (as stated in javadocs: "unbounded priority queue based on a priority heap..."), preference of API designers expressed above do not apply. This means it is left at programmer discretion to pick the method that better suits their needs in a specific usage context.

Title: What is the difference of the add and offer methods of Java's PriorityQueue?

Body:
In java.util.PriorityQueue we have the methods add(E e) and offer(E e). Both methods are documented as:

Inserts the specified element into this priority queue.

What are the differences between these two methods?


答:
I am not a lawyer.  There's a special word for people who take anonymous legal advice from the Internet - "fool".

Do a risk analysis -

a) you don't write the software.

outcome: Nothing.

b) you do write the software.

outcome #1: Sony doesn't notice and/or doesn't care.  This might be a case of the "shallow pockets" defense - in their eyes you're not worth the effort to sue.

outcome #2: Sony sees your work and is impressed by it.  They may offer to purchase it from you.  (That might be cheaper than suing you then coding it up themselves)

outcome #3: Sony sees your work as an infringement that they must prevent.  Step #1 (in the US, not sure about other countries) would be to send you a "cease & desist" letter.  It's cheaper than suing, and chances are it's all they'd need to get you to stop.

Outcomes #1 and #2 are not harmful to you.  Outcome #3 would probably mean you'd simply have to stop selling your software.  You have to decide how likely #3 is and whether or not you can afford to stop.

My recommendation is to go ahead and write the software.  You have much to gain (experience, reputation, possibly money) and little to lose.  It's difficult to get the attention of large companies when you actually want it, so I'd expect outcome #1.

Good luck!

Title: I want to publish an android app, but I'm afraid of software patents

Body:
I wrote an application that helps you to save energy. Actually it is very simple. I check the current location of the phone and I make some changes to the configuration like "sound off, dark display, wifi off...", depending on the location of the user. Sony just released a new phone including one of my apps features (actually they have an extra entry in the options menue for this). I have no idea whether there is a patent for this function.

Can I even release this app without risking to be sued some day?

I'm very confused about the whole "patent" situation.

I'm about 20 years old and I can't even write a simple app, without investing lots of money for a lawyer.

Edit: I don't ask for legal advice. I wanted to receive an overview about how developers see or handle the whole situation.


问:
Would Python be too slow for client-side use in Browsers?
I've heard the statement that Python would be too slow to be of any use in browsers.

I reckon Javascript is only superior in this aspect because of companies like Google who need it fast (and made it fast) because they need it to survive, but I could be wrong.

Are there any differences in how Python and Javascript are designed that have an impact on how they (would) perform in browsers?

Since as of now there isn't a client side Python implementation, my question comes from the statement someone made, so maybe it has something to do with the languages itself (although I don’t believe that).

答:
I think Python has its own virtual machine.  I don't have a lot of experience with Python, but I don't see any reason why it wouldn't perform as well as a non-optimized JavaScript engine.

Some random thoughts:

(1) You could probably run Python locally through a Java applet using Jython.  The hard part I see here is that applets are very restrictive, so you might need to modify Jython to fit within the access restrictions.  For instance, if it writes to a log file, you may need to remove the logging code.  An applet doesn't need to be noticeably visible.

(2) Someone could build a Python-to-JavaScript "compiler"/converter.  This would be a lot of work.


答:
I don't think Python would be too slow at all. There's nothing about the language that prevents it running fast enough to at least match JavaScript. It can be compiled to JavaScript, so, if nothing else, you could include a compiler in the browser and only potentially increase page load times.

UPDATE: Please see the comments below discussing why compiling Python to JS would be considerably more costly than implied here.

The problem is trying to convince the browser vendors and W3C to first choose Python, over Ruby or any other nice scripting language, then define a standardised subset, as they can not allow system calls and so on, and then implement it well, all while supporting JavaScript still. That's not going to happen, but if it did, I doubt that speed would turn out to be a serious issue.

Title: Would Python be too slow for client-side use in Browsers?

Body:
I've heard the statement that Python would be too slow to be of any use in browsers.

I reckon Javascript is only superior in this aspect because of companies like Google who need it fast (and made it fast) because they need it to survive, but I could be wrong.

Are there any differences in how Python and Javascript are designed that have an impact on how they (would) perform in browsers?

Since as of now there isn't a client side Python implementation, my question comes from the statement someone made, so maybe it has something to do with the languages itself (although I don’t believe that).


答:
In the elder times of the web, when java applets where the <s>main</s> only form of client side interactive content people realized that there needed to be a way to get forms on a web page to be able to interact with the applets on the web page.

From this, a scripting language to link the java applet to the web page was created with the name... javascript.

One can see the vestiges of this legacy with SO questions such as [1], [2], [3] - and the two official documents: Invoking JavaScript Code From an Applet and Invoking Applet Methods From JavaScript Code

With such a language available the browsers of the time (Netscape being the predominant one) made javascript available as a competitive advantage (javascript designed at Netscape - Netscape was the first server side javascript with its server back in '94 - nearly two decades before node.js). Other browsers followed suit.  People were writing pages that used javascript, other attempts at client side scripting would mean completely incompatable pages between things that work and things that don't - or duplication of code (here's the {insert language here} block that does this for non-javascript browsers and here is the javascript block for everyone else).

As Netscape was the dominant browser for a period, javascript took hold.  While the legacy of Netscape is lost to the footnotes of the source files of Mozilla, javascript lives on and nothing has been able to over throw it's place.

The problem remains for any other client slide scripting language.  Javascript is supported on every browser.  If one was to make a browser that supported python (for example) rather than javascript, it would not be able to use the vast majority of the web sites.  Furthermore, unless that browser was able to get a significant share of browser traffic, web designers don't want to create two sets of pages with different scripting languages for the same page.

One might try to make a python scripting plugin for some browser that enabled a python script on the page... akin to how vrml works today.  But unless you have heard and seen of a web page that uses vrml, one is just as likely to find use for another web page for another scripting language.


问:
What is the value of using version control?
I'm new to version control (currently using SVN), but I don't understand how this helps developers. What does version control do that makes it useful in a development environment?</p>

答:
Version control offers a number of things:

Archive your software so you can see the state it was in at previous
points in time. Very useful for finding where a bug was introduced.

Allow multiple developers on the same project to share and coordinate
their work while helping to guard against overwriting each others
work.

Support individual and business continuity particularly through a
central server that is protected and backed-up.

Its a minimum for any software development work beyond just tinkering to see what happens.

I always warn anybody who is working with a version control system for the first time that avoiding it is only inviting trouble.  They WILL run into a problem that when they look back they WILL realize it would not have happened if they used the system.

ContentLicense: CC BY-SA 4.0


答:
Python is a "console" language, running on the server

Javascript is a "browser" language, running on the client

As such, they don't compete directly

...of course there is node.js and probably python browser plugins, but then it's more a question about the performance about a particular implementation.

Moreover, for most applications python will do just fine, except if you have to do some kind of extensive computations and squeeze out CPU cycles.

As a last note, python and javascript share many similarities. Due to their dynamic nature, both have to be interpreted at runtime and cannot be compiled as strongly as static typed languages. As such, I assume their achievable performance would be similar.


问:
How to offer custom word processor like editing power from an application
I have a very complex Java application which renders spreadsheet tables and summary documents in a window.
These outputs are non standard in the sense that for instance the spreadsheet table isn't really a spreadsheet indeed not every row is an instance of an entity and every column an attribute. Some rows might for instance be titles to sub tables.

Now the user wants to print these screens so we generally offer to export these screens to word processor or spreadsheet documents so that he can customize font, number of columns, width of columns etc etc.

The problem with that is that the management is not happy with this solution because although flexible it forces the user to customize the document for every single print and has to restart from the beginning each time.
We had therefore to put some editing features in our program and if the user wants something more (for instance backgroudn color of a row) he can always export what he has so far and add the wanted extra features to the document using his word processor or spreadsheet processor.

Thsi solution works but doesn't please me because the more time passes, the more our very complex program has to deal with editing like features at a point where in a future it will be as complex as a standard word or excel processor.

Isn't there any solution to keep our program separate from editing features but somehow to let the choices be remembered when the user wants to export the data and not let him redo all again?
This solution should be portable enough to work with OpenOffice, Libre Office and Microsoft Word at least...

Thank you

答:
We have exactly this issue.

Our solution was to engage with the customer, discuss the options, they want HUGE flexibility, but little work.

Build reports. We use Microsoft SQL Reporting Server (which the Express edition is free for commercial use but limited, need standard licence for busy/production sites)

From 'the screen' you want to print from, you 'open' the report by passing I the correct parameters.

For example, if you were on an 'order' screen, you would pass the 'order id'.

From SSRS, you can view/print etc. and export to Word/Excel/PDF.

The reports are simple to create if you know SQL. Otherwise a bit difficult. So provide the 'base' report/template, then they can change/add to it with ease, a bit like a really old edition of word!

Pros:

Really flexible

Can make reports look really nice: https://stackoverflow.com/questions/1246428/examples-of-great-looking-ssrs-pdf-reports

Can do email schedules etc.

Word/Excel/PDF export

lots more

Cons:

There is a learning curve to using SSRS Report Builder. Lots of
videos on you tube.

You have to maintain/setup a 'server' to run reports on, it is
possible to run reports locally only, but you're in JAVA so I won't
go there.

not a simple to edit as a word document

when building a report, you need to connect to THE database directly, or have a local copy of it.


问:
What can a technically proficient senior software developer study to keep improving
Say you have been programming for over 10 years. You know many languages, with few of those at very detailed level. You have been designing architecture for solutions, worked on and delivered larger projects. You have been studying patterns, best practices, effective coding guidelines, unit testing, multi-threading, etc.

And then you slowly develop a feeling that most of the books you read, give less and less valuable information per 100 pages of text. So they start giving diminishing returns. You still learn, but you no longer improve by leaps and bounds.

Why does learning become less productive compared to how it was before?

Back then, it used to change your way of thinking, taught you new things and broadened your horizons that later improved either your current profession, or allowed to invent/manage/build something new. Why is it no longer the case?

答:
After a certain point, you've learned enough about a specific topic that you are comfortable picking up new knowledge on an ad hoc basis. When you feel that there is not much more to learn about your primary field, it's time to start gaining supplemental knowledge that complements your primary knowledge.

For me, I am diving into UX and graphic design because I feel that will make me better as a developer to provide not just elegant structures in code but also elegant interfaces for the end user.

Other topics you can approach include project management, business analysis, system administration, and software process improvement. If you find yourself working in a specific domain, it might make sense to dive deeper into that domain. For example, I have been working heavily in the financial services sector lately. I've signed up for courses on Coursera around financial modeling and the like that will help me speak with my customers on their terms.

There's always more to learn, it just takes thinking outside the box.


答:
Release the App.

Because you already coded it, the most you can loose (from a lawsuit) is the generated income from the App. Plus they will likely send you a "Cease and Desist" prior to taking any legal action.

Basically worst case scenario is: you are back where you started now, with no revenue.
(I would doing this before investing any more development time into your app).

Also Check out Ask Patents

Ps: I am not a lawyer.


答:
I am neither a lawyer nor an accountant.

What I have done is to register an LLC. You can register an LLC in your state for relatively cheap (hundreds) and you can set it up so that income goes directly to yourself and is taxed as your regular income (it won't be double-taxed like in a normal corp).

The LLC will be liable for any suits brought against it, but you won't be held personally accountable, so if you get sued you can choose for the LLC if you want to fight, settle, or declare bankruptcy and it won't disturb your normal finances.

I think everyone should do this. Well-known patent troll Intellectual Ventures creates shell companies to protect its assets against counter-suits; we indie developers should all have non-shell companies to protect ourselves from patent trolls.


问:
Single-Tenant Databases - creating and updating new tenants via PHP
We've built a single-tenant webapp in PHP and as it stands each hosted 'site' has its own database.

However we need to be able to run a script to create their database, assign a mysql user, and insert the default sql.

Now, we've got the database and user stuff working fine, its just the importing of the SQL. From what I can tell, PHP quite simply sucks when it comes to handling sql files, so storing a 'template' sql file seems to be out of the question.

My next thought was maybe storing a live database which is then cloned, giving the site its pre-populated database, however I cant see how this would work.

At the same time, I'd rather not 'hard code' the table creations into PHP as if we perform any updates we want to be able to update the SQL direct from our backend control panel.

Surely there has to be a logical way of handling creations and updates on a multi-tenant SaaS?

答:
You can execute an SQL file from the command line using MySQL's client.  So you always have the option of doing:

```<code>mysql -u <etc> -p <etc> <database> < master_definition.sql
</code>```

right from a command line or shell script.  Or exec() from within PHP.  Once the structure is created, then insert users from within a PHP script.

Body:
You can execute an SQL file from the command line using MySQL's client.  So you always have the option of doing:

mysql -u <etc> -p <etc> <database> < master_definition.sql

right from a command line or shell script.  Or exec() from within PHP.  Once the structure is created, then insert users from within a PHP script.


问:
About ANSI C++ 2003 standard
I would like to ask for your help. I searched a lot on Internet, but I found mismatched informations.

My questions:

I tried to buy the "ISO/IEC 14882:2003(E) Programming Languages - C++" standard on the ansi.org, but i have not found it. However, I found this standard on nssn.org:

www.nssn.org/search/DetailResults.aspx?docid=338353&selnode=

But unfortunately this standard has been deleted or replaced with an another one.

webstore.ansi.org/RecordDetail.aspx?sku=INCITS/ISO/IEC%2014882-2003

On the iso.org, it's also the same situation:

www.iso.org/iso/catalogue_detail.htm?csnumber=38110

Yes, I know that the actual standard is C++11, but I'm need the C++03 standard. From another sources, I heard that, the C++03 standard has become an open standard, so I can download it from the Internet for free, THE FULL, OFFICIAL standard, for example:

code.google.com/p/openassist/downloads/detail?name=C%2B%2B%20Standard%20-%20ANSI%20ISO%20IEC%2014882%202003.pdf

cs.nyu.edu/courses/spring13/CSCI-GA.2110-001/downloads/

Is this true?
And it's the full, official C++03 standard, not just a draft?

Is that true, the C99 (C programming language, 1999) has also become an open standard? If yes, this is the full C99 standard?: cs.nyu.edu/courses/spring13/CSCI-GA.2110-001/downloads/C99.pdf

答: The current C++ standard is C++11. It replaces C++03, which is no longer an official standard, so you can't get copies from ISO or INCITS (formerly ANSI). It is by no means an "open standard", for whatever reasonable meaning you attribute to that phrase.</p>

Title: About ANSI C++ 2003 standard

OwnerDisplayName: Pete Becker


答:
All ISO standards work in the same manner. When a new version is published and approved, older versions are immediately withdrawn and no longer available. National standard institutes follow this procedure too. This is "the standard way of handling standards".

C++03 and C99 are no longer available (nor C90 for that matter). Neither the C nor the C++ standards are "open", an open standard is typically a standard that is handled by a non-profit organization.

My advise is to either refer to draft standards, or to search around among the various national standard institutes, some of them may still have withdrawn standards available.

Title: About ANSI C++ 2003 standard

Body:
I would like to ask for your help. I searched a lot on Internet, but I found mismatched informations.

My questions:

I tried to buy the "ISO/IEC 14882:2003(E) Programming Languages - C++" standard on the ansi.org, but i have not found it. However, I found this standard on nssn.org:

www.nssn.org/search/DetailResults.aspx?docid=338353&selnode=

But unfortunately this standard has been deleted or replaced with an another one.

webstore.ansi.org/RecordDetail.aspx?sku=INCITS/ISO/IEC%2014882-2003

On the iso.org, it's also the same situation:

www.iso.org/iso/catalogue_detail.htm?csnumber=38110

Yes, I know that the actual standard is C++11, but I'm need the C++03 standard. From another sources, I heard that, the C++03 standard has become an open standard, so I can download it from the Internet for free, THE FULL, OFFICIAL standard, for example:

code.google.com/p/openassist/downloads/detail?name=C%2B%2B%20Standard%20-%20ANSI%20ISO%20IEC%2014882%202003.pdf

cs.nyu.edu/courses/spring13/CSCI-GA.2110-001/downloads/

Is this true?
And it's the full, official C++03 standard, not just a draft?

Is that true, the C99 (C programming language, 1999) has also become an open standard? If yes, this is the full C99 standard?: cs.nyu.edu/courses/spring13/CSCI-GA.2110-001/downloads/C99.pdf


问:
Does anybody ever uses the OpenId url Log in?
As programmers I think we are the most inclined to use new technologies and things that are not so mainstream.

I absolutely love OpenId's ability to log in with credentials you already have, but I always use a provider that I already use and that is the fastest to log in, like google. God knows I'd never used it if i had to type in the whole "https://www.google.com/accounts/o8/id" I like to click on the google button and then just say yes (the first time, then its just clicking the button).

Does any of you ever uses the Generic "Enter your own provider" OpenId?

Do you think its worth to even offer it to more casual end users?

答:
I use Yahoo for the most part, easy to remember if you set it up right:

me.yahoo.com/xxxx

ContentLicense: CC BY-SA 2.5


问:
Is Non-Deterministic Resource-Management a Leaky Abstraction?
From what I can see, there are two pervasive forms of resource-management: deterministic destruction and explicit. Examples of the former would be C++ destructors and smart pointers or Perl's DESTROY sub, whilst an example of the latter would be Ruby's blocks-to-manage-resources paradigm or .NET's IDispose interface.

Newer languages seem to opt for the latter, perhaps as a side-effect of using garbage collection systems of the non-reference-counting variety.

My question is this: given that destructors for smart pointers or reference-counting garbage collection systems -- almost being the same thing -- allow implicit and transparent resource destruction, is it a less leaky abstraction than the non-deterministic types which rely on explicit notation?

I'll give a concrete example. If you have three C++ subclasses of a single superclass, one may have an implementation that doesn't need any specific destruction. Perhaps its does its magic in another way. The fact that it doesn't need any special destruction is irrelevant -- all of the subclasses are still used in the same way.

Another example uses Ruby blocks. Two subclasses need to free resources, so the superclass opts for an interface that uses a block in the constructor, even though other specific subclasses might not need it since they require no special destruction.

Is it the case that the latter leaks implementation details of the resource destruction, whilst the former does not?

EDIT: Comparing, let's say, Ruby to Perl might be more fair since one has deterministic destruction and the other hasn't, yet they're both garbage-collected.

答:
No" the destructor, or other interface that says "this class must be destroyed" is a contract of that interface. If you make a subtype that doesn't require special destruction I would be inclined to consider that a violation of the Liskov Substitution Principle.

As for C++ vs. others, there's not much difference. C++ forces that interface on all it's objects. Abstractions can't leak when they're required by the language.


答:
There's two parts to this question: why is it harder to learn, and what can you do?

The first part is pretty straightforward - more advanced topics are harder. As difficult as it is to learn how to program, it's quite a bit harder to learn how to design programs well, and even harder to learn how to design large applications. The fact of the matter is that advanced topics are harder, or else they wouldn't be advanced. You'll need to spend more time learning them; more time practicing to master them.

As for what you can do, you seem focused on the technical aspects of being a senior software engineer. You can do a lot more things to help your team create software than learning languages and frameworks. Soft skills, such as mentoring other developers, negotiating requirements, project management, program design, communicating vision, implementing team norms... All those important things needed to make a team of developers effective at making software, not just you.

Title: What can a technically proficient senior software developer study to keep improving

Body:
Say you have been programming for over 10 years. You know many languages, with few of those at very detailed level. You have been designing architecture for solutions, worked on and delivered larger projects. You have been studying patterns, best practices, effective coding guidelines, unit testing, multi-threading, etc.

And then you slowly develop a feeling that most of the books you read, give less and less valuable information per 100 pages of text. So they start giving diminishing returns. You still learn, but you no longer improve by leaps and bounds.

Why does learning become less productive compared to how it was before?

Back then, it used to change your way of thinking, taught you new things and broadened your horizons that later improved either your current profession, or allowed to invent/manage/build something new. Why is it no longer the case?


答:
In the worst case, several things can happen:

You could be sued, but that is very unlikely as a first step.

You can receive a cease and desit letter. At least here in Germany this can be very costly. You have to pay the issuer's attorney's fees which can be a couple thousand euros. I don't know how this works in other countries, but most have a similar system.

You can be forced to "buy" a license for the patent (either by coercing you into a settlement, or directly if the legal system allows it).

What makes this very complicated is that several legal systems apply: The one of your country, presumely American, the one of where Sony resides / chooses to file suit in (USA, Japan, who knows?) and possibly the ones of countries you sell your app in, if you violate any patents held there. It's basically impossible to protect yourself 100%.

What you can do is register an LLC or similar, as Victor said. If you can afford it, you should also try to talk to a lawyer, although I realize this is overkill for most small developers (I certainly wouldn't be able to affort it, and wouldn't want to blow my meager app earnings on one).

One thing you should definately look into is to get legal expenses ensurance. Again, I only know the situation in Germany, where it is pretty affordable, and they'll pay all your attorney fees, but I something similar exists in other countries, as well.

But as Morons said, don't let the possibility of patent violation deter you. The chance of getting into trouble is very small and nobody wants to waste time and money chasing "small fish". The realistic worst case is that they'll ask you to take down your app.

(Oh, and I'm not a lawyer and everything I said is potentially wrong, so don't rely on it.)


问:
Disk I/Os incurred by readLine () in Java
Does readLine() Java function used with BufferedReader cause one disk I/O per call?

If yes, is there any way to read specific number of lines, say n, from a text file causing only one disk I/O?

Here's the code:

```<code>String file;
BufferedReader br = new BufferedReader (new FileReader (file));
int n = 10;
for (int i = 0; i < n; i++)
{
    String line = br.readLine ();
    /* Do something */
}
</code>```

答:
You are going through several layers of abstraction between the java code and the disk.  There is the Java Virtual Machine and its specific implementation, and then there is the operating system that the JVM is running on, which is then communicating to the disk through some method (it may be a network disk, it may be a local raid, it may be a solid state drive, it may be a stream from a network).

The specifics of the disk IO are determined by the virtual machine and operating system and the underlying source of the data.  It may be different for different vm's in how they ask for io requests - there is no way to determine this from within Java, nor is there a way to communicate at that level with the disk through Java.


问:
Why is (position < size) such a prevalent pattern in conditionals?
In a condition statement (IF) everyone uses (position < size), but why?

Only convention or there is a good reason for that?

Found in the wild:

if (pos < array.length) {
   // do some with array[pos];
}
```

<p>Rarely found:</p>

<pre class="lang-c prettyprint-override"><code>if (array.length > pos) {
   // do some with array[pos];
}
</code>```

答:
While it's mainly a matter of convention, it is my opinion that this best matches the way we think - it shows the item on which we place emphasis.

If we translate these to English, it would be the phrase "If the position is less than the array length", where the subject of the sentence is the transient item.

To express it the other way, "if the array length is greater than the position" puts the array length (assumed to be a fixed value) in the subject and the position (transient) becomes the direct object.


答:
The only justification I've ever seen for it is that it is like number lines or other ordering things we learned in school.  For example, we write number lines like this:

```<code><--|--|--|--|--|--|-->
   1  2  3  4  5  6
</code>```

The smaller things appear on the left of larger things.  The same applies to other things such as dates (think of how a calendar is laid out).

It basically boils down to how we naturally think about the order of things.  It is easier to read the first form because you don't have to do much mental processing on it.

Title: Why is (position < size) such a prevalent pattern in conditionals?

Body:
In a condition statement (IF) everyone uses (position < size), but why?

Only convention or there is a good reason for that?

Found in the wild:

if (pos < array.length) {
   // do some with array[pos];
}
```

<p>Rarely found:</p>

<pre class="lang-c prettyprint-override"><code>if (array.length > pos) {
   // do some with array[pos];
}
</code>```

Body:
The only justification I've ever seen for it is that it is like number lines or other ordering things we learned in school.  For example, we write number lines like this:

<--|--|--|--|--|--|-->
   1  2  3  4  5  6

The smaller things appear on the left of larger things.  The same applies to other things such as dates (think of how a calendar is laid out).

It basically boils down to how we naturally think about the order of things.  It is easier to read the first form because you don't have to do much mental processing on it.


答:
My opinion, and this is only my opinion, is that it's a convention for readability.  Although the two are identical, they feel different in my brain.  I don't want to know if the array size is larger than pos.  I want to know if pos is smaller than array size.

It's like a half-empty vs. half-full discussion.  Mathematically identical, but my brain will see them differently depending on the context.

Personally, if I see

```<code>if (array.lengh > pos) {
    // do some with array[pos];
}
</code>```

I will start thinking about whether or not that is a bug and what the programmer meant.  Is he trying to do something other than bounds-checking?

Maybe I'm just not bright, but if I have to do that kind of analysis on every line of code, my brain hurts.

Body:
My opinion, and this is only my opinion, is that it's a convention for readability.  Although the two are identical, they feel different in my brain.  I don't want to know if the array size is larger than pos.  I want to know if pos is smaller than array size.

It's like a half-empty vs. half-full discussion.  Mathematically identical, but my brain will see them differently depending on the context.

Personally, if I see

if (array.lengh > pos) {
    // do some with array[pos];
}

I will start thinking about whether or not that is a bug and what the programmer meant.  Is he trying to do something other than bounds-checking?

Maybe I'm just not bright, but if I have to do that kind of analysis on every line of code, my brain hurts.


答:
Your own example answers the question.  The transparent destruction is clearly less leaky than explicit destruction. It can leak, but is less leaky.

Explicit destruction is analogous to malloc/free in C with all the pitfalls. Maybe with some syntactic sugar to make it appear scope-based.

Some of the benefits of transparent destruction over explicit:

--same usage pattern

--you can't forget to release the resource.

--clean up details do not litter the landscape at the point of usage.

Title: Is Non-Deterministic Resource-Management a Leaky Abstraction?

Body:
From what I can see, there are two pervasive forms of resource-management: deterministic destruction and explicit. Examples of the former would be C++ destructors and smart pointers or Perl's DESTROY sub, whilst an example of the latter would be Ruby's blocks-to-manage-resources paradigm or .NET's IDispose interface.

Newer languages seem to opt for the latter, perhaps as a side-effect of using garbage collection systems of the non-reference-counting variety.

My question is this: given that destructors for smart pointers or reference-counting garbage collection systems -- almost being the same thing -- allow implicit and transparent resource destruction, is it a less leaky abstraction than the non-deterministic types which rely on explicit notation?

I'll give a concrete example. If you have three C++ subclasses of a single superclass, one may have an implementation that doesn't need any specific destruction. Perhaps its does its magic in another way. The fact that it doesn't need any special destruction is irrelevant -- all of the subclasses are still used in the same way.

Another example uses Ruby blocks. Two subclasses need to free resources, so the superclass opts for an interface that uses a block in the constructor, even though other specific subclasses might not need it since they require no special destruction.

Is it the case that the latter leaks implementation details of the resource destruction, whilst the former does not?

EDIT: Comparing, let's say, Ruby to Perl might be more fair since one has deterministic destruction and the other hasn't, yet they're both garbage-collected.


答:
The deeper pattern is that we naturally use "[thing that varies] [comparison] [thing that does not vary]" as the standard order.  This principle holds true for your example because position may vary, while size will not.

The only common exception is when testing for equality some programmers train themselves to use the opposite order (known as Yoda conditions) in order to avoid the common variable = constant rather than variable == constant bug -- I don't hold with this idea because I find the natural ordering described above much more readable, primarily because it's the way we express the idea in English, and because most modern compilers will detect this and issue a warning.


答: No.  A BufferedReader stores data in its internal buffer, that's the entire point of the class.  If there's enough data in there already, a call to readLine() will not issue another I/O request.

Title: Disk I/Os incurred by readLine () in Java

Body:
Does readLine() Java function used with BufferedReader cause one disk I/O per call?

If yes, is there any way to read specific number of lines, say n, from a text file causing only one disk I/O?

Here's the code:

```<code>String file;
BufferedReader br = new BufferedReader (new FileReader (file));
int n = 10;
for (int i = 0; i < n; i++)
{
    String line = br.readLine ();
    /* Do something */
}
</code>```


问:
In a resume, what all constitutes a Programming Language
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?

答:
Personally, I have a Skills & Technologies sections, with different sub-sections:

Programming Languages *

Operating Systems

DataBases

Frameworks & Technologies (where you dump all the stuff you want)

* including markup / declarative languages, because recruiters think it's the same, and technical people who would hold a grudge wouldn't be people I want to work with if they cannot go past it after an interview.

Depending on the job, I modify it to include other sections and be very extensive like this:

Operating Systems

Frameworks / SDKs

Programming Languages

CLEs / VMs

Databases

App. Servers / Containers

IDEs / Editors

Office / Authoring Suites

Virtualization

Which I would admit is way overkill and laughable, but the job market being the way it is, and recruiters liking tick-boxes, I don't see why I wouldn't hold it against them. If it gets me through a keyword search, then I can send a cleaner and leaner version for the interview. (I actually produce always 3 different versions of my resume because of this, and because of cultural differences in seveal countries: I have a 1-page version, a 3-page version, and a very extensive version.)

But I'd agree with others: don't mix languages and libraries. That would be fine with recruiters, as they often - but not always - don't understand any of this in detail and won't see the line between the categories. But people you interview with will think that goes a bit too far. I'd still give you a call for a phone screening though, but I'd say it might leave a negative impression (for instance, I have to confess that my teeth cringe every time I see "J2EE" or "JEE" under the programming languages section).


答:
It depends on how big your lines are.

By default, BufferedReader uses an 8k buffer (see source). This means that it will attempt to read 8K at a time from the Readerthat it was constructed around. You can read as many lines as will fit into that 8K buffer, without going back to the underlying Reader.

Edit: As a general comment, do not use FileReader. Instead, wrap FileInputStream with an InputStreamReader, and specify your encoding.


答:
It's a matter of preference or convention. If you want to be consistent, there are two equally reasonable ways you could go about it:

Always put the "subject" first (think of it as a sentence) - the
value that the test is about. So for example you'd write if
(age>5)

Or always put the smaller element first (think of it as the values
are ordered on your screen in the natural order). So for example
you'd write if (a<b) regardless of whether this code is mostly
about a or mostly about b.

Both conventions would recommend the first snippet you showed instead of the second, so I guess in this particular case you have your answer. I'd say it's wise to avoid writing code that violates both (1) and (2) here, as it'll make it harder to read for most people.


答:
To start with, we must make a clear distinction between languages and implementations.  A language is an abstract thing, the implementation is a concrete thing that can have performance measured.  For example, Lisp was once considered far too inefficient for practical use but compilers kept maturing and, eventually, dedicated hardware was developed for it; at one point in the 1980s it was the development platform of choice for high performance workstation development.

That said, the simplest answer is that a fast Javascript implementation like Google's V8 blows the standard implementation of Python (CPython) out of the water.  V8 is a highly optimized virtual machine with a JITer that is amazingly fast while CPython is a fairly simple VM in comparison.  There's an implementation of Python with a JIT but that is still only about 5-6x faster.

Five years ago it would have been a different story.  Browsers had simplistic Javascript implementations because speed wasn't a concern since nobody built 'real' software with it and Python would have been equal, if not faster.


答:
I think you can solve it using a breadth-first search, maintaining no more than 2 * N^2 tuples of (boolean, int, int, int, string) where the strings are as long as the path is complicated.

The tuples are (min or max boolean, min position traveled, max position traveled, total radiation emitted, path history).

I see the algorithm going like this:

Initialize the pool of tuples to a single entry, (min, 0, 0, 0, "")

Find an element in the pool that has minimal radiation emitted.  If the min and max correspond to the min and max of all the barrels, then the path history is the optimal
solution.  Otherwise delete it from the pool.

Calculate the 2 descendants of this tuple, each of which corresponds to walking left or right to the next unprocessed barrel.

Insert the descendants into the pool.  If there is already an element in the pool with the same boolean, min, and max as a new descendent, then discard the element with the higher radiation count.

goto 2.

Finding and removing dominated tuples will dramatically improve performance.  It might be worthwhile to add a 'has bred" flag to each tuple, and leave bred tuples in the pool.

There are also some significant decisions to be made in deciding how to store the tuples, and search them for dominations and new elements to breed.

Title: Visiting points on a number line while minimizing a cost not related to distance

Body:
I need some help on this ACM ICPC problem. My current idea is to model this as a shortest path problem, which is described under the problem statement.

Problem

There are N = 1000 nuclear waste containers located along a 1-D number line at distinct positions from -500,000 to 500,000, except x=0. A person is tasked with collecting all the waste bins. Each second that a waste container isn't collected, it emits 1 unit of radiation. The person starts at x = 0 and can move 1 unit every second, and collecting the waste takes a negligible amount of time. We want to find the minimum amount of radiation released while collecting all of the containers.

Sample Input:

4 Containers located at [-12, -2, 3, 7].

The best order to collect these containers is [-2, 3, 7, -12], for a minimum emitting of 50 units. Explanation: the person goes to -2 in 2 seconds and during that time 2 units of radiation are emitted. He then goes to 3 (distance: 5) so that barrel has released 2 + 5 = 7 units of radiation. He takes 4 more seconds to get to x = 7 where that barrel has emitted 2 + 5 + 4 = 11 units. He takes 19 seconds to get to x = -12 where that barrel has emitted 2 + 5 + 4 + 19 = 30 units. 2 + 7 + 11 + 30 = 50, which is the answer.

Notes

There is an obvious O(N!) solution. However, I've explored greedy methods such as moving to the closest one, or moving to the closest cluster but those haven't worked.

I've thought about this problem for quite a while, and have kind of modeled it as a graph search problem:

We insert 0 in as a baseline position (This will be the initial state)

Then, we sort the positions from least to greatest.

We then do a BFS/PFS, where the state consists of

Two integers l and r that represent a contiguous range in the sorted position array that we have visited already

An integer loc that tells us whether we're on the left or right endpoint of the range

An integer time that tells us the elapsed time

An integer 'cost' that tells us the total cost so far (based on nodes we've visited)

From each state we can move to [l - 1, r] and [l, r + 1], tweaking the other 3 integers accordingly

Final state is [0, N], checking both ending positions.

However, it seems that [L, R, loc] does not uniquely define a state, and we have to store L, R, loc, and time, while minimizing cost at each of these. This leads to an exponential algorithm, which is still way too slow for any good.

Can anyone help me expand on my idea or push my into the right direction?

Edit: Maybe this can be modeled as a dynamic programming optimization problem? Thinking about it, it has the same issues as the graph search solution - just because the current cost is low doesn't mean it is the optimal answer for that sub problem, since the time also affects the answer greatly.

Greedy doesn't work: I have a greedy selection algorithm that estimates the cost of moving to a certain place (e.g. if we move right, we double the distances to the left barrels and such).

Could you do a Priority-first search, with a heuristic? The heuristic could combine the cost of the current trip with the amount of time elapsed.


答:
Personally, I prefer this:

```<code>bool positionIsWithinBounds = pos < array.length;
if (positionIsWithinBounds) {
   // do some with array[pos];
}
</code>```

... it's more code, but is also very easy to read.

Body:
Personally, I prefer this:

bool positionIsWithinBounds = pos < array.length;
if (positionIsWithinBounds) {
   // do some with array[pos];
}

... it's more code, but is also very easy to read.


问:
Longest subsequence without string
Does there exist a dynamic programming algorithm to find the longest subsequence in a string X that does not contain Y as substring? Just that this problem seems so similar to other DP string algorithms such as longest common subsequence and string.  It must be able to handle occurrences of Y that overlap.

It seems that this might be a 2-state DP problem, with the state [s_pos, t_pos] being the longest subsequence of string S starting at s_pos that does not have sting T[t_pos..M] as a substring. N is the length of string S and M is the length of string T. However, my transitions are not correct: it does not get the case where S=aaabc and T=aabc. The problem is in the else statement - I don't know how to transition if the characters are equal. Actually I feel that the if branch is wrong... anyone know what could be wrong?

It even fails the case S=aaab and T=aab. I can explain why it fails: assuming I call solve(0, 0). solve(0, 0) calls solve(1, 1). solve(1, 1) calls solve(2, 2). Since s[2] != t[2], it restarts the search from solve(3, 0). However, aab is a substring and it never checks this or considers this case...

```<code>int solve(int s_pos, int t_pos)
{
    if (s_pos >= N || t_pos >= M) return 0;
    if (t_pos == M - 1 && s[s_pos] == t[t_pos]) return 0;
    int ret = 0;
    if (s[s_pos] != t[t_pos])
    {
        int tmp = solve(s_pos + 1, 0);
        ret = max(ret, tmp + 1);
    }
    else
    {
        for (int i = s_pos + 1; i < N; i++)
        {
            int tmp = solve(i, t_pos + 1);
            if (tmp != 0)
            {
                ret = max(ret, 1 + tmp);
            }
        }
    }
    return ret;
}
</code>```

答: I think you need to treat the Y substring like a regular expression and transform it into a DFA.  Then you pass the input through the DFA, tracking how long its been since you've had a match.  It seems like a linear-time problem, assuming the size of the input is much larger than the complexity of the matching string.</p>

Title: Longest subsequence without string


问:
Should I tell the interviewer I already know the answer to the question being asked?
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?

答:
I'm in favour of open and honest communication, so I'd definitely say that I knew the question, and the trick involved.

I suppose for extra credit you could say "OK, this is how everyone else does it, but let's see if there's a different way." Or you could deconstruct the question in other ways, and show why people like the question, what the question's supposedly trying to get you to see.

(Edit: removed the reference to FizzBuzz, from other people's comments on this post.)


问:
combining (something like) Flash in a windows form application
I know this is a place where people ask advice for designing code.
I am at a bit strange side on my coding quest, on one side people send me design stuff.
Special graphics and ideas on how they should be shown in a program workflow.

(i think the marketing designers are a bit to powerfull in this project
 They tend to think here that their pictures are the program itself,
 but all that coding still has to be written still ..by me in 1 week.. )

They want tweans of graphics and rotation etc..
Well in short this reminded me of things i have seen in flash
But flash is for the web, as far as i know.
But i think.. those people most likely use Adobe software so might safe it as some Adobe flash formats. In the end it is all about a interface for a machine
Because of some hardware limits, i need to do it all in .net 2 on normal win forms.
And on slow PC hardware  (no direct10 or so).. directX is to much for me to finish in 1 week anyway

Now i was thinking would it be possible to run flash on a form, or what would be something close the the Flash Experience ..you know text tweens/ slide ins etc something that could be combined with C# ?.

答:
If you want to use Flash, you can pull in an ActiveX component of it into a .NET Form (though IIRC you need to get the ActiveX Flash installer to get that component and the installer is somewhat difficult to find on Adobe's website) then you could program things in Flex (if you don't have Flash handy). There's not much documentation that I've been able to find on this ActiveX component though.

As for similar things in .NET itself, I'm not too familiar with that area of .NET, so I'm afraid I can't help you there.


答:
To express what some have tried to get at, in a different way...

When the order makes no difference to the behavior of the program, the difference is clearly a matter of what's most readable to humans. Here's a linguistic reason why putting the "topic" on the left makes sense:

In linguistics, the topic of a sentence is what is being talked about, and the comment is what is being said about the topic. In this example, we can assume that position is the topic, and "less than array length" is the comment. In English, and in many other languages, the topic is usually expressed before the comment.

"The tendency to place topicalized constituents sentence-initially (topic fronting) is widespread."

So a good rule of thumb is to think of your line of code as a sentence (or clause, in this case), decide what the sentence is about, and put that first if you can. Often, what the sentence is "about" will be a variable rather than a constant. But sometimes the comment will also involve a variable, so you can't just go by that.


问:
What is the minumum code/operations to have in a separate thread?
I understand that threading is needed to get the maximum performance out of today's multicore processors but starting a thread is rather costly so you can't put every single calculation that can be done in parallel in an own thread. For example

```<code>answer = new thread(plus(1,2)) + new thread(plus(3,4))
</code>```

will run much slower than the simple single-threaded

```<code>answer = 1+2+3+4
</code>```

but if plus was some really complicated calculation the threaded variant might be faster.

Now to the questions

Are there any convention or standards about what the minimum length of code, operations or execution time that are defendable to put in its own thread?

Do I even have to worry about this or are the compiler/processor so smart that they do all the work for me?

The reason I ask this question is that I saw an implementation of quicksort that started a new thread for every recursive call ending up with (n²) threads and there many of this threads just returned some value.

答:
While a lot dependson your actual tools, the following guideline from Intel's TBB documentation may givea useful ballpark figure:

A rule of thumb is that grainsize iterations of operator() should take at least 10,000-100,000 instructions to execute.

TBB is not exactly heavyweight.


答:
As many other answers have said, it is very often easier to read:

```<code>[thing that varies] [comparison] [thing that does not vary]
</code>```

Almost everyone I know uses this style exclusively.

There is one exception, for C-style languages which use = for assignment and == for comparison.  If you accidentally type:

```<code>if (variable = 5) ...
</code>```

instead of:

```<code>if (variable == 5) ...
</code>```

then you will not get an error because this is a valid line of code.  (Some compilers and IDEs will warn you about doing this, but it is still very easy to have such a simple typo.)

However, if you write:

```<code>if (5 == variable) ...
</code>```

the compiler/interpreter will error because that is not a valid construct (in most languages, anyway).

This switch-around is often called a Yoda Condition.

UPDATE: Here is a list of places where Yoda Conditions are useful.

Body:
As many other answers have said, it is very often easier to read:

[thing that varies] [comparison] [thing that does not vary]

Almost everyone I know uses this style exclusively.

There is one exception, for C-style languages which use = for assignment and == for comparison.  If you accidentally type:

if (variable = 5) ...

instead of:

if (variable == 5) ...

then you will not get an error because this is a valid line of code.  (Some compilers and IDEs will warn you about doing this, but it is still very easy to have such a simple typo.)

However, if you write:

if (5 == variable) ...

the compiler/interpreter will error because that is not a valid construct (in most languages, anyway).

This switch-around is often called a Yoda Condition.

UPDATE: Here is a list of places where Yoda Conditions are useful.


问:
I want to publish an android app, but I'm afraid of software patents
I wrote an application that helps you to save energy. Actually it is very simple. I check the current location of the phone and I make some changes to the configuration like "sound off, dark display, wifi off...", depending on the location of the user. Sony just released a new phone including one of my apps features (actually they have an extra entry in the options menue for this). I have no idea whether there is a patent for this function.

Can I even release this app without risking to be sued some day?

I'm very confused about the whole "patent" situation.

I'm about 20 years old and I can't even write a simple app, without investing lots of money for a lawyer.

Edit: I don't ask for legal advice. I wanted to receive an overview about how developers see or handle the whole situation.

答:
The situation with software patents is complex, and the laws are arguably broken (and vary from country to country), but the best thing you can do is to follow the same route everybody else does:

Don't even try to figure out if you're going to be infringing someone else's patent.
You're presumably not an IP lawyer, so you're unqualified to do the required research. If you do any kind of research, and conclude incorrectly that you're not infringing, the mere fact that you're familiar with the patent in question may open you up to "willful infringement" charges, where the penalties can be much higher.

If you think that some idea in your product is patentable, then engage a patent lawyer to help you prosecute the patent application, and they (along with the patent office) will let you know if you're infringing anybody else's patent.

If you're giving the software away, you're probably pretty safe
With the possible exception of a crazy lone-inventor type, no company is going to want to go through the expense of suing if there's nothing to recover.

If you want to sell anything, you need a way to shield yourself from liability
This varies a lot from locale to locale, but there is often a low-cost way to create a corporate entity that will hold the assets and handle claims against the business, while shielding your personal assets. In the USA, this is typically an LLC or a C-corp, but there are lots of options.


答:
If you use Windows Presentation Foundation, it is a core part of the .NET framework from version 3.5. In short, it allows you to pretty much do all the things in flash, including tweening and rotating as you've said.

The other alternative is to embed the Flash ActiveX component and load an SWF.

EDIT to add: I just saw you wrote .NET2 - WPF requires .NET 3.5, however the core runtime is still the same as version 2. If you can't upgrade to 3.5 then Flash might be your only option.

Title: combining (something like) Flash in a windows form application

Body:
I know this is a place where people ask advice for designing code.
I am at a bit strange side on my coding quest, on one side people send me design stuff.
Special graphics and ideas on how they should be shown in a program workflow.

(i think the marketing designers are a bit to powerfull in this project
 They tend to think here that their pictures are the program itself,
 but all that coding still has to be written still ..by me in 1 week.. )

They want tweans of graphics and rotation etc..
Well in short this reminded me of things i have seen in flash
But flash is for the web, as far as i know.
But i think.. those people most likely use Adobe software so might safe it as some Adobe flash formats. In the end it is all about a interface for a machine
Because of some hardware limits, i need to do it all in .net 2 on normal win forms.
And on slow PC hardware  (no direct10 or so).. directX is to much for me to finish in 1 week anyway

Now i was thinking would it be possible to run flash on a form, or what would be something close the the Flash Experience ..you know text tweens/ slide ins etc something that could be combined with C# ?.


答:
As Sam mentioned, one option for graphically rich UI is to use WPF. You get animations, custom styles and a lot of other features at a much lower cost than trying to do the same in Winforms.

The other is using Adobe AIR which is basically Flash for the desktop.


问:
How do I handle having so many SQL queries?
I have an MVC3 project that uses SQL Server.

I use data from the SQL database all the time and I often find that I'm reusing/duplicating some SQL queries. I thought I'd solve this problem by creating a few static "helper" classes that just contain a bunch of static methods for retrieving common things.

```<code>GetAllUsers(database As MyEntity)
GetAllNonActivatedUsers(database As MyEntity)
GetUser(database As MyEntity, userId As Integer)
</code>```

The problem is that this made things slightly worse. Now instead of having SQL queries all over my controller actions, there are large numbers of them in these helper classes. The names of these methods are becoming silly.

```<code>GetPendingUserApplicationByApplicationId(database as MyEntity,
    applicationId As Integer, userId As Integer)
</code>```

At this stage I'm thinking of scrapping the helper classes and going back to just random SQL queries throughout my controller actions.

Where have I gone wrong and how do people manage their SQL queries?

Is it ok to duplicate SQL queries?

答:
A lot of people these days (based purely on my professional exposure) are now using ORM tools for the benefits they provide.

Benefits include:

Lazy loading

Multiple database targets

For some frameworks, use of LINQ to select records (i.e. Linq-to-SQL, Entity Framework)

Not having to change multiple queries when you add a field

The primary negative as far as I am concerned is a steep learning curve however Linq-to-SQL is fairly simple.

Since you are using ASP.NET MVC, I'd suggest looking at the Entity Framework tutorial Microsoft provides on the ASP.NET portal.

Where have I gone wrong and how do people manage their SQL queries?

I've been using ORM frameworks for years which minimises the amount of SQL I need to use. For times when I have to write SQL (which is not often) I ensure I write standards compliant code that works on all database targets, I embed them in the assembly under a SQL folder and load the resource stream for execution. Personally, I don't ever write SQL queries inline.

Is it ok to duplicate SQL queries?

I would say it is a code smell but that's because I consider any duplication to be so.


问:
Can commented-out code be valuable documentation?

I wrote the following code:

if (boutique == null) {
    boutique = new Boutique();

    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.persist(boutique);
} else {
    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    //boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.merge(boutique);
}
```

There is a commented-out line here. But I think it makes the code clearer, by making obvious what the difference is between if and else. The difference is even more noticeable with color highlighting .

Can commenting out code like this ever be a good idea?

答:
The only time I've seen commented-out code that was useful was in config files, where the code for every option is provided, but commented out, making it easy to enable settings by just removing comment markers:

```<code>## Enable support for mouse input:
# enable_mouse = true
</code>```

In this case, the commented-out code helps to document all of the available options, and how to use them. It is also conventional to use the default values throughout, so the code is also documenting the default settings.

Body:
The only time I've seen commented-out code that was useful was in config files, where the code for every option is provided, but commented out, making it easy to enable settings by just removing comment markers:

## Enable support for mouse input:
# enable_mouse = true

In this case, the commented-out code helps to document all of the available options, and how to use them. It is also conventional to use the default values throughout, so the code is also documenting the default settings.


答: I'd just answer it without much hesitation or screwing around. Knowing the answer to a question isn't something evil, it means you've encountered it before and know how to solve it. Fix it, move on to the next.</p>

Title: Should I tell the interviewer I already know the answer to the question being asked?

Body:
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?


问:
Performance and other issues with using floating point types in C++
Being interested in C++ performance programming there is one aspect I really have no clue about- and that is the implications of using floating point calculations vs doubles vs normal integer mathematics?

What performance issues with these types of calculations should I consider? What other issues need to be considered when deciding which kind of operators to use?

All I currently know is that doubles are probably the most expensive because they are larger, floating point is next and then integer calculations are usually the fastest on a CPU because they are much simpler.

答:
The comments by @ratchet, @Sjoerd and @Stephane answer you question.

Your assertion in the question "All I currently know is that doubles are probably the most expensive because they are larger" shows the rules about optimization - are true - "Only for experts" followed by the "Your not an expert yet" .....

Unless you know the minutest details of the underlying hardware AND how the compiler utilizes those, you cannot make any assertions about floating point numbers. You can't even be certain that a floating point operation takes more time than an integer operation.
As a rule, there is enough problems with programmers writing floating point code correctly, that it should be avoided unless needed. If needed, performance is of little concern.

As a rule of thumb - use ints if possible - it's rarely slower then FP operations, and often faster, and more predictable. If you must use FP operations, use doubles. Floats do not have a large enough mantissa for anything but the roughest of calculations (unless extreme care is taken) and a prone to insidious rounding errors.

However, like all rules of thumb, they need to be applied appropriately. If it matters - measure it.


问:
Queuing RPC calls
I'm designing a system which listens to JSON RPC calls from clients, piles them up inside a list, and if the list gets full it will store them in a DB and keep receiving calls.

My original plan is to listen to the RPC calls from Perl with the JSON-RPC and put them in an array. The clients do some long polling in another server to get responses as they appear.

What is this blocking/non-blocking thing?

Should I do a script for node.js to listen to the calls?

What do you think is a good practice in this case?

The goal is to listen as much calls as possible.

答:
It sounds to me that using a message queue (MQ) would be ideal for you here.

piles them up inside a list, and if the list gets full it should store them in a DB and keep receiving calls.

An MQ can be thought of as a first-in first-out storage service. The way it works is that rather than piling up your service requests and managing them internally, you would write them to the queue and have your server process poll the queue to see if there are any messages to process.

What is this blocking/non-blocking thing?

Blocking / Non-blocking refers to the time it takes for an operation to complete blocking the thread from running. For example, IO and network operations are a common blocking bottleneck.

Using a message queue would allow you to largely avoid blocking as they're generally quick (given being located on the same network) and will allow you to fire the RPC call and continue with your processing.

If you need to process a result this gets more complex and where you would consider mechanisms such as a result queue that you poll, invocation of a remote script, etc.

Title: Queuing RPC calls


问:
Is there a proper way to create a file format?
I'm building a proprietary file format for an application I wrote in C# .NET to store save information and perhaps down the line project assets. Is there a standard on how to do this in any way? I was simply going to Serialize my objects into binary and create a header that would tell me how to parse the file. Is this a bad approach?

答:
I would also love to hear answers to this question from people with years more experience than myself.

I have personally implemented several file formats for my work, and I've moved over to using an XML file format. My requirements and hardware that I interact with change all the time, and there is no telling what I will need to add to the format in the future. One of XML's primary advantages is that it is semi-structured. For this reason, I generally avoid automatic XML Serialization that .NET provides because I believe it forces it to expect an exact format.

My goal was to create an XML format that allowed for new elements and attributes to be added in the future and for the order of the tags to not matter whenever possible. If you are sure that you can load your entire file into memory then XPATH is probably a good choice.

If you are dealing with particularly large files, or for other reasons cannot load the file all at once, then you are probably left with using an XmlStreamReader and scanning for known elements and recursing into those elements with ReadSubtree and scanning again...

OwnerDisplayName: Corylulu


问:
What is Delegation and why is it important in iOS programming?
At the moment I am teaching myself iOS programming, and one concept I find really hard to wrap my head around is delegation. What is it? Why and how is it used? What is the advantage? The technical writing from the book I'm reading makes it hard to understand. </p>

答:
Delegates are objects that implement certain functions when it doesn't make sense to implement those functions on the normal object. It is a form of dependency injection.

For a concrete example, look at the UITableViewDelegate protocol. These methods don't make sense for a table view to implement directly, because actions for selecting a table view row will be different in each app and maybe in each table view. The delegate has a method -tableView:didSelectRowAtIndexPath: so you can create an object that handles row selection without subclassing the table view for every separate action you want to implement.


答:
I disagree wtih Haylem on listing markup languages under programming languages - markup languages are used to structure data, not to actually generate it. You can't actually program anything with HTML, at least not in combination with Javascript - in which the markup language becomes the data storage medium, of a sorts. List those under frameworks / technologies.

Also, proving you actually know the difference between a programming / scripting language, markup / data structuring language and libraries / APIs will avoid you getting thrown off of the list after a quick glance at your resumé.

Title: In a resume, what all constitutes a Programming Language

Body:
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?