问:
Smallest lexicographical rotation of a string using suffix arrays in O(n)
I will quote the problem from ACM 2003:

Consider a string of length n (1 <= n <= 100000). Determine its minimum lexicographic rotation. For example, the rotations of the string “alabala” are:

alabala

labalaa

abalaal

balaala

alaalab

laalaba

aalabal

and the smallest among them is “aalabal”.

As for the solution - I know I need to construct a suffix array - and let's say I can do that in O(n). My question still is, how can I find the smallest rotation in O(n)? (n=length of a string)

I'm very interested in this problem and still I somehow don't get the solution. I'm more interested in the concept and how to solve the problem and not in the concrete implementation.

Note: minimum rotation means in the same order as in an english dictionary - "dwor" is before "word" because d is before w.

EDIT: suffix array construction takes O(N)

LAST EDIT:
I think I found a solution!!! What if I just merged two strings? So if the string
is "alabala" the new string would me "alabalaalabala" and now I'd just construct a suffix array of this (in O(2n) = O(n)) and got the first suffix? I guess this may be right. What do you think?
Thank you!

答:
A simple trick to construct all rotations of a string of length N is to concatenate the string with itself.

Then every N-length substring of this 2N-length string is a rotation of the original string.

Locating the "lexicographically minimal" substring is then done with your O(N) tree construction.


问:
Patterns for Maintaining Model State in Real Time
While some platform in some languages already address this issue, I would like to keep this semi-language agnostic and to focus on patterns associated with this issue.

I have a data model that contains FirstName, MiddleName, and LastName (to keep things simple).  First and Last names are required and may have other rules to ensure their validity.  Middle name is optional.

By default, the model is empty and thus, invalid.

When a value changes, an event can be triggered to validate the field that changed.

My question is what patterns can be used to best manage the state of the object since, based on the scenario, I'm doing field level validation.  Should I move to model level validation on field change which would address the state issue or is there an alternate way?

答:
This is a common problem in data validation; When entering new data into the system, before any information is entered by the user, the default working state of the object (mostly nulls) is an invalid state for virtually all other processes of your system.

Validation is always context-dependent. If you have, for instance, a business requirement that all entered "people" records must have at least a first and last name, then neither field-level validation (which would only be run when setting a field, and so would not catch a failure to set the other field), nor model-level validation (which, if invoked real-time, would return a validation error for this rule when entering the first name because the last name is invalid) would work all the time when implemented naively.

Instead, your domain model has to be made intelligent enough to know when it is ok to be in an inconsistent state, and when it is not. Usually, this is accomplished by providing some sort of scope or context identifier into your validation routines:

When entering a single field, you can, and should, only validate rules the define the behavior of that single field. You simply cannot require the user to enter a last name when they are attempting to specify a first name in a new record, and vice-versa.

At certain points, you may know that a subset of your object should now be in a consistent state. This may happen when filling out a multi-page form and attempting to continue to the next page; at that point, you may validate rules that involve one or more fields on the current page. This includes all field-level validations, but also additional multi-field validations, such as making sure date ranges composed of a start and end date are valid (end date after start date for instance), and that a person has both a first and last name.

Sometimes, if one page's data depends on data in a previous page, you may be able to make these validations as well, but in that case those validations should not prevent a person going backwards to fix a mistake; it should only prevent the user continuing now that there is an obvious inconsistency. Understand that allowing real-time validation of values within a page or across multiple pages may introduce undesirable coupling; the validation rules must incorporate logic that is dependent on the structure of the View layer.

Finally, when persisting an object (or retrieving it from persistence for use behind the scenes), it must be wholly consistent. That includes all field validations, all page-level validations, and additionally all rules involving data spread across multiple pages.

Rules that the model must meet at one of these levels may prevent proper execution of the program when run at a lower level. It is often possible to include the scope or level of validation in a suite of rules that can be run with one method call, thus allowing the rule to pass if the data is "consistent enough" for a particular level of validation. However, doing so often couples the domain (or controller) to a very specific View, making the design brittle; if you want to move a field to a different page of the View, the validation routines back in the controller or data model may have to change to reflect this. There may not be a good way around this if you want to validate each rule as soon as possible.

ContentLicense: CC BY-SA 3.0


问:
any website monitoring library/modules to use in my website?
I'm trying to build a site which user can add their websites which should be monitored and can view a detailed report and statistics of it. And also it should be able to monitor local webservices (mainly),

1) is there any popular java library to use for monitoring a website? (in sense to ping a website and load some content etc., or to show whether site is up or not kinda)

2) Also to validate a flow of website (if possible)?

Example: Go to login page, find fields , fill fields and submit form and validate for successful login or not.

I know this kinda looks big but any small part done can be helpful, I've found several of monitoring projects, but they only do normal websites but not local/other webservices and also they can't validate flow of website.

答:
All types of normal monitoring can be done via Nagios.

However to test the flow of a website you should probably set up automated test software for production. E.g Run Selenium scripts. You may run them with FitNesse or directly via a cronjob.

I previously answered a similar question on ServerFault, referring to a monitoring software I wrote myself once.


问:
What should I learn more about debugging?
To debug my programs I mainly use the following methods:

Use printf (or equivalent in other languages) to check the value of a variable after a particular statement or to check whether the program enters a conditional statement or a loop.

Use watch/breakpoints when using IDEs.

I am able to solve the problems using the above methods. But I have noticed that there are two kinds of builds - debug and release. From the name I can understand that debug build would be helpful in debugging. Also I have read that debug build stores something called symbol table information and stuff.

How can I use the debug build for debugging? Are there any other debugging techniques which I should learn?

答:
The most important debug tool I've ever used is the post-mortem crash dump (core dump in Linux, user dmp in Windows).

Its a really complex topic, so here's a link:

basically (on Windows, the platform I have most experience post-mortem debugging with), you build your apps with symbols that are saved in a separate file (a .pdb file). You keep these safe (so no-one can easily reverse-engineer your code) and wait for a crash. When it does (and you have DrWatson or similar running to capture the crash and generate the dump file), you load the .dmp file into WinDbg (windows debugger) along with the symbols (and optionally, a path to the source code) and it will show you loads of information like call stack, registers, variables, memory values etc. Its beautiful when it works.

For a debug build, all this is set up to happen automatically. You have to enable symbols when building release. Debug builds also add other stuff like memory guards (that trigger exceptions is you try to write into them, this shows buffer overflows or memory corruption real easily; or asserts for things that are not-quite-right). Generally though Debug builds are for developers to run and test their code before passing it on.

Now this is for native code debugging, .NET code is a PiTA for post-mortem stuff like this, but you can sometimes get .NET exception stuff out by loading sos.

All complex stuff, but it's not so bad. Don't expect nice pointy-clicky GUI though, this is command line power loveliness.


答:
A debug build is built with debugging symbols in the executable. Basically what that means is that every line of source code is linked to the machine code that was generated from it, and all the names of variables and functions are kept. In GCC this is done with the -g flag when you compile source files. Another thing that is often done is to turn off optimisation, this is because the compiler does some neat tricks that makes your program go faster, but makes debugging impossible. In GCC this is done with -O0.

The single most useful tool that I have ever used for debugging is gdb. It is a text version of the IDE breakpoints that you mentioned. You can do a lot more with gdb than you can with an IDE though. In fact, some IDEs are just a wrapper around gdb, but some features are lost. You can watch memory locations, print assembly, print stack frames, change signal handling, and a whole lot more. If you are serious about debugging, I would learn gdb or some equivalent text-based debugging program.

Another thing that I often find useful is valgrind. It finds memory leaks and keeps track of whether memory is initialised or not. You use it with your debug build, because then you get line numbers where interesting things happen.

Title: What should I learn more about debugging?

Body:
To debug my programs I mainly use the following methods:

Use printf (or equivalent in other languages) to check the value of a variable after a particular statement or to check whether the program enters a conditional statement or a loop.

Use watch/breakpoints when using IDEs.

I am able to solve the problems using the above methods. But I have noticed that there are two kinds of builds - debug and release. From the name I can understand that debug build would be helpful in debugging. Also I have read that debug build stores something called symbol table information and stuff.

How can I use the debug build for debugging? Are there any other debugging techniques which I should learn?


问:
Will Java still be relevant in 5 years?
Will Java have the same importance it had in the past, or it will be less relevant than nowadays?</p>

答:
It depends on how the language will evolve.

At present state Java is not very actractive as language. It was born to support one (and just one) paradigm: OOP.
It places itself somewhere midway between languages that permit higher level abstractions (like C++ and its metaprogramming features) and scripting languages with reflection capabilities (like the Python "exec" and "dir" commands) but somehow it fails to find its real place.
It's basically becoming obsolete as "language". Weren't for the fact it's a de-facto standard on mobile devices I think it would be dead by now.

As for the fact it's a good teaching language for OOP I have my doubts from what I can see: all Java-born programmers just spawn Visitor and Observer patterns everywhere but it's not that I have a great experience with Java programmers.

Still there is a lot of legacy code and on mobile devices it's a standard. That said I'd never choose Java for either a desktop or a web application. There is no reason to, apart business ones (most managers nod if you say "Java" and that is, I suppose, the reason it's a standard on mobile devices).

Title: Will Java still be relevant in 5 years?

ContentLicense: CC BY-SA 2.5


问:
Should Sequence Diagrams be Specific or Abstract?
I'm creating a sequence diagram for a simple program I'm working on for work. The diagram I'm currently working on is very high level - it defines the interface with lots of alt paths, but does not exemplify any specific use cases. I was wondering whether would it be more appropriate to instead make several diagrams which demonstrate specific examples.

I'm not familiar with the way that these diagrams are intended to be used, and I've seen both specific examples and abstract examples.

Thanks!

答:
It depends entirely on what you want to communicate.  In my experience sequence diagrams work great for both very high level through to very low level systems.

For example, we use a sequence diagram showing the event level flow of an SSL handshake to help explain some security related issues to users.  Very low level, and very concrete.

We also use a sequence diagram that shows the high level message exchange in our distributed system between the four or five actors in place.  That makes each actor something like 50,000 lines of code in size - and events that take multiple communications are one "event" at that scale.


答:
@flurdy gave some good suggestions. Nagios is good, Selenium is great.

For graphs, checkout Munin

For site flow check out http://www.dejaclick.com/ - their app uses a Firefox extension to record user interaction on a site then replay it throughout the day to test whether or not it can complete that cycle. So for example, adding something to a shopping cart and checking out completely.

Title: any website monitoring library/modules to use in my website?

Body:
I'm trying to build a site which user can add their websites which should be monitored and can view a detailed report and statistics of it. And also it should be able to monitor local webservices (mainly),

1) is there any popular java library to use for monitoring a website? (in sense to ping a website and load some content etc., or to show whether site is up or not kinda)

2) Also to validate a flow of website (if possible)?

Example: Go to login page, find fields , fill fields and submit form and validate for successful login or not.

I know this kinda looks big but any small part done can be helpful, I've found several of monitoring projects, but they only do normal websites but not local/other webservices and also they can't validate flow of website.


答:
Diagrams should help understand things.

If they don't, they fail.

Sequence diagrams are very good at explaining protocols over network and single interactions in a API, in any non-trivial API you're gonna have an hard time describing all interactions. (i.e. you can't)

You obviously have to make multiple diagrams, one for each interaction scenario, making a single diagrams with all the interactions overimposed one another is sick and will make people's eyes cross.

You will still have to write your documentation in natural language, anyway. Diagrams can only help to attain a broader or more precise understanding on top of an already well written documentation.

And if the API implies the usage of different objects, of different classes, by different users, a class diagram, may and will come handy.

Title: Should Sequence Diagrams be Specific or Abstract?

Body:
I'm creating a sequence diagram for a simple program I'm working on for work. The diagram I'm currently working on is very high level - it defines the interface with lots of alt paths, but does not exemplify any specific use cases. I was wondering whether would it be more appropriate to instead make several diagrams which demonstrate specific examples.

I'm not familiar with the way that these diagrams are intended to be used, and I've seen both specific examples and abstract examples.

Thanks!


问:
What characteristics or features make code maintainable?
I used to think I knew what this was, until I really started thinking about it... "maintainable"... what exactly makes code maintainable?

To me, if code must be maintainable that means we can expect to revisit the code to make some sort of change to it in the future. Code is always "changeable" no matter what state it is in. So does this mean code needs to be easy to change? However, if our code was scalable/extensible, there would be no need to directly change it, because it will "change" (adapt) for free and automatically.

I've also seen code maintainability used interchangeably with coding standards. Using a consistent coding pattern or style, does this really make code more maintainable? More readable and more consistent? Sure, but how does this improve the maintainability?

The more I try to think into this, the more confused I get. Anyone have a proper explanation?

答:
maintaining code means taking that code and making a change to it to fix a bug or add a feature

maintainable code makes this process easier

making code maintainable means making it easy to understand (descriptive variable names, comments and documentation will help here) and making changes to it easy to make (patterns can make this easier, but it depends on the actual need)


答:
Here's a quick list of techniques:

Static call graphs

Dynamic call graphs

Hotspot profiling

Thread messaging watching

Replay debugging/reverse execution

Watchpoints

Tracepoints

You can also implement custom behaviors with AOP-style tools, as well as going a long way with a good static analysis tool.


问:
How do programmers quit a job?
I'm thinking about leaving my current employer and wondering how one goes about that process in the programming world. We have a lot of projects on the go at the moment and I'm the only developer. We have 4-5 projects that are fairly big and need to be done in the next few months and even a few longer than that.

I'm leaving because I'm the only employee and that's doing me no good. I'm young and want to learn, so a team would be nice. It's also too much work and the company is managed horribly.

I have no contract to worry about so I could theoretically quit and just not come back without notice. Just wondering how this is normally handled.

Should I write a resignation letter

How much notice should I give

Should I give a reason for leaving

Should I go to my boss who is the main reason I'm leaving or go to his boss?

Overview of replies

From the feedback here, it looks as though it's best to give 2-4 weeks of notice, and present a written resignation. Don't go into detail explaining why you're leaving in most cases. Don't burn bridges. Be professional.

答:
Be a professional when leaving in my opinion...

If you go for the last two options in the rotten state of Denmark, they'll actually be able to drag you to court for doing so. Concerning the emails you are allowed to delete those that contain information you can find otherwise in the company according to the cases they have trialed here. If you delete files you have created while being employeed you are probably hitting a lawsuit about intellectual property vs business/company knowledge.

If I had no contract I would give them a months notice, just like I have when I have a written contract. I would get them to sign a letter where I state when I quit, and when my last day in the company will be so there is no case of bugging me about that later on. The few times I have quit I haven't written anything about why, but I have always had another job at hand I could go to so it was pretty obvious that I went for greener grass :)

Who should you go to...at the moment I have a manager and two bosses and I would probably go to the boss office and quit, or if the situation allows it I would bring the manager as well.

Title: How do programmers quit a job?


答:
Learn everything about your debugging tool.

They often hide really powerful features that might help you understand better what's happening. (in particular the C++ debugger of Visual Studio)


答:
Learn your Debugger

It's really helpful to get to grips with the debugger, whether it be text-based, full IDE or some blend thereof. You don't give much details so I'll describe the general case:

1) Breakpoints

In addition to just stopping at a line of code, many debuggers let you specify to break when a condition arises (e.g. "x > 5"), after a number of passes through the code or when some memory changes value. This is very useful for understanding how your code gets into a bad state, e.g. watching for when a pointer becomes null rather than catching the crash when it is dereferenced.

2) Stepping through code

You can step into functions, line-by-line along code, jump over lines ('set next statement') and then 'up' out of functions. It's a really powerful way of following your code execution to check that it does do what you think it does :-)

3) Evaluating expressions

So you can put variables into a Watch list/window and see their value change when you hit a breakpoint or step through code, but you can also usually do complex expression evaluations too, e.g. "x + y / 5" will be evaluated. Some debuggers let you put function calls into the watch lists too. You can do things like "time()", "MyFunction(...)", "time()" and get clock timing of how long your function took.

4) Exceptions and Signal handling

So if your language supports exceptions and/or signals, you can usually configure the debugger for how to react to this. Some debuggers let you break into the code at the point where the exception is about to happen, rather than after it has failed to be caught. This is useful for tracking down weird problems like "File Not Found" errors because the program is running as a different user account.

5) Attaching to a process/core

So sometimes you have to use the debugger to jump on an existing process which is going awry. If you've got source code nearby and the debug symbols are intact, you can dive in as if you'd started in the debugger in the first place. This is similar for core dumps, too, except you usually can't continue debugging in those (the process has already died).

Build Configuration

There are a number of build variations you can make through turning on or off features like debug symbols, optimisations and other compiler flags:

1) Debug

Traditionally, this is a plain build with no special characteristics, which makes it both easy to debug and predictable. It varies a little by platform, but there may be some extra head-room on, e.g. allocations and buffer sizes in order to ensure reliability. Usually a compiler symbol like DEBUG or Conditional("Debug") will be present so debug-specific code is pulled in. This is often the build that is shipped, with function-level symbols intact, especially if reliability and/or repeatability are a concern.

2) Release/Optimised build

Enabling compiler optimisations enables some low-level code generation facilities in the compiler to make faster or smaller code based on assumptions about your code. The speed increases possible are irrelevant if your algorithm choice is poor, but for intensive computations this can make enough of a difference through Common Subexpression Elimination and Loop Unrolling, etc. Sometimes the assumptions made by the optimiser are incompatible with your code and so the optimiser has to be cranked down a notch. Compiler bugs in optimised code have also been a problem in the past.

3) Instrumented/Profiled build

Your code is built with specific instrumentation code to measure the number of times a function is called and how long is spent in that function. This compiler-generated code is written out at the end of the process for analysis. Sometimes it's easier to use a specialised software tool for this - see below. This type of build is never shipped.

4) Safe/Checked build

All the 'safety valves' are enabled via preprocessor symbols or compiler settings. For example, ASSERT macros check function parameters, iterators check for non-modified collections, canaries are put into the stack to detect corruption, heap allocations are filled with sentinel values (0xdeadbeef being a memorable one) to detect heap corruption. For
customers who have persistent problems that can only be reproduced on their site, this is a handy thing to have.

5) Feature build

If you have different customers that have differing requirements of your software product, it's common to make a build for each customer that exercises the different parts when testing. For example, one customer wants Offline functionality and another wants Online-only. It's important to test both ways if the code is built differently.

Logging and Tracing

So there's writing some helpful statements to printf() and then there's writing comprehensive, structured trace information to data files as you go. This information can then be mined to understand the runtime behaviour/characteristics of your software. If your code doesn't crash, or it takes some time to repro, it is helpful to have a picture of e.g. list of threads, their state transitions, memory allocations, pool sizes, free memory, number of file handles, etc. this really depends on the size, complexity and performance requirements of your application, but as an example, game developers want to ensure that there are no 'spikes' in CPU or memory use while a game is in progress as that will likely affect frame rate. Some of this info is maintained by the system, some by libraries and the rest by the code.

Other Tools

It's not always the case that you have to make a different build to cover these scenarios: some aspects can be chosen at runtime through process configuration (Windows Registry tricks), making alternate libraries available with higher priority to the standard libraries, e.g. efence on your loader path or using a Software ICE or specialised debugger to probe your software for runtime characteristics (e.g. Intel v-Tune). Some of these cost big money, some are free - dtrace, Xcode tools.


问:
When are scripts inside HTML not considered a bad practice?
I am new to web development. While studying the Play framework and JSP, I noticed that they both give an option to place script (in jsp scriptlet) inside HTML, but in both books I am reading they both say it is bad practice and don't give an explanation as to when should I use scripts, only writing not to.

My question is, if both frameworks supply such an option, when would it be ok to use scripts inside HTML?

Please note, I'm talking about server side scripts for creating dynamic HTML (i.e. JSP scriptlet).

答:
Never.  Mixing the presentation and business logic is a bad strategy for long term maintenance.  You should avoid it, and will eventually come to regret it in almost every case.

What changed is that the problems with that approach were noticed, and the world has generally moved to better, more robust solutions - but the Java folks care deeply about long term compatibility, so they keep this feature around in case it would make life more miserable for someone who depended on it.


问:
Software Licences Wizard
Is there a license "wizard" question system that asks you questions about how you would like to use the software, and then either allows you to compare it against one or more license types.

Background: In asking a question that requires the open source image recognition software to have a license commercial internal distribution without release of the source code even internal to all those who have the binary... I realized that the current answer using a GPLV2 license likely mean it's a bad fit. I'd like to make the question more clear by adding a list of licenses that are known to be a fit, and those that are not a fit, but I don't even have a clue as how to do that other than to ask if there's a wizard that will help do this.

答: From an answer given in this question, I think what you're looking for is the license differentiator from OSS Watch.</p>

Title: Software Licences Wizard


答:
There are mostly two reasons to put scripts outside HTML code:

Server-side, separation of concerns and clean code. You quickly understand why you must be very careful with that when you see some PHP code which, in the same piece of code, mixes PHP, SQL queries, JavaScript, HTML, CSS and Base64-encoded images embedded in CSS.

Client-side, external scripts are easily cached. If your HTML is a dynamic page, it may change often. By putting scripts outside HTML, you allow your visitors to download this content once, and never refresh it again (well, not never, but rarely). In the same way, if two static or dynamic HTML pages share the same script, putting it in an external file will allow to download it once.

▪ The first point is valid in all cases. You'll never be able to justify that it's cleaner to mix everything in one file. Why frameworks allow this? Because there are situations where you don't care about clean code:

If I write a small page I'll throw away for sure, and I must do it quickly, it's not so bad to put everything in one file.

If I want to show a short example to my colleague (by putting a single file to a document management system platform) or publish it to a blog¹, having everything in one file can be acceptable and useful too.

If I must create a small prototype before developing the application for a customer, best practices don't matter at all, while reducing cost is critical for source code which will be thrown in all cases.

▪ The second point, on the other hand, explains why there are perfectly valid cases to put scripts in HTML:

The script changes on every change of a dynamic page. In this case, why would you force the client to download the HTML file, then the separate file containing the script (i.e. doing two requests, which is a waste of time and resources which must not be neglected for the websites of some scale), while you can provide the same thing through one request?

The static HTML page uses the script which is not shared by any other page of the website. It's a perfect candidate too, if you want to avoid doing two requests².

Now, returning to the first problem (clean code), you can serve scripts in HTML and have clean code server-side (for example by using a template which will inject, at runtime, the script which is written separately). This, of course, requires some level of expertise, and as I said before, combining scripts and HTML is needed only on high-scale websites. This means that if you're seeing an inexperienced developer mixing scripts and HTML when doing a personal website, it's a good sign that something is wrong.

¹ Personally, I'm against this practice. More we share through our blogs code which does not follow best practices, more the less experienced developers would be encouraged to copy it and to believe that this is the right style.

² With appropriate caching configuration, two requests will happen only for users with empty cache. For others, you can set the expiration date for the far future, and the browser will avoid the request which will return the 304 Not Modified response.

Title: When are scripts inside HTML not considered a bad practice?

Body:
I am new to web development. While studying the Play framework and JSP, I noticed that they both give an option to place script (in jsp scriptlet) inside HTML, but in both books I am reading they both say it is bad practice and don't give an explanation as to when should I use scripts, only writing not to.

My question is, if both frameworks supply such an option, when would it be ok to use scripts inside HTML?

Please note, I'm talking about server side scripts for creating dynamic HTML (i.e. JSP scriptlet).


答:
Ask yourself some questions.

(or, as some may say, let's run together trough some scenarios)

How hard will it be for you to understand what you wrote?

Last week?

Last month?

Last year?

27 years from now?

How hard will it be for a coworker to understand what you wrote?

In the unfortunate event everybody on your team is unavailable, but a fix must get trough in hours, and the only guy available for the job is a summer intern, how likely is he to succeed?

And then:

how hard will it be to apply a security fix to a random chunk of code?

how hard will it be to change a logic misunderstanding of the requirements?

how hard will it be to take care of usability/UX/cosmetic issue?

how hard will it be to adapt to the ever changing legal landscape?

how hard will it be to push some new marketable features in?

how hard will it be to port the whole thing to a different architecture?

And the best of all:

how hard will it be to adapt the whole behemoth to a new set of requirements for a client with a similar needs, but...?

This is more or less what maintenance is about.
The latter is more about transforming the application into a product,
maybe, but that's a need that's pretty typical to raise, with time.

"Best Practices":

Comments

Documentation

Diagrams

Consistent indentation

Coding Patterns

Are all just meant to make your code survive longer.

Coding patterns, in particular, help maintenance by making code reading less and less of a discovery, and more and more of a "Oh yeah, I saw that already, so the part I'm looking for should be... around here".

They should, obviously, be used with caution and never be copypaste/abused just for the heck of it.

It's not LEGO, it's more of a source of inspiration.

Chances are if you cannot relate someone's usage of some pattern with advantages in maintainability, they are not using them right. But stay assured that as a way of comparing different solutions and permitting faster response times in case of maintenance, they are theoretically sound.

Title: What characteristics or features make code maintainable?

Body:
I used to think I knew what this was, until I really started thinking about it... "maintainable"... what exactly makes code maintainable?

To me, if code must be maintainable that means we can expect to revisit the code to make some sort of change to it in the future. Code is always "changeable" no matter what state it is in. So does this mean code needs to be easy to change? However, if our code was scalable/extensible, there would be no need to directly change it, because it will "change" (adapt) for free and automatically.

I've also seen code maintainability used interchangeably with coding standards. Using a consistent coding pattern or style, does this really make code more maintainable? More readable and more consistent? Sure, but how does this improve the maintainability?

The more I try to think into this, the more confused I get. Anyone have a proper explanation?


答:
Tools are sometimes supplied in such a way that they can be misused.
For instance - you shouldn't put your shoes on backwards even though "technically" it's possible. At first it might be cool, or if you're lazy it might save you some time, but down the road it will hurt you ... and the shoes ... think of the shoes!

Scripting inside web applications is a very common practice. But it does not lend itself to maintainable code or "future proof" code.

Some golden rules are keep the logic, view and data all separate.
When properly thought out - you should never need to actually script anything.

Down the road when you want to do unit testing...but your views contain logic...you will be kicking yourself after you realize you cannot make simple, common sense assertions.

Also - if someone looks inside a controller and expects to find logic and it's not there - they will be cursing your name when they have to hunt around the application for where you decided to stick it.

Scripting methods lend themselves to obfuscation and duplication.

-> You can play with it yourself in your spare time, do some projects from scratch and revisit them in a month.

-> You can learn the hard way and use scripting methods regardless of what others say.

-> You can save yourself some valuable time and focus on proper application architecture and design.

Remember, the web development industry is littered with the corpses of developers who refused to learn from people who had to mud through the trenches and save themselves some time and agony.


问:
Does long term programming affect writing in a native spoken languages?
So, I am getting some years under my belt in long term programming.  I have noticed, however, when the frequency and duration started increasing in my coding sessions that when I actually went to write a paper, email, document, or anything else that required writing more than a few sentences that my writing quallity appeared to suffer.  I started forgetting the basic rules and vocabulary of written English.

I am now going back for my Masters and find that writing papers does not come as easy as it used to.  I remember thinking to myself how my Creative Writing class back in my freshman year of college helped a great deal in writing for my other classes.  Hate to say it, but it feels like I could use a refresher.  Also, my hand writing has especially not got any better!  I feel inclined to say it's a side-effect of long term programming but want know any if real studies have been done or just from personal experience from programmers.

答:
My guess: it's not a side-effect of long-term programming in particular,

but a byproduct of a long period of not writing anything in natural language.

If you where good at creative writing, you should keep practicing that art.

Writing essays in other fields helps.

The skill you train while doing that is still natural language writing.

Writing programs doesn't.

Formal languages use a whole different set of synapses in your brain.

The natural-language ones, unfortunately, go stale.


问:
What can I do to help users create self-service reports?
I work using Reporting Services 2008 and I'm constantly creating ad-hoc reports. We'd like to use PowerPivot on Sharepoint but we're stuck on Sharepoint 2007. Using easy reporting software like Tableau Server would be fantastic but we can't afford it SSRS Report Builder hasn't proved to be very helpful, unfortunately.

I've been trying to think of ways to leverage Excel / PowerPivot or any other (free or inexpensive) tool. We just need to be able to provide more data to users so they can analyze on their own. This is an area our IT team as a whole needs to improve.

We use SSRS 2008 and SQL Server 2008. We also don't have a data warehouse, it's in the works...

答:
We have deployed a simple BI system using Excel / PowerPivot as the front end allowing users to build there own reports.

We wrote a User Manual (including a data dictionary) and provided the users with training, we dedicated a few of the more technical users as power users that field questions from the user base , if a power user need help he\she comes to us.

It's really not that bad, it takes a while for it to Click, but when it does they do fine.

Just do it.


问:
In Scrum, should tasks such as development environment set-up and capability development be managed as subtasks within actual user stories?
Sometimes in projects we need to spend time on tasks such as:

exploring alternate frameworks and tools

learning the framework and tools selected for the project

setting up the servers and project infrastructure (version control, build environments, databases, etc)

If we are using User Stories, where should all this work go?

One option is to make them all part of first user story (e.g. make the homepage for application). Another option is to do a spike for these tasks. A third option is to make task part of an Issue/Impediment (e.g. development environment not selected yet) rather than a user Story.

答:
At work we use a task for preparing the environment. It might be confusing for some people but the task we use is very much the same task as the task from a user story. The task does not belong to a user story but is estimated in hours and it has to be agreed on by the product owner to complete in a particular sprint.

We also use the task for architectural work that does not have an "apparent" business value but that adds quality to the product particularly for an existing product with a large code base.

These might not apply in your work environment but it worked well for us.


答:
Looking at this another way, All code is maintainable. The differentiating factor boils down to the effort required to maintain the code and the amount of technical debt the code represents in any given state.

Well factored code requires little effort to maintain, and when you do need to modify it will not impose a significant resourcing cost. Code that is difficult to read, too "clever" for its own good, poorly factored, or which does not suite the intention for which it was written, these are the types of code that incur higher costs to maintain, or to work-around if the cost:benefit makes it more expedient to avoid direct maintenance. Failing to maintain poor code greatly increases your technical debt, and increases the likelihood that the code will eventually be considered too costly to maintain.

Labeling code as maintainable vs un-maintanable can result in significant losses to your company, and can result in the stigma of project failure following its developers around like a bad smell for years. Changing the language to be more about effort, and less about the perception of maintainability can be more useful in the longer term, by helping to focus efforts on the problem before it becomes very difficult to manage.


问:
What is the difference between user stories and features?
Playing with icescrum, I realised that I do not understand the difference between user stories and user features.

Can someone explain the difference?

答:
A User Story is an informal statement in the language of the customer which captures the intent of something that the customer wishes to achieve.  You can think of a User Story as an Informal Requirement Statement.

A Software Feature is a distinct characteristic of the software that contributes to the overall design and functionality of the software.

A couple of key considerations:

A Story may describe a Feature, but a feature never describes a Story.

A Story might not directly describe a Feature.

A Story may imply the inclusion of a number of Features.

A Feature - either singly or as a member of a collection of Features - may capture the intent of a Story.

With all of this in mind, I tend to think of Stories as descriptions. Basically informal requirements which tell me what the customer wants. Features on the other hand I tend to think of more as a specification which tells me how a system should work in order to meet the customers requirements.

OwnerDisplayName: VJo


问:
Number of combinations
How to go about getting the number of combination ( C(5,4) ) without using recursion in C? Is there any other method or inbuilt library to do this?</p>

答:
What is wrong with using the formula:

n!/(k! (n-k)!).

You don't need recursion to calculate a factorial.

Title: Number of combinations


答:
You can avoid recursion and looping completely if an approximation is acceptable, you can use Stirling's Formula to approximate the answer.

Example

Option 1: Recursively or iteratively calculate factorial(n)

```<code>5! = 5x4x3x2 = 120
</code>```

Option 2: Use Stirling's Approximation

```<code>5! ~ sqrt(2*pi*5) * (n/e)^n = sqrt(10*pi) * (5/2.718281828)^5
                            = sqrt(31.41592654) *  (1.839397206)^5
                            = 5.604991216 * 21.05608437
                            = 118.019168 (close to 120)
</code>```

(Note: ~ means approximately and e is Euler's number defined 2.718281828)

This may seem silly because 5! is so small, but for a number like 100! the approximation works fairly well.

Large example, n = 100:

according to Google :

100! = 9.33262154 × 10^157

using Stirling's Approximation:

100! = 9.3224838328837612788449900430478 x 10^157

That's close enough for me :)

Title: Number of combinations

Body: How to go about getting the number of combination ( C(5,4) ) without using recursion in C? Is there any other method or inbuilt library to do this?</p>

Body:
You can avoid recursion and looping completely if an approximation is acceptable, you can use Stirling's Formula to approximate the answer.

Example

Option 1: Recursively or iteratively calculate factorial(n)

5! = 5x4x3x2 = 120

Option 2: Use Stirling's Approximation

5! ~ sqrt(2*pi*5) * (n/e)^n = sqrt(10*pi) * (5/2.718281828)^5
                            = sqrt(31.41592654) *  (1.839397206)^5
                            = 5.604991216 * 21.05608437
                            = 118.019168 (close to 120)

(Note: ~ means approximately and e is Euler's number defined 2.718281828)

This may seem silly because 5! is so small, but for a number like 100! the approximation works fairly well.

Large example, n = 100:

according to Google :

100! = 9.33262154 × 10^157

using Stirling's Approximation:

100! = 9.3224838328837612788449900430478 x 10^157

That's close enough for me :)


问:
How can I explain the difference between NULL and zero?
Working on a problem that uses the percent change formula:

```<code>percent change =  100 * [(new value - old value) / old value]
</code>```

How would I explain the difference if new value or old value = NULL, rather than 0 to someone who might not be a programmer?

My boss is wondering why there is an empty string in the TextBox rather than a value, because we have the old value, but not the new value.

答:
The person who -1ed this has no sense of humor. FWIW I am an Architect myself.

Null is emptiness. According to legend there are 17 flavors (possible meanings) of Null including "I dont know", "They didnt say", and "somebody broke this".
Nobody knows why except DBAs and Architects who scowl from dark back rooms at mere programmers. They smile politely at bosses and wag their tongues in deep concern with impossibly complex wisdom that must be so, and is deeply important but not very clear - because bosses deliver important performance to the DBA and Architect. A pay check. Even so Nulls never tell their secrets. They are black holes of empty.
One null never equals another null because each emptiness is empty of equality and refuses to admit that it might not be all the empty there is. This of course is conjecture because no self respecting null could ever actually admit it. Sometimes nulls suck vast quantities of real data into their (). This is called a bug but really is just the emptyness of the programmer's mind forgetting about nulls. So you see they do breed sometimes. But how or why is always quickly forgotten. () is sometimes a sign of a null or his cousin nil but paradoxically seldom a bug.

Zero is a definite quantity of something. Zeros are much happier than nulls. Zeros are merely lazy and dont add much to the outcome.

For the boring, very old accurate answer
Null is a representation of "missing information and inapplicable information" E.F. Codd, creator of SQL.

Codd also invented 3rd Normal Form which is applied to the minds of young Computer Scientists as a form of preliminary torture. Once mastered it is completely disregarded . Similar things happen when Object Oriented Design is introduced. And we are never happy to leave it alone, so along comes impedance mismatch to add to the frolicking fray.


问:
Should internal code be shared with non-developers in an organisation?
Where I work, we have a lot of developers and an awful lot of code running our proprietary applications used by staff & customers alike.

We also have a lot of smart support staff that like to understand the inner workings of our systems to better support our customers, and perhaps even submit a patch from time to time.

Should we open up our code for our non-development staff to be able to read?  What factors should we take into account when making this decision?  I have come across a bunch of arguments and counter-arguments each way & would like to make a decision based on the experience of others as well as well-understood risks.

Some arguments thus far:

Passwords in VCS are exposed (solution: get rid of the passwords - they shouldn't be there to begin with)

Code is open to white-box security attacks (counter-argument: this only keeps out the honest/lazy attackers)

Support staff can ask developers "how" things work (counter: teach a man to fish, etc)

Does anyone open their code to staff at their organisation?  Has it caused any problems?

答:
In general, from the organization point of view - people come and go; the project (or product) needs to continue to evolve. Hence, in most organization, there is usually an Open to all repositories for maintaining code.

Usually there are access rights etc. to prevent unnoticed unauthorized access (to prevent code theft etc.) but most higher ups are not really barred on this. Within an organization, one must trust people (enough) that you can trust them with code. Hiding code from employees (or colleague) is a great de-motivating factor.

In our organization, even when people don't really contribute to code - they have direct access to code that helps because they attempt to fight/fix the problems at field (with ownership) rather than dump things back to developer and go to sleep!


问:
If I wanted to build a search engine, how would I start?
Can somebody point me into the right direction? I really don't have experience writing code but I'm a fast learner. I'm not trying to say it will be easy but I hope somebody can help me...</p>

答:
Building a Search Engine

This is an introductory course to CS that's going to start on the 20th, I suggest you check it out, it's offered free of charge.


答: The freely distributed draft of Introduction to Information Retrieval is going to be your prime reference material. It handles search (information retrieval) from basic to advanced level.</p>

Title: If I wanted to build a search engine, how would I start?

Body: Can somebody point me into the right direction? I really don't have experience writing code but I'm a fast learner. I'm not trying to say it will be easy but I hope somebody can help me...</p>


问:
What is the best way to allow a client to contribute to a project?
We've been building a CRM for a client. Now that the first major phase has been finished, and a second one agreed upon, the client would like to pick up some of the work, making minor amendments to the database schema and business processes the first phase while we build the second.

I'm undecided whether this is at all practical, but assuming it is, I'd like some pointers on which measures can be taken to make this at all workable. Here's what I've got so far:

Until now, the client has mostly seen the project from a user's point of view; clearly, a two-part seminar ought to take place where we introduce him to the inner workings:

first, showing the existing database schema and, by way of example, extending it,

then, showing some sample code, and writing a new business process for the schema enhancement.

The code currently resides in an internal Subversion repository. While we could set up a public one or one on his network (which we can VPN to), I feel a distributed system would work better. I appear to be the only one who feels that way, however, so I could use some good convincing arguments.

I'm not sure how to mandate/ensure that code that runs in production is committed. Seems like "x made a critical, undocumented change right before going on vacation; now y's trying to figure out this bug that's been occurring ever since" disasters are inevitable. Ideally, all changes, before deployment, would:

be documented in an issue tracking system,

occur on a separate testing environment first, and

have to pass automated tests.

Alas, I doubt the discipline for any of those will prevail.

Assume that a plug-in architecture or separate project aren't viable options, because 1) the former doesn't exist, and 2) the latter would prohibit the client from looking at and possibly modifying existing code, an ability I believe he would insist on.

答:
This is going to be least favorite answer - but nevertheless here it is!

It is risky (as much as allowing a newbie to drive a brand new car) - but it is not a bad idea.

Understand why they want to do this: it is not that they have spare
  resources, it is only to make themselves feel under control.

What you need to do is following:

Educate your client - software is more than a code.
If they want to participate, let them first review architectural aspects, designs and so on. Raise questions to them and show them the implications of the choices they make a prior.

You should always go back with options about pro/cons on approaches (and document these meetings well) but you should allow them to take on some decision making. At least they will begin to appreciate that they don't know much - or will take ownership on themselves.

You can create separate space - such as branches so that they must be able to code whatever they want - things should be duly tested before commits or merges.

While i know complications might happen, every problem is an opportunity. If all goes well, your client will actually come to more appreciation about internal issues, and will develop a better trust because they know (how) you have done a good job!

PS: To give you an insight - i am from India; and i know great many IT shops where management doesn't really have much clue. They don't usually mind (even feel happy) that client puts additional resources to ensure that project doesn't go in dustbin! This works great for them; they all go with one mindset "Whatever you say sir!". This is not to demean my own countryman - but to show that joint development is not such a bad idea. It is after all, what many management gurus
portray is "Prosumer approach" to business problems.


问:
Can increased usage of higher and higher programming languages lead to a deficit of programmers with computer architecture knowledge?
Quote from Wikipedia of the article "High-level programming language":

A high-level programming language is a programming language with strong abstraction from the details of the computer. In comparison to low-level programming languages, it may use natural language elements, be easier to use, or be more portable across platforms. Such languages hide the details of CPU operations such as memory access models and management of scope.

I.e., as the level of programming language increases, the further away the programmer goes from the hardware on which the program runs.

Now I do not know the statistics of language usages across levels, but I would suspect that the higher level languages more and more are replacing the lower level languages. If so, can this lead to a deficit of programmers with computer architecture knowledge? Would this be a problem for the industry?

答:
No, it won't lead to a deficit of programmers with computer architecture knowledge. Languages are used to solve problems in a particular domain. If you want to solve a particular problem, you use the appropriate language or one good enough given your resources.

In reality, what domains actually need knowledge of the computer's architecture? That need to be tied down to a particular hardware architecture? Operating Systems? Device Drivers? Sure, but even then only parts of such code need specific architectural knowledge.

Performance improvement? Yes, you can apply knowledge of the computer's architecture to improve the performance of algorithms. But two other factors have a bigger impact on performance: the use of better algorithms and knowledge of the language's runtime environment.

In essence, more abstract programming languages solve problems for which details of the computer architecture isn't necessary. They allow more problems to be solved. The people that use them aren't using them to solve machine-dependent problems. People that need to solve machine-dependent problems will continue to use machine-capable languages. This isn't a zero-sum issue.


问:
Available options for classifying words in text?
I am researching ways to classify words in text and I'm wondering what options there are and which are best suited to this job. I'm mostly interested in keywords which are most often nouns.

So far I know I could use a Bayes classifier, blacklist, or whitelist. However, I haven't had the best of luck with each of these so far.

I started with a whitelist using the words provided by wordnet and moby to attempt to spot each noun. However, many words were missed as not existing in the database, or not being nouns.

Next I tried building a blacklist to match everything except known stop-words, verbs, and such. However, It would take a long investment of time to build a list large enough to handle the 200,000 known English (let alone other languages) words. In addition, keeping that many words in memory for comparison is not practical for performance on commodity hardware.

Using I have had luck with a bayes classifier matching spam and sentiment, but I'm not sure how to use it to tell nouns (or keywords) from other words since there are so many similarities between all the groups of words.

Last, I tried using regex to spot keywords based on proper nouns and names since they are always capitalized in English. The problem is that many keywords are not capitalized resulting in lacking results.

What other options exist for classifying keywords? What other design patterns could I use with the options above for better results?

答:
This is computational linguistics, and the book accompanying the open-
source Natural Language Toolkit, Natural Language Processing with
Python --- Analyzing Text with the
Natural Language Toolkit, is available as a paper book and free online.

Chapter five covers "part-of-speech tagging" or POS-tagging with the NLTK in detail, using Python dictionaries:

As we have seen, a tagged word of the
  form (word, tag) is an association
  between a word and a part-of-speech
  tag. Once we start doing part-of-speech
  tagging, we will be creating programs
  that assign a tag to a word, the tag which is most likely in a given context.
  We can think of this process as mapping from words to tags. The most natural way to store mappings in
  Python uses the so-called dictionary data type (also known as an associative array or hash array in other programming languages). In this
  section we look at dictionaries and see
  how they can represent a variety of
  language information, including parts
  of speech.

It also covers several methods of automatically tagging text to identify POS in text with unknown words.

Some other introductory books to computational linguistics have ben suggested at Linguistics.SE, where you can ask further questions on the topic.


答:
To calculate factorial for large numbers you can use a biginteger-library or arbitrary-precision library like http://gmplib.org/ or do it yourself (arbitrary-precision multiplication is easy, division not so) by using an array of unsigned ints.

Since you dont want to do it recursively, just iterate through the numbers from 1 to n, multiplying each of them into an biginteger you initialize with 1.

Then to calculate the number of combinations not permutations you calculate n!/k!/(n-k)!

Title: Number of combinations


答:
I don't think there is a general answer to this. Organisations differ wildly in their size, geographical spread, company culture, copyright policies, kind of software being developed, etc. etc. etc.

E.g. for a company developing commodity / infrastructure type of software, it may be easy to open up the source code, even to open source it, as Cisco did some years ago with their printer driver software (IIRC).

For a company developing some rare proprietary software, potentially including special algorithms or stuff which gives them competitive advantage over their competition, I can very well understand if they are striving to keep their code secret. E.g. AFAIK Google very strictly limits the number of people who are granted access their core search algorithm implementation.

Also a multinational organisation is nowadays spread over many countries, time zones and cultures, and for security reasons, they probably segment their intranet and use firewalls to control traffic between different segments / domains. So making an SCM repo accssible to "the whole company" may in fact require a lot of extra work for sysadmins, and extra security risk. While it doesn't usually bring any benefit in general, as employers working on a different continent on totally different stuff probably don't even know about our project over here, much less to contribute to it positively.

So if it makes sense within your department, and/or for people associated with the project in some way, why not. But in general, just for the sake of "openness", I am not quite sure it is worth it.

One final note: even when support people are smart and eager to contribute patches, I would say their contributions should always be reviewed by a developer before getting integrated into the system.

Title: Should internal code be shared with non-developers in an organisation?

Body:
Where I work, we have a lot of developers and an awful lot of code running our proprietary applications used by staff & customers alike.

We also have a lot of smart support staff that like to understand the inner workings of our systems to better support our customers, and perhaps even submit a patch from time to time.

Should we open up our code for our non-development staff to be able to read?  What factors should we take into account when making this decision?  I have come across a bunch of arguments and counter-arguments each way & would like to make a decision based on the experience of others as well as well-understood risks.

Some arguments thus far:

Passwords in VCS are exposed (solution: get rid of the passwords - they shouldn't be there to begin with)

Code is open to white-box security attacks (counter-argument: this only keeps out the honest/lazy attackers)

Support staff can ask developers "how" things work (counter: teach a man to fish, etc)

Does anyone open their code to staff at their organisation?  Has it caused any problems?


答:
Optimize the combination formula. If \binom{n}{r} is asked, first set r to be (r) or (n-r), whichever is smaller. Now use the normal shortcut method for finding combinations without calculating full factorials:

(n)(n-1)....(n-r+1)[r terms]/r!

Use Stirling's formula if the numbers are too large. You don't have to use recursion, for loops are more efficient (though less aesthetically pleasing) for factorials and continued products.

Title: Number of combinations


答:
In most organizations I have worked in, the code repository was open to all developers.

In some it was also used to store documents (such as specs and requirements) to version them alongside the software. In that case most other employees also had access. Where the repo was only used for code, non-devs usually did not have access - but I never heard anyone complain, so it was probably no big deal either way.

I would recommmend as much openness as possible - so if people want access, give it to them unless there is an obvious problem. But that really a question of the culture of the organization...


问:
Getting attention for my open sourced project

Possible Duplicate:

  How to promote an open-source project?

I've done quite a lot of work in my spare time on a project that was mostly for my own learning experience and I'm quite pleased with the results. I've used github as a source control management, so the code is already public in a sense. The code in question is a library that is quite specialized in it's application, and pretty well commented and understandable. It would probably be a good resource for students learning about the algorithms being used.

What I'm really looking for is the best way to see if there is any audience for what I've done. It's no big deal if there isn't but if there are I'd like people to know about my code, and find it if they are searching for something similar.

How to go about this task in the best way? I do have a blog and I intend to introduce the code there, but the audience is so far quite small - mostly co-workers and friends. I'm also unsure about going to specialized sites and advertise, especially as I'm not really part of a community around these types of libraries.

Any thoughts and ideas would be greatly appreciated! Thank you for reading.

Edit: I'm not sure if I should post a link to the project in question on github, or refrain. It's not my intention for this question to come off as advertising.

Also, it's amazing how I always find good links after I posted my question. http://producingoss.com/ seems like a good fit.

答:
I'd say you have to market your project:

Tweet about it

Blog about it

Do become part of the communities that use these libraries and ask their opinions, be active in these communities, give something to those communities (don't just take!)

Where you encounter people that have problems for which your project can provide a solution (forums, live encounters, tweets from people - search for certain hashtags, ...), provide them a link to your project

Put up a nice-looking site for your project, highlighting key features, documenting how to use it, providing examples, ... Github is ok to post code, but often a good looking site with good content can be more easily readable


问:
What should I learn more about debugging?
To debug my programs I mainly use the following methods:

Use printf (or equivalent in other languages) to check the value of a variable after a particular statement or to check whether the program enters a conditional statement or a loop.

Use watch/breakpoints when using IDEs.

I am able to solve the problems using the above methods. But I have noticed that there are two kinds of builds - debug and release. From the name I can understand that debug build would be helpful in debugging. Also I have read that debug build stores something called symbol table information and stuff.

How can I use the debug build for debugging? Are there any other debugging techniques which I should learn?

答:
There is one extremely powerful debugging technique, not mentioned yet in the other answers. It is available for free for some development environments, or can be added with a relatively little effor to nearly anything else.

This thing is an embedded REPL, preferably allowing to connect any time via a socket, running in a dedicated thread and able to use all the possible forms of reflection for the running code, modifying or completely replacing the running code, adding new things, running functions, etc.

You'll have it out of the box if you code in, say, Common Lisp, Smalltalk, Python, Ruby, etc. It is possible to embed a lightweight interpreter (say, Lua, Guile, JavaScript or Python) into a native application. For JVM or .NET-based environments there are many embeddable compilers and interpreters available, and quite a powerful reflection is there for free.

This approach is much more efficient than the interactive/iterative debuggers (such as gdb, visual studio debugger, etc.), and for the best results should be used in conjunction with a proper logging facility and properly placed assertions.


答:
I assume you can construct a simple function to calculate n! = nx(n-1)x(n-2)x...x1.
Now for large numbers, you may need to divide your algorithm as follows:

part1: when the input number has an acceptable value to be used with the formula above. I am not a C developer, so I can't tell you what is this value, for now we'll call it (L). For this case, you simply apply the above formula.

part2: When the input number is greater than the acceptable value L:The formula c(n,k) = nx(n-1)x(n-2)x....x(n-k)!/((n-k)!*k!) this can be simplified as:

c(n,k)=nx(n-1)x(n-2)x....x(n-k+1)/k! (see Related Answer)

this last equation involves smaller values than those in the original expression.

if k! in the above expression is less than or equal to L, then use the regular formula.

if k! > L or if nx(n-)x...x(n-k+1) > L you can use Sterling's formula as suggested by @Hunter McMillen

Title: Number of combinations


答:
You may still be subject to your employer's contract even if you haven't signed it - check what your local employment law says before doing anything rash. If that's the case, or you want to play it safe, you should follow the procedure in that.

If you're sure that you have no contractual obligations, you should still think twice before burning your bridges. You may need a good reference from your employer; you may end up working with some of your colleagues again in the future; your successor may be a violent psychopath; your boss may have powerful friends.

Without a contract, I'd give written notice of perhaps two weeks, and spend the time making a reasonable effort to tidy up and document my work. Separately, I'd discuss the reasons for leaving, but wouldn't complain about my boss (or anyone else) unless there was a serious problem with them. Mild incompetence is endemic in middle management, and the only effective paths are to subtly educate your boss, put up with it, or move on.

Also, make sure you have a new job lined up, or plenty of savings to live off. You may find that everywhere else you look is even worse...

Title: How do programmers quit a job?

Body:
I'm thinking about leaving my current employer and wondering how one goes about that process in the programming world. We have a lot of projects on the go at the moment and I'm the only developer. We have 4-5 projects that are fairly big and need to be done in the next few months and even a few longer than that.

I'm leaving because I'm the only employee and that's doing me no good. I'm young and want to learn, so a team would be nice. It's also too much work and the company is managed horribly.

I have no contract to worry about so I could theoretically quit and just not come back without notice. Just wondering how this is normally handled.

Should I write a resignation letter

How much notice should I give

Should I give a reason for leaving

Should I go to my boss who is the main reason I'm leaving or go to his boss?

Overview of replies

From the feedback here, it looks as though it's best to give 2-4 weeks of notice, and present a written resignation. Don't go into detail explaining why you're leaving in most cases. Don't burn bridges. Be professional.


答:
I do share a general/pragmatic view on this and may also depend on the nature of work/organisation as well. But I do believe that the code base should be open to all (will also show openess and trust within the organisation also).

I also work in a similar setup as you mentioned where we have a suppor/helpdesk team which deals with customer requests. However certain complex areas of the system they require addtional help. In my case the code base is open to all we have not encountered any problems.

I think by opening up the code base other support team members who are keen can also checkout the code base and get familiar with the business rules/area they are interested in or need to find answers (and possibly improve their technical understanding and looking at something different than the monotonous routine if time permits ;) ). This might also prove useful when support team members get customer issues and logs and would be able to point/assist on possible areas of the code where this happens by looking at the stacktrace e.g. (obviously will depend on the problem etc). This will also save time with the developer but depending on the problem of course.

Also having an up to date documentation/wiki of the product which contains all the business rules/decisions will also help. But of course you need to make sure that the wiki is constantly updated to relfect new enhancements and/or bug fixes (where behaviour changes). My honest thoughts


答:
As a first step, you must publish it in a easily downloadable place like GitHub or SourceForge. However, this is not all.

Second thing i would do is to publish it in forums where you may find similar minded people.

Best thing you need to become popular (or even being used) is NOT quite Advertise about it. Over time, when customers request comes, you must try to attend their feature demands. Remember, we all know Linus Torvald not because of the amount of marketing he did - but because he kept on evolving Linux (the hardway) during earlier days that majority people found it useful.

Best publicity of any product is when other people recommend and in Open source it is only possible when many people like to depend on your product and use it again.

Title: Getting attention for my open sourced project

Body:
Possible Duplicate:

  How to promote an open-source project?

I've done quite a lot of work in my spare time on a project that was mostly for my own learning experience and I'm quite pleased with the results. I've used github as a source control management, so the code is already public in a sense. The code in question is a library that is quite specialized in it's application, and pretty well commented and understandable. It would probably be a good resource for students learning about the algorithms being used.

What I'm really looking for is the best way to see if there is any audience for what I've done. It's no big deal if there isn't but if there are I'd like people to know about my code, and find it if they are searching for something similar.

How to go about this task in the best way? I do have a blog and I intend to introduce the code there, but the audience is so far quite small - mostly co-workers and friends. I'm also unsure about going to specialized sites and advertise, especially as I'm not really part of a community around these types of libraries.

Any thoughts and ideas would be greatly appreciated! Thank you for reading.

Edit: I'm not sure if I should post a link to the project in question on github, or refrain. It's not my intention for this question to come off as advertising.

Also, it's amazing how I always find good links after I posted my question. http://producingoss.com/ seems like a good fit.


答:
One thing to remember is that when you are building a web page to write it for users of the product not developers. I was looking at some video editing software for linux last week and the web page for one project put the fact that it was written in Python above the fold but I had to dig for the features. As a user I don't care that you write it in Python, Haskell or C# I care that it will solve some problem that I have. Of course for a Open source package you should put that somewhere, but in a development page.

I would write out a marketing plan for your program. If nothing else this is a really useful exercise for later. It does not have to be anything fancy just a guide for what you want to do and should include such things as blogging and tweeting, making a screen cast or whatever. Also it will impress someone in the future that you can write a marketing plan for some software that you have developed.


问:
Are Domain Objects in Domain Driven Design only supposed to be write-only?
I've been reading about Domain Driven Design for almost two years and have been cautiously been introducing some concepts in to my daily work or at least making plans for how things I do regularly could be done within a Domain Driven Design.

One conclusion that I've beginning to come to especially in response to reading more about Event Sourcing and Command Query Responsibility Segregation (CQRS) that perhaps domain objects are intended to be used only for write purposes. To be more clear, it seems that what people are subtly suggesting in much of the documentation I've read that the domain objects are responsible for doing domain centric operations/calculations, validation, and then are there mainly to provide a road to persistence through the infrastructure provided within a Repository implementation. Although I do like the fact that this may simplifies the domain model greatly as it cuts out the responsibility of exposing state.

If it is indeed correct that domain objects are mainly to be used as write-only objects then that raises some questions for me that I'm hoping somebody could answer.

How does one perform unit tests on an object that has setters, or methods that modify the state of an object but that provide no outwardly public interface to read the state from such as property getters in C#? Is it okay to expose state solely for the purpose of making that object testable?

How does one show to a user the results of calculations or operations done in the domain without having to persist them and then pull the results from persist store outside of the context of the domain? Is it okay to expose state solely for the purpose of showing results.

Is the rule of thumb that the only property getters (get accessors) should be ones that are also writable in the domain? Or said differently should readonly properties be the only thing to avoid since they are only there for read purposes and thus do not play a a necessary role in the actual domain model?

Related material:

TDD, DDD and Encapsulation

答:
Are Domain Objects in Domain Driven Design only supposed to be
  write-only?

No. CQRS can used alongside DDD.


答:
Use printf (or equivalent in other languages) to check the value of a variable after a particular statement or to check whether the program enters a conditional statement or a loop.

You should also use any kind of assert statement that's offered.

You should also write unit tests.

I am able to solve the problems using the above methods.

Perfect.  You know everything you need to know.

Are there any other debugging techniques which I should learn?

No.  Not that you should learn.  You may learn more if you think it will help.  But you don't need anything more than what you have.

For the last 30+ years, I've used a debugger only a few times (perhaps three or four).  And then, I've only used it to read post-mortem crash dumps to find the function call which failed.

Use of the debugger isn't an essential skill.  The print statement is sufficient.


答:
Judging by the variety of answers on this question, it can be concluded what we already know: null can mean many things.

Either it means the data is:

not known to be known,

known to be not known,

invalid (e.g. measuring error),

not accessible (e.g. security-wise),

known to be known but irrelevant for the current data processing

the data is infinite (often used in databases)

probably 10 more things I didn't think of

For this, and many other reasons, it is often useful to define a datastructure which encapsulates the meaning of the null value (e.g. an Optional class).

Title: How can I explain the difference between NULL and zero?

Body:
Working on a problem that uses the percent change formula:

```<code>percent change =  100 * [(new value - old value) / old value]
</code>```

How would I explain the difference if new value or old value = NULL, rather than 0 to someone who might not be a programmer?

My boss is wondering why there is an empty string in the TextBox rather than a value, because we have the old value, but not the new value.


答:
Licenses are usually more about what your rights and responsibilities are with regard to software derived from the licensed software, not whether the source code can be used in a commercial product or not.

It is perfectly possibly to sell a piece of software which uses a GPL library, as long as you are happy for people you have sold it to (who now have the source) to give it away.

Generally speaking though, for commercial software most people will want closed source, and for that you need a library with a permissive (or at least weak copyleft) license rather than a strong copyleft license. That way you don't need to release the source code to your product when you distribute the binaries.

In the license differentiator from OSS Watch that means choosing "I don't want to include licensing conditions on reuse" at Choice 2 (a):

Choice Two (a)

All Free and Open Source licences will allow others to make modified versions of your code, and to make these modified versions available to others. Your licence can make conditions about how this happens - specifically what licences can be used on these modified versions. These conditions can help keep your code free, but they can also put some people off reusing your code.

Alternatively, you could select "I want to include licensing conditions on reuse" at Choice 2 (a) but then select "Weak copyleft" at Choice 2 (b):

Choice Two (b)

This question is only if you chose to include licensing conditions on reuse.

You chose to include specific licensing conditions on reuse.

Sometimes these are called 'copyleft'. Copyleft comes in two basic varieties:

Strong Copyleft: When a software project contains some of your code, the project as a whole must be distributed under your licence, if it is distributed at all. The effect of this will be that the source code to all additions made to the code will be available.

Weak Copyleft: When a software project contains some of your code, the parts of the project you originated must be distributed under your licence, if it is distributed at all. Other parts may be distributed under other licences, even though they form part of a work with is - as a whole - a modified version of your code. The effect of this will be that the source code to some additions made to the code may not be available.
Which form of copyleft do you want?

A BSD licensed library like OpenCV can be pretty much used in any way you like, with some relatively minor restrictions. You can keep your application source code closed source, and distribute binaries without releasing your source code or any modifications you made to the library. That is what permissive means in practice.

Finally, don't assume that just because a project says GPL on it's website, that the copyright holders won't be prepared to license it to you under LGPL or commercial terms.

I once found that I could license a library (a simple comuter vision library) I was considering for $100 a year for unlimited run-time licenses! If I hadn't e-mailed the author directly, I would never have known.

Title: Software Licences Wizard

Body:
Is there a license "wizard" question system that asks you questions about how you would like to use the software, and then either allows you to compare it against one or more license types.

Background: In asking a question that requires the open source image recognition software to have a license commercial internal distribution without release of the source code even internal to all those who have the binary... I realized that the current answer using a GPLV2 license likely mean it's a bad fit. I'd like to make the question more clear by adding a list of licenses that are known to be a fit, and those that are not a fit, but I don't even have a clue as how to do that other than to ask if there's a wizard that will help do this.


答: Certainly they understand the concept of putting "N/A" on a form when they mean "not available".  For instance, to answer the question, "How old is Benjamin Franklin?" the answers 0 and N/A are obviously different (and the latter one is correct).  Similarly the answers 0 and NULL are different.</p>


问:
Interacting With Data Using Multiple Databases/Servers
All of the projects that I've had to deal with so far have only required a single database on a single server. I'm interested in learning more about how projects that need to scale move to  multiple databases and/or servers to help manage the load. I'm aware of High Scalability, but I'm particularly interested in some code examples or additional resources where I could read more on the subject.

For instance:

How are joins constructed between two tables on multiple databases? (A code example here would be helpful).

Are there any special strategies for tracking which tables are in which database?

Does the application code need to know that one or more databases are spread across multiple servers? If not, at what level are the requests filtered?

When is it time to move beyond a 1 database/1 server setup? How common is it to need to do this?

答:
There is a new SQL (ACID) database in beta that is claimed to have elastic scaling properties. There is a free beta program going on now and I suggest you have a look, it's called NuoDB.

Apparently it easily outperforms MySQL even on a single threaded machine, but scales happily to 70+ instances in certain benchmarks.


问:
Delegates and events
What is the difference between

```<code>public delegate void SecondChangedHandler(Object clock, TimeInfoEventArgs ti);
public event SecondChangedHandler OnSecondChanged;
</code>```

and

```<code>public event EventHandler<TimeInfoEventArgs> OnSecondChanged;
</code>```

When should you use which and is there any best practice?

答: There is no difference indeed. Then EventHandler<T> (msdn) has just been added as a "shortcut" to avoid having to redeclare the delegate.

Title: Delegates and events


答: Before generics the first approach was the only option to declare an event handler delegate. Since generics were introduced in .NET 2.0, EventHandler<T:EventArgs> is the preferred way. Semantically there is no difference between them.

Title: Delegates and events

Body:
What is the difference between

```<code>public delegate void SecondChangedHandler(Object clock, TimeInfoEventArgs ti);
public event SecondChangedHandler OnSecondChanged;
</code>```

and

```<code>public event EventHandler<TimeInfoEventArgs> OnSecondChanged;
</code>```

When should you use which and is there any best practice?


问:
Removing the "integration test scam" - Understanding collaboration and contract tests
I've recently watched Integration Tests are a Scam by J. B. Rainsberger and am now looking for more material on the subject. I have to say, I'm shocked by how much we're doing wrong, (i.e. integration testing when we should unit test), intrigued by the concepts described by Rainsberger but also confused about how to apply them. I would like to have more of the described collaboration tests and contract tests but I don't know where to start.

The only things that got stuck in my mind are the 4 questions the tests need to ask:

Side A:

```<code>Do I ask the right question?
Can I deal with the answer?
</code>```

Side B:

```<code>Can I answer a question?
Do I answer correctly?
</code>```

But how do I apply this to some random method in my application stack?

Is there a book or a tutorial or example out there that takes a real world example and applies these ideas of isolated micro tests?
Ideally the example uses Java, Spring + PowerMock / Mockito / EasyMoock

Any literature that deals with these concepts in general and helps me understand them better would be appreciated.

Also if there are forums out there where I can ask more detailed questions about how to go about correctly unit testing and maybe even refactoring existing code and post examples would be nice.

Thanks!

Edit - some additional thoughts:

Is there a general rule, when to use a mock and when a stub to isolate a class under test from it's collaborators? Can it be applied to the 4 questions?

The best mocking frameworks seems to be PowerMock, allowing me to precicely define for each test what class I want to have mocked and what it should return or is there anything better that you have used to ask the above questions? Are there good tutorials out there that use PowerMock to apply some or all of the given principles to some part of a real world application stack, say a DAO or a GUI?

Edit 2 - an example

Just some example of the kind of methods I want to test and my thoughts..

I have a web service that saves orders. At this stage we're not too worried about the best security, so to have some, the service will also take a username and password to authenticate the save request. Once authenticated, the OrderManager is called to save the Order. Internally the manager decides if its a new order so it has to be created or an existing one that has to be updated. (That shouldn't matter to the WebSerice, right?)

```<code>@WebService
public class OrderService {
    @Inject
    private AuthenticationManager authenticationManager;

    @Inject
    private OrderManager orderManager;

    public void save(String username, String password, Order order) {
        authenticationManager.authenticate(username, password);
        try {
            orderManager.save(orde);
        } finally {
            authenticationManager.logout();
        }
    }
</code>```

Now I am wondering: What exactly am I testing here? I'm thinking there should be tests for authentication success and failure and for order saving success and failure.

But how can I split that up into the 4 questions? My class under Test is obviously OrderService (OS) and the collaborators are OrderManager (OM) and AuthenticationManager. (AM)
So I have the following tests, please correct me here, I am just thinking aloud:

OS <--> OM

OS asks OM to save an order (what kind of different parameters do I test here? null and Order? Does it matter if Order is correctly initialized?)

OM answers a save call by calling some other internal method, I I test if that method gets invoked?!

OS should not fail if OM does not fail

OS should fail if OM fails

... What else?

And then of course OS <--> AM:

OS asks AM to authenticate - I guess I test how the AM reacts to different kinds of username / password?

...

Now my first conclusion:

As far as the WebSerice is concerned I can only test 2 out of 4 questions: Side A. Now I have to look at the OrderManager and AuthenticationManager and see if they can answer the questions of side B. Right?

Secondly - database access:

Authentication and Order persisting obviously requires some data in the database in a production environment. For my unit tests however I won't need them so I'll just mock the calls to return the desired result, right? But how do I mock this?

I need the AuthenticationManager.authenticate to pretty much do nothing, as in case of a failed authentication it will throw an Exception, else it has the return type void. How do I tell my OrderService.save() to use my mocked AuthenticationManager.authenticate()?

And how do I set the AuthenticationManager up to either do nothing or throw an exception?

Can I tell Spring to inject a mocked AuthenticationManager that will do nothing / throw an Exception into my OrderService under test?

答:
That is a really long question and I apologize but I only skimmed the additional thought parts.

I can recommend two excellent books:

The Art of Unit Testing

xUnit Test Patterns

They don't use the exact frameworks you mentioned but the advice they give you is very valuable and easily applies to any scenario with OOD.  Both go into great detail of how to setup unit tests to isolate just the component being tested and how to set up mock/fake/stub objects to remote dependencies.

UPDATE (Response to below comment):

This answer is in response to OP's:

"I would like to have more of the described collaboration tests and contract tests" - contract tests are unit tests because OP wants to remove integration tests, and instead, test individual components against a well defined interface for that component.  That is unit testing and precisely what those books are about.

"...where I can ask more detailed questions about how to go about correctly unit testing and maybe even refactoring existing code"

"Is there a general rule, when to use a mock and when a stub to isolate a class under test from it's collaborators?" - Both those books deal very heavily with setting up mock objects and using them properly

"Is there a book or a tutorial or example out there that takes a real world example and applies these ideas of isolated micro tests?" - Yes, this is called Unit Testing and the two books I listed are great at explaining this.

As OP pointed out, integration tests cause have many issues because they tend to become very complex and hard to write very fast, good alternative is unit test and testing each class in isolation against their public interfaces.  In addition to unit tests, both of those books discuss integration testing as well and mention where it should and should not be used.

Furthermore, after skimming OP's question some more, it seems a lot of uncertainty revolves specifically around the use of mock objects and both of those books really do focus on how to properly use mock objects (although they don't mention Spring or specific mock frameworks)


问:
How to structure an application which reads UPC barcodes
I have no previous experience on creating a project for a seller which will use barcode reader. I am trying to put together a small project but I cannot figure out how the pieces should glue together.

I will create a sample with Motorola Scanner SDK to read barcodes and from that point, I have couple of questions:

How UPC barcodes work in general? AFAIK, a barcode stores the manufacturer and product info but no price data.

Should I store price information inside a database which corresponds to barcode data?

I would really appreciate if you can guide me here.

答:
Essentially the BarCode reader is an input device, not much different then your keyboard.

A UPC is one type of bar code. A bar code is series of lines where the width of each line determine the number. Some lines act as the standard line width unit, so the bar code can be any size, it the relative size that matters).

The BarCode is simply a device friendly way of representing numbers, you could replace a bar code scanner with an OCR device and print the numbers on the box, but bar code has a major befit over OCR where you don't have to worry about the orientation of the bar code.

All the scanner is doing is reading a Number and "Typing" into the computer system (You could just as well type the number in the same input box). Everything else is handled by the App.

The Barcode does NOT Store any data except for a single ID that your system has to handle. If your system has the wrong data mapped to the bar-coded ID, the wrong data is retrieved.


问:
Using Django without a database
Is Django a good solution for creating applications that won't use any database and communicate only through an internal API? </p>

答:
Although there is nothing stopping you from not using a DB in Django, my advice would be: "If you don't need a full stack framework, don't use a full stack framework". Python has many excellent microframeworks that might suit your needs better.

This blog post discusses some of them: http://www.konstruktor.ee/blog/python-web-framework-roundup

My personal favorite is Flask: http://flask.pocoo.org/, but I have not done much real work with it.

Title: Using Django without a database


问:
How to store record statuses (like pending, complete, draft, cancelled...)
Quite a lot of applications require records in their tables to have a status, such as 'complete', 'draft', 'cancelled'. What's the best way of storing these statuses? To illustrate what i'm getting at here is a *very short) example.

I have a simple Blog application and each post has a status one of: published, draft or pending.

The way i see it there are 2 ways to model this in the database.

The Post table has a text field that includes the status text.

The Post table has a status field that contains the ID of a record in the PostStatus table

The Blog example here is a very simple example. Where an enum (if supported) might suffice. However i'd like responses to the question to take into account that the list of statuses could change at any time, so more could be added or removed.

Can anyone explain the advantages/disadvantages of each?

Cheers!

My initial optnion on this is that its better to use another table and look up the status as its better for normalisation and i've always been taught that normalisation is good for databases

答:
Storing the status text is IMO not a good idea, since someone might decide that "complete" should be called "finished" instead and then you have to update your database, look through the program if someone hardcoded the text etc.

What I have seen in many programs is either a numerical code (1=new, 2=draft, 3=in validation, 4=complete, 99=cancelled) or a short alphanumerical code ("NEW", "DRA", "INV", "COM", "CAN"). The later makes the code (in the program or in the database) more human-readable, which is generally a good thing. On the other hand, numerical codes make it easy to do "greater than" or "smaller than" comparisons, for example

```<code>select * from myrecords where status < Status.Complete;
</code>```

Body:
Storing the status text is IMO not a good idea, since someone might decide that "complete" should be called "finished" instead and then you have to update your database, look through the program if someone hardcoded the text etc.

What I have seen in many programs is either a numerical code (1=new, 2=draft, 3=in validation, 4=complete, 99=cancelled) or a short alphanumerical code ("NEW", "DRA", "INV", "COM", "CAN"). The later makes the code (in the program or in the database) more human-readable, which is generally a good thing. On the other hand, numerical codes make it easy to do "greater than" or "smaller than" comparisons, for example

select * from myrecords where status < Status.Complete;