答:
The general structure of a recursive function is something like this:

```<code>myRecursiveFunction(inputValue)
begin
   if evaluateBaseCaseCondition(inputValue)=true then
       return baseCaseValue;
   else
       /*
       Recursive processing
       */
       recursiveResult = myRecursiveFunction(nextRecursiveValue); //nextRecursiveValue could be as simple as inputValue-1
       return recursiveResult;
   end if
end
</code>```

The text that I marked as /*recursive processing*/ could be anything. It could  include a loop, if the problem being solved requires it, and could also include recursive calls to myRecursiveFunction.

Body:
The general structure of a recursive function is something like this:

myRecursiveFunction(inputValue)
begin
   if evaluateBaseCaseCondition(inputValue)=true then
       return baseCaseValue;
   else
       /*
       Recursive processing
       */
       recursiveResult = myRecursiveFunction(nextRecursiveValue); //nextRecursiveValue could be as simple as inputValue-1
       return recursiveResult;
   end if
end

The text that I marked as /*recursive processing*/ could be anything. It could  include a loop, if the problem being solved requires it, and could also include recursive calls to myRecursiveFunction.


问:
Equivalent of SOLID principles for functional programming
I've found the SOLID principles quite useful when thinking about object-oriented design.

Is there a similar / equivalent set of language-agnostic principles tailored for functional programming?

答:
SOLID turns out to be a good idea for the functional/imperative realms too.

SRP - 'Only do one thing' was taken from imperative programming in the first place. Having small, focused functions is good.

OCP - Allowing you to change behaviors without modifying code is good. Functional programming uses higher order functions more than inheritance, but the principle holds.

LSP - Abiding by some interface contract is just as good in functional programming as in object oriented. If a sort function takes a comparator, then you would expect the '0 is equals, less than provides negative results, greater than positive results' behavior.

ISP - Most functional languages still have structs. Specifying the smallest set of data required by a function is still good practice. Requiring the least specific interface to the data (why use Lists of ints when Enumerations of T work just as well?) is still good practice.

DIP - Specifying parameters to a function (or a higher order function to retrieve them) rather than hard coding the function to go get some value is just as good in functional programming as in object oriented.

And even when doing object oriented programming, many of these principles apply to the design of methods in the objects too.

ContentLicense: CC BY-SA 3.0


问:
design a model for a system of dependent variables
I'm dealing with a modeling system (financial) that has dozens of variables.  Some of the variables are independent, and function as inputs to the system; most of them are calculated from other variables (independent and calculated) in the system.

What I'm looking for is a clean, elegant way to:

define the function of each dependent variable in the system

trigger a re-calculation, whenever a variable changes, of the variables that depend on it

A naive way to do this would be to write a single class that implements INotifyPropertyChanged, and uses a massive case statement that lists out all the variable names x1, x2, ... xn on which others depend, and, whenever a variable xi changes, triggers a recalculation of each of that variable's dependencies.

I feel that this naive approach is flawed, and that there must be a cleaner way.  I started down the path of defining a CalculationManager<TModel> class, which would be used (in a simple example) something like as follows:

```<code>public class Model : INotifyPropertyChanged
{
    private CalculationManager<Model> _calculationManager = new CalculationManager<Model>();

    // each setter triggers a "PropertyChanged" event
    public double? Height { get; set; }
    public double? Weight { get; set; }
    public double? BMI { get; set; }

    public Model()
    {
        _calculationManager.DefineDependency<double?>(
            forProperty: model => model.BMI,
            usingCalculation: (height, weight) => weight / Math.Pow(height, 2),
            withInputs: model => model.Height, model.Weight);
    }

    // INotifyPropertyChanged implementation here
}
</code>```

I won't reproduce CalculationManager<TModel> here, but the basic idea is that it sets up a dependency map, listens for PropertyChanged events, and updates dependent properties as needed.  I still feel that I'm missing something major here, and that this isn't the right approach:

the (mis)use of INotifyPropertyChanged seems to me like a code smell

the withInputs parameter is defined as params Expression<Func<TModel, T>>[] args, which means that the argument list of usingCalculation is not checked at compile time

the argument list (weight, height) is redundantly defined in both usingCalculation and withInputs

I am sure that this kind of system of dependent variables must be common in computational mathematics, physics, finance, and other fields.  Does someone know of an established set of ideas that deal with what I'm grasping at here?  Would this be a suitable application for a functional language like F#?

Edit

More context:

The model currently exists in an Excel spreadsheet, and is being migrated to a C# application.  It is run on-demand, and the variables can be modified by the user from the application's UI.  Its purpose is to retrieve variables that the business is interested in, given current inputs from the markets, and model parameters set by the business.

答:
A cleaner way (depending on your usage pattern) is to not store the value of BMI. Just have a getter that looks at its dependencies and calculates the result when accessed. This is much better if the inputs are changed much more than the outputs are read.

That still leaves you with updating the UI when the state of a property (and/or its dependencies) changes. For some UIs a full refresh will be fine since almost everything is changing anyways. If not, then you're likely building your own graph (hopefully via reflection or attribute marking) and firing change events (hopefully not by hand) to the UI. I've done this for a similar setup and it actually works really well, though not in a high-change environment like financial modelling.


问:
Should cookies be used in a RESTful API?
I'm specifically interested in how users perform authorized / authenticated operations on a web API.

Are authentication cookies compatible with the REST philosophy, and why?

答:
One can use cookies. REST allows them.

REST requires that any session information be stored on the client side, but when it comes to authentication, some information has to stay on the server side for security reasons.

From one of my blog posts, there is a general agreement that authentication data is considered out of scope regarding REST. Hence, it is ok for servers to keep some of this session data on their side.


问:
How to manage and estimate unstructured requirements received from customers
A lot of the times during the bidding phase of a project I receive a software system's requirements from our potential customers in a very unstructured format from various sources [email, word documents, excel]. It is usually a bunch of "product development" guys from the customer's side who come up with these "proposed solutions" to the business problems they have. While they are the experts at the business domain, a lot of the times they don't have the solutions right.

This results in

multiple versions of the same requirement

mixing up of two requirements into one

a few versions of the requirement later down the line, the
requirements which were combined together get separated out again,
each taking with it some of the new additions

How do you work with such requirements coming in and sort them out into proper use cases and before development begins? What tools can we use to track a particular requirement's history, from the first time it was conceived till the time it gets crystallized into a proper use case? Estimating work against requirements received in such a fashion is a nightmare which ends up in making mistakes in understanding the requirement correctly and estimating the effort against it correctly.

Once we win the project, then the customers have given some more thought to their requirements and have been able to articulate it properly. What happens in this case is that some functionality gets dropped, some enhanced, some take a whole new turn. This basically can nullify some of the work item's estimates that were made before the project was won. I would be interested in knowing if there is any system by which we can build a tree of a particular requirement and how each branch resulted in a different estimate.

Any tips, tools, tricks to make this activity more manageable? I'm just trying to get some insights from someone more experienced than I am in requirements management and effort estimation.

答:
Requirements will grow and change.  I don't think anyone could argue that.

How to collect and process incoming requests.

In my experience it helps when gathering requirements if there is a single or very small group of customers acting as a filter for delivering new or updated requirements to a small group of development planners.  Anyone from their side can propose or write them up, but delivery should be through only a very small few.  The less people that are involved in the exchange from one party to the other, the better.

The purpose of filtering through a smaller set of people isn't to discard or diminish the effort and information others put in, even if duplicate or seemingly unimportant on the surface, but to limit points of failure: lost or mishandled information.  It follows on a principle similar to the purpose of encapsulation and interfaces: protect private data, and establish a common protocol for handling similar requests.  Let me reiterate: submission of duplicates is ok.  As a planner, that tells me the thing they are talking about or proposing is important. Save or record everything.

How to track and organize requirements

In the short term, go low tech

Obviously there are low tech solutions that can be effective to a large degree in organizing and tracking incoming requirements: whiteboards, stickies, posterboards, what have you.  These can be great for short term planning.  They are highly visible, accept freeform notation, and easy to 'reconfigure'.

In the long term, use a searchable, sortable, linkable software tool

For longer range efforts, some kind of software would be valuable.  There are specialized requirements management tools: Doors, Clearcase/Clearquest, and many others.  Those highly specialized tools are great at what they do, but are often overkill.  Sometimes even a plain old spreadsheet is more than adequate.  I personally find general issue tracking systems fairly useful to accomplish this, and right now my favorite is redmine, but others I am sure would be fine too.

With an issue tracking system, anyone you choose to allow can create a 'new issue' or requirement, and add any detail they see fit to include.  They can watch the issue, and give feedback to any actions you take with it.  You can re-categorize it, adjust priority, rewrite the body, attach supplemental information, associate it with other 'issues', promote to a higher level feature or 'use case' or story or whatever terminology fits your system, ad nauseum.  In other words, you can do a lot to create a traceable, sortable, prioritized, history-aware, related list of requirements via issues.  Plus being fairly configurable out of the box, and open-source, if the tool isn't quite what I need or want at any point, I can change it fairly easily to better fit the needs of my process.

A final note about tools, some people I have talked with have a good deal of success using plain old text files in a change management and versioning system.  They obviously get the benefits of historical versions.  They also utilize the base operating system and supplementary tools for finding, linking, and cataloging the requirements.  They aren't able to add as much structured, related meta information, but they don't feel they need it, and for their efforts doesn't add enough value.  That may or may not be the case for you.  The advantage is that is potentially a few less pieces of software on your development stack to manage and maintain.

Post contract award/post project development kickoff requirements

The final aspect of the question, is how to manage requirements after an effort has begun.  I think there are two leading thoughts on this, and part of how you handle them depends on the nature of your relationship with the customer: firstly, if under contract at a fixed value, requirements that come in after contract award can be incorporated. The implication is they may change the scope of the effort, so the rate or bill will be higher when those extra items are delivered and accepted; unless an equivalent amount of effort is removed from the accepted proposal.  If it is going to a change in scope, you must ensure the customer understands and accepts the consequence, otherwise, those late submissions will have to be tabled.

Second, for the new requirements coming in after the contract is awarded, and the contract is oriented more towards a time and material effort (whatever it takes to get the body of work completed), you can and should be a bit more flexible if the customer insists on including it during that particular go.  You will get paid whether you include it or not, so long as everything you say you will do gets done.

If you aren't familiar with them, you may want to look at a Kanban approach and Agile methods.  These techniques can help bring focus to the immediate concerns, without necessarily losing sight of longer term development goals.

Present options as 'what if' scenarios and give the customer a choice and the decision

In either case, a 'what if' estimate is a good strategy to employ when negotiating with the customer and your team.  Construct a side-by-side comparison of the tasks, their costs, and the schedule as planned, with a column showing the same information for the alternative approaches.  Microsoft Project is probably a good candidate for doing this as you can construct different estimates based on a largely similar set of tasks.

However, even a basic spreadsheet is often just as effective for demonstrating how specific changes or inclusions would impact the cost and schedule.  A list in this case is probably just as effective as a tree might be in demonstrating the differences.  The tool and method you choose to construct these scenarios largely depends on the size of the project and staff (but even triple A software like MS Project has its own limits of usefulness and ability).

Consider these what if scenarios as internal work items and save them for the duration of the project.  They were critical demonstrations in the decision making and negotiation process.  You may also have to revisit them, or repeat them for a successive round of what ifs.

When preparing what if scenarios, a supplementary explanation of pro's and con's from a technical or implementation perspective (in simplified terms) might be useful for helping to justify why one alternative would have such a significant impact.


问:
Using nested public classes to organize constants
I'm working on an application with many constants. At the last code review it came up that the constants are too scattered and should all be organized into a single "master" constants file. The disagreement is about how to organize them. The majority feel that using the constant name should be good enough, but this will lead to code that looks like this:

```<code>public static final String CREDITCARD_ACTION_SUBMITDATA = "6767";
public static final String CREDITCARD_UIFIELDID_CARDHOLDER_NAME = "3959854";
public static final String CREDITCARD_UIFIELDID_EXPIRY_MONTH = "3524";
public static final String CREDITCARD_UIFIELDID_ACCOUNT_ID = "3524";
...
public static final String BANKPAYMENT_UIFIELDID_ACCOUNT_ID = "9987";
</code>```

I find this type of naming convention to be cumbersome. I thought it might be easier to use public nested class, and have something like this:

```<code>public class IntegrationSystemConstants
{
    public class CreditCard
    {
        public static final String UI_EXPIRY_MONTH = "3524";
        public static final String UI_ACCOUNT_ID = "3524";
        ...
    }
    public class BankAccount
    {
        public static final String UI_ACCOUNT_ID = "9987";
        ...
    }
}
</code>```

This idea wasn't well received because it was "too complicated" (I didn't get much detail as to why this might be too complicated). I think this creates a better division between groups of related constants and the auto-complete makes it easier to find these as well. I've never seen this done though, so I'm wondering if this is an accepted practice or if there's better reasons that it shouldn't be done.

答:
Both approaches work, and that's what's important at the end of the day.

That said, your approach is common enough to be considered a pattern, or more accurately a good enough improvement over the constant interface anti-pattern. I don't see what's complicated about it, but that's a discussion you should have with your team.


答:
One of the challenges with the long list of constants is finding the "correct" constant to be using.  Invariably, someone tacks a constant in at the end of the line instead of adding it to the group it belonged to.

Which brings up another point to discuss with your team - there already is a de facto categorization of the constants through their names.  So it really shouldn't be a big shift for them from current state to what you're proposing.  Using auto-complete makes constant look-ups even easier.

If anything, your suggestion helps discourage using the "wrong" constant even though it might fit in a particular situation.  By wrapping the constants within a representative class, it will encourage the developers to think through if they should be using it.  For example, if I pull CreditCard.SomeConstant for general usage, I really should wonder why there isn't a General.SomeConstant for that situation instead.

I've been on projects with monster amounts of constants, and I would have preferred to have the method you're suggesting.  It's cleaner, more direct, and it helps avoid inadvertent usage.

Title: Using nested public classes to organize constants

Body:
I'm working on an application with many constants. At the last code review it came up that the constants are too scattered and should all be organized into a single "master" constants file. The disagreement is about how to organize them. The majority feel that using the constant name should be good enough, but this will lead to code that looks like this:

```<code>public static final String CREDITCARD_ACTION_SUBMITDATA = "6767";
public static final String CREDITCARD_UIFIELDID_CARDHOLDER_NAME = "3959854";
public static final String CREDITCARD_UIFIELDID_EXPIRY_MONTH = "3524";
public static final String CREDITCARD_UIFIELDID_ACCOUNT_ID = "3524";
...
public static final String BANKPAYMENT_UIFIELDID_ACCOUNT_ID = "9987";
</code>```

I find this type of naming convention to be cumbersome. I thought it might be easier to use public nested class, and have something like this:

```<code>public class IntegrationSystemConstants
{
    public class CreditCard
    {
        public static final String UI_EXPIRY_MONTH = "3524";
        public static final String UI_ACCOUNT_ID = "3524";
        ...
    }
    public class BankAccount
    {
        public static final String UI_ACCOUNT_ID = "9987";
        ...
    }
}
</code>```

This idea wasn't well received because it was "too complicated" (I didn't get much detail as to why this might be too complicated). I think this creates a better division between groups of related constants and the auto-complete makes it easier to find these as well. I've never seen this done though, so I'm wondering if this is an accepted practice or if there's better reasons that it shouldn't be done.


问:
What's so difficult about SVN merges?

Possible Duplicate:

  I’m a Subversion geek, why should I consider or not consider Mercurial or Git or any other DVCS?

Every once in a while, you hear someone saying that distributed version control (Git, HG) is inherently better than centralized version control (like SVN) because merging is difficult and painful in SVN.  The thing is, I've never had any trouble with merging in SVN, and since you only ever hear that claim being made by DVCS advocates, and not by actual SVN users, it tends to remind me of those obnoxious commercials on TV where they try to sell you something you don't need by having bumbling actors pretend that the thing you already have and works just fine is incredibly difficult to use.

And the use case that's invariably brought up is re-merging a branch, which again reminds me of those strawman product advertisements; if you know what you're doing, you shouldn't (and shouldn't ever have to) re-merge a branch in the first place.  (Of course it's difficult to do when you're doing something fundamentally wrong and silly!)

So, discounting the ridiculous strawman use case, what is there in SVN merging that is inherently more difficult than merging in a DVCS system?

答:
Yes, I do that too. I currently have 12 VMs for different versions
  (branches) of the project I'm part of at work. When I have to fix a
  bug in an older version, I fix the bug, then merge that commit into
  the branches for newer versions. But that's now re-merging an entire
  branch, which is what I'm talking about here.

Here lies one of the very nice things about git. It's not inherit about DVCS, it's just something git excels at. You can merge specific revisions from any branch into another branch. It basically just takes the diff and applies it to the other branch, but does tracking and is much more automatic.

So, if you have branch 2.0 and branch 3.0 and discover a bug in 2.0, you can then fix it in 2.0 and take the set of revisions which resolve it and merge only those revisions into the 3.0 branch. I don't believe SVN has any way to do this other than manually taking the diffs for each revision and applying them

Of course, the auto-merge algorithm also appears to work a lot smoother and git was built from the ground up on the "make a branch for all the things" model, so branching is just really smooth and easy in it. It just seems natural to branch often with how lightweight it's branches are

Title: What's so difficult about SVN merges?


答:
You are right.  Your suggestion allows a programmer to import static Constants.BankAccount.* and eliminate countless repetitions of 'BANKACCOUNT_'.  Concatenation is a poor substitute for actual scoping.  That said, I don't hold out a lot of hope for you to change the team culture.  They have a notion of proper practices, and aren't likely to change even if you show them 100 experts that say they are wrong.

I'm also wondering why you have a single 'Constants' file at all.  This is very bad practice, unless these constants are all related somehow and are very stable.  More typically it becomes a kind of kitchen-sink class that changes constantly and is depended on by everything.


答:
if you know what you're doing, you shouldn't (and shouldn't ever have to) re-merge a branch in the first place. (Of course it's difficult to do when you're doing something fundamentally wrong and silly!)

And therein lies the source of your confusion and the whole problem in general.

You say that merging branches is "fundamentally wrong and silly". Well, that's exactly the problem: you're thinking of branches as things that shouldn't be merged. Why? Because you're an SVN user who knows that merging branches is hard. Therefore, you never do it, and you encourage others to not do it. You have been trained to avoid merging; you've developed techniques that you use to avoid merging.

I'm a Mercurial user. Even on my own projects, where I'm the only developer, I merge branches all the time. I have a release branch, which I put a fix into. Well, I merge that back into the main-line so that the fix goes there.

If I were using SVN, I would adopt a completely different structure of the codebase. Why? Because SVN makes merges hard, and therefore you develop idioms and techniques to avoid doing complex merges.

DVCS's make complex merges easy because they are the default state. Everything is a branch, more or less, in a DVCS. So the entire structure of them is built from the ground up to make merging easier. This allows you to develop a workflow that uses merging on a daily basis, rather than the SVN workflow where you never use merging.

The simple fact is this: you should approach a DVCS in a different way than SVN. You should use the proper idioms for these very different kinds of version control systems. In SVN, you adopt idioms that don't involve merging because merges are hard. In DVCS's, you adopt idioms that frequently use merges because they're no big deal.

Right tool for the right job.

The thing is, the merge-focused workflow is a lot nicer and easier to use than the SVN-style workflow where you don't merge things. It's easier to see when something from the release branch was brought into the dev branch. It's easier to see the various interplay between branches. It's easy to create test branches for things, then clip them off if the test doesn't work. And so on.

Really, Joel explains this a lot better than I can. You should have a good read of that.

Title: What's so difficult about SVN merges?

Body:
Possible Duplicate:

  I’m a Subversion geek, why should I consider or not consider Mercurial or Git or any other DVCS?

Every once in a while, you hear someone saying that distributed version control (Git, HG) is inherently better than centralized version control (like SVN) because merging is difficult and painful in SVN.  The thing is, I've never had any trouble with merging in SVN, and since you only ever hear that claim being made by DVCS advocates, and not by actual SVN users, it tends to remind me of those obnoxious commercials on TV where they try to sell you something you don't need by having bumbling actors pretend that the thing you already have and works just fine is incredibly difficult to use.

And the use case that's invariably brought up is re-merging a branch, which again reminds me of those strawman product advertisements; if you know what you're doing, you shouldn't (and shouldn't ever have to) re-merge a branch in the first place.  (Of course it's difficult to do when you're doing something fundamentally wrong and silly!)

So, discounting the ridiculous strawman use case, what is there in SVN merging that is inherently more difficult than merging in a DVCS system?

ContentLicense: CC BY-SA 4.0


问:
Software licensing and code generation
I'm developing a tool that generates code from some various data. The tool itself will be licensed with the MIT license, which strikes a good balance for me in terms of allowing the freedom to use and modify it, while still holding the copyright.

OK, but what is the legal status of the code generated by the tool? Who holds the copyright for code generated by a tool? Do I need to give users of the tool a license for the generated code, or do they already have that by virtue of it being generated by them?

What is different about this code generation system (which may be relevant) is that the source information about the code generation is provided by the system itself. The user doesn't feed source data in; the source data is bundled along with it. They simply have the means to transform it in various ways (filtering out parts of the data they don't want, etc). Obviously they could edit the bundled data. Does that affect anything about this?

答:
I don't know too much about your tool, but it sounds similar to what the "bake" utility in CakePHP framework does. The CakePHP bake command similarly builds an entire working application using some non-code input from the user.

This is the CakePHP license:

CakePHP is licensed under the MIT license. This means that you are
  free to modify, distribute and republish the source code on the
  condition that the copyright notices are left intact. You are also
  free to incorporate CakePHP into any Commercial or closed source
  application.

IANAL, but I think that the license that applies to CakePHP could possibly apply to your tool as well.

Title: Software licensing and code generation


答: I've done a fair bit of SVN merging -- including having long running development and release branches. By and large I survived. Merging is always tricky, but with DCVS the downside is not horribly bad -- everything is local so just update to a known good revision and keep going. Whereas with SVN alot happened on the server side so recovery was ugly -- usually it involved wiping out the local copy then checking out a new clean branch to try it again. Wasn't bad in my case -- a gigabit connection to the SVN box helps. But we had some contractors who had lots of trouble with this as they were on slow connections so anything took forever, including merges.</p>

Title: What's so difficult about SVN merges?


答:
I don't agree with either of the two proposals.

Constants should be in their pertinent classes, not in an all-constant class in either of the two forms proposed.

There shouldn't be constants-only classes/interfaces.

A class CreditCard (not an internal class) should exist. This class/interface has methods relative to credits cards as well as the constants UI_EXPIRY_MONTH and UI_ACCOUNT_ID.

There should exist a class/interface BankAccount (not an internal class). This class/interface has methods relative to bank accounts as well as constant UI_ACCOUNT_ID.

For example in the Java API every class/interface has its constants. They are not in a Constants class/interface with hundreds of constants, either grouped into inner classes or not.

For example, these constants pertinent to result sets are in the interface ResultSet:

```<code>static int  CLOSE_CURSORS_AT_COMMIT
static int  CONCUR_READ_ONLY
static int  CONCUR_UPDATABLE
static int  FETCH_FORWARD
static int  FETCH_REVERSE
static int  FETCH_UNKNOWN
static int  HOLD_CURSORS_OVER_COMMIT
static int  TYPE_FORWARD_ONLY
static int  TYPE_SCROLL_INSENSITIVE
static int  TYPE_SCROLL_SENSITIVE
</code>```

This interface has method signatures relative to result sets, and implementing classes implement that behavior. They are not mere constant-holders.

These constants pertinent to UI actions are in the interface javax.swing.Action:

```<code>static String   ACCELERATOR_KEY
static String   ACTION_COMMAND_KEY
static String   DEFAULT
static String   LONG_DESCRIPTION
static String   MNEMONIC_KEY
static String   NAME
static String   SHORT_DESCRIPTION
static String   SMALL_ICON
</code>```

Implementing classes have behavior relative to UI actions, they are not mere constant holders.

I know at least one "constants" interface (SwingConstants) with no methods but it doesn't have hundreds of constants, just a few, and they are all related to directions and positions of UI elements:

```<code>static int  BOTTOM
static int  CENTER
static int  EAST
static int  HORIZONTAL
static int  LEADING
static int  LEFT
static int  NEXT
static int  NORTH
static int  NORTH_EAST
static int  NORTH_WEST
static int  PREVIOUS
static int  RIGHT
static int  SOUTH
static int  SOUTH_EAST
static int  SOUTH_WEST
static int  TOP
static int  TRAILING
static int  VERTICAL
static int  WEST
</code>```

I think constants only classes are not good OO design.

Body:
I don't agree with either of the two proposals.

Constants should be in their pertinent classes, not in an all-constant class in either of the two forms proposed.

There shouldn't be constants-only classes/interfaces.

A class CreditCard (not an internal class) should exist. This class/interface has methods relative to credits cards as well as the constants UI_EXPIRY_MONTH and UI_ACCOUNT_ID.

There should exist a class/interface BankAccount (not an internal class). This class/interface has methods relative to bank accounts as well as constant UI_ACCOUNT_ID.

For example in the Java API every class/interface has its constants. They are not in a Constants class/interface with hundreds of constants, either grouped into inner classes or not.

For example, these constants pertinent to result sets are in the interface ResultSet:

static int  CLOSE_CURSORS_AT_COMMIT
static int  CONCUR_READ_ONLY
static int  CONCUR_UPDATABLE
static int  FETCH_FORWARD
static int  FETCH_REVERSE
static int  FETCH_UNKNOWN
static int  HOLD_CURSORS_OVER_COMMIT
static int  TYPE_FORWARD_ONLY
static int  TYPE_SCROLL_INSENSITIVE
static int  TYPE_SCROLL_SENSITIVE

This interface has method signatures relative to result sets, and implementing classes implement that behavior. They are not mere constant-holders.

These constants pertinent to UI actions are in the interface javax.swing.Action:

static String   ACCELERATOR_KEY
static String   ACTION_COMMAND_KEY
static String   DEFAULT
static String   LONG_DESCRIPTION
static String   MNEMONIC_KEY
static String   NAME
static String   SHORT_DESCRIPTION
static String   SMALL_ICON

Implementing classes have behavior relative to UI actions, they are not mere constant holders.

I know at least one "constants" interface (SwingConstants) with no methods but it doesn't have hundreds of constants, just a few, and they are all related to directions and positions of UI elements:

static int  BOTTOM
static int  CENTER
static int  EAST
static int  HORIZONTAL
static int  LEADING
static int  LEFT
static int  NEXT
static int  NORTH
static int  NORTH_EAST
static int  NORTH_WEST
static int  PREVIOUS
static int  RIGHT
static int  SOUTH
static int  SOUTH_EAST
static int  SOUTH_WEST
static int  TOP
static int  TRAILING
static int  VERTICAL
static int  WEST

I think constants only classes are not good OO design.


答:
The Free Software Foundation addresses this in their FAQ

Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free?

In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.

So the only way you have a say in the use of the output is if substantial parts of the output are copied (more or less) from text in your program. For instance, part of the output of Bison (see above) would be covered by the GNU GPL, if we had not made an exception in this specific case.

You could artificially make a program copy certain text into its output even if there is no technical reason to do so. But if that copied text serves no practical purpose, the user could simply delete that text from the output and use only the rest. Then he would not have to obey the conditions on redistribution of the copied text.

I believe this applies to any Copyrighted work not just GPLed code.  The output is not typically a derived work unless it includes substantial parts of the copyrighted work.

That said if the source data is under the MIT license and is included verbatim in the output then the output may be covered by the MIT license as a derivative work, but if the source data is transformed in substantial ways then the output would probably not be covered as a derivative work.

Title: Software licensing and code generation

Body:
I'm developing a tool that generates code from some various data. The tool itself will be licensed with the MIT license, which strikes a good balance for me in terms of allowing the freedom to use and modify it, while still holding the copyright.

OK, but what is the legal status of the code generated by the tool? Who holds the copyright for code generated by a tool? Do I need to give users of the tool a license for the generated code, or do they already have that by virtue of it being generated by them?

What is different about this code generation system (which may be relevant) is that the source information about the code generation is provided by the system itself. The user doesn't feed source data in; the source data is bundled along with it. They simply have the means to transform it in various ways (filtering out parts of the data they don't want, etc). Obviously they could edit the bundled data. Does that affect anything about this?


答:
it came up that the constants are too scattered and should all be organized into a single "master" constants file.

This is the 100% wrong solution to the problem of constants being "hard to find". It's a fundamental error (unfortunately all too commonly perpetrated by programmers) to group things by technical criteria like being constants, enums or interfaces.

Except for layer architectures, things should be grouped by their domain, and constants all the more so since they are very low-level elements. Constants should be part of the classes or interfaces that use them as part of their API. If you can't find a natural place for them to live, you need to clean up your API design.

Additionally, a single huge constants file kills development speed in Java because constants are inlined into the classes that use them at compile time, so any change forces a recompilation of all those files and all that depend on them. If you have one file with constants that are used everywhere, you largely lose the benefit of incremental compilation: watch Eclipse lock up for 15 minutes as it recompiles your entire project for every change to that file. And since that file contains all constants used anywhere, you'll be changing it quite often. Yes, I am speaking from personal experience.


答:
It's because svn lacked the proper data structures to accurately determine the latest common ancestor of the two branches.  That's not a big deal for a branch that is only merged once, but can cause a lot of erroneous merge conflicts in situations where several branches are merged multiple times.

I don't follow svn very closely, but my understanding is those particular technical issues have been fixed in recent versions.  However, it wasn't fixed early enough to dispel the myth, and people who tried DVCS for the merges have stuck with it for other reasons.

Title: What's so difficult about SVN merges?


问:
Unable to debug an encodded javascript?
I’m having some problems debugging an encoded javacscript. This script I’m referring to given in this link over here.

The encoding here is simple and it works by shifting the unicodes values to whatever Codekey was use during encoding.  The code that does the decoding is given here in plain English below:-

```<code><script language="javascript">
function dF(s){
var s1=unescape(s.substr(0,s.length-1)); var t='';
for(i=0;i<s1.length;i++)t+=String.fromCharCode(s1.charCodeAt(i)-s.substr(s.length-1,1));
document.write(unescape(t));
}
</script>
</code>```

I’m interested in knowing or understanding the values (e.g s1,t). Like for example when the value of i=0 what values would the following attributes / method would hold

```<code>    s1.charCodeAt(i) and s.substr(s.length-1,1)
</code>```

The reason I’m doing this is to understand as to how a CodeKey function really works. I don’t see anything in the code above which tells it to decode on the basis of codekey value. The only thing I can point in the encoding text is the last character which is set to 1 , 2 ,3 or 4 depending upon the codekey selected during encoding process. One can verify using the link I have given above.

However, to debug, I’m using firebug addon with the script running as localhost on my wamp server. I’m able to put a breakpoint on the js using firebug but I’m unable to retrieve any of the user defined parameters or functions I mentioned above.

I want to know under this context what would be best way to debug this encoded js.

EDIT

@blueberryfields Thanks for the neat code review.

However, to clarify this is no homework its something i picked from a website about encoding and javascript.The material just looked interesting and decided to give it a go. I don't see the point of using the intermediate variables as I was hoping to make use of those already define (s1,t,i). Usually these variable types are seen in firebug way too often like the enumerable types. Beside, using a good breakpoint and the right place i can always step over these values in the loop.

I changed my focus as someone on stackexchange told me to use dragonfly (opera) as i did I was able to retrieve the variable and their values with the breakpoint statement. For other values i just did document.write to get desired results. Here is the link of the screenshot.

link.

I was more interested in understanding the part of coding that actually tell the program to shift-back the unicode character based upon code key value. That part of code was s.substr(s.length-1,1). He just extracted the last character which is the codekey number and then use it in calculating the matching charcode value.

If you unescape this shift-1 code %264DTDSJQU%2631MBOHVBHF%264E%2633kbwbtdsjqu%2633%264F%261Bbmfsu%2639%2638Ifmmp%2631Xpsme%2638%263%3A%264C%261B%264D0TDSJQU%264F%261B%261%3A%261%3A%261%3A1 you would get &4DTDSJQU&31MBOHVBHF&4E&33kbwbtdsjqu&33&4F&1Bbmfsu&39&38Ifmmp&31Xpsme&38&3:&4C&1B&4D0TDSJQU&4F&1B&1:&1:&1:1 Although those last chars not required but were intentionally added so it helps in decoding.

答:
To figure out how this code works, I would recommend expanding it, and assigning intermediate local variables to store various results, so you can watch how they change as you step through.

Before assuming that you're looking at you're looking at user defined parameters or functions, you might want to look the functions up in a standard library. If you do look them up, you'll notice all the functions used are standard library functions for Javascript.

For example, with the code you've got, I'd do something like this:

```<code>function dF(s) {
    var s1 = unescape(s.substr(0, s.length - 1));
    var t = '';
    for (i = 0; i < s1.length; i++) {
        var cCode = s1.charCodeAt(i);
        var key = s.substr(s.length - 1, 1);
        var temp= String.fromCharCode( cCode - key );
        t += temp;
    }
    var unescaped = unescape(t);
    document.write(unescaped);
}
</code>```

NOTE:

This question smells a lot like a homework question. It's generally frowned upon to ask us to do your homework for you, and it's usually good form to at least warn that it's homework you're doing.

Title: Unable to debug an encodded javascript?

Body:
To figure out how this code works, I would recommend expanding it, and assigning intermediate local variables to store various results, so you can watch how they change as you step through.

Before assuming that you're looking at you're looking at user defined parameters or functions, you might want to look the functions up in a standard library. If you do look them up, you'll notice all the functions used are standard library functions for Javascript.

For example, with the code you've got, I'd do something like this:

function dF(s) {
    var s1 = unescape(s.substr(0, s.length - 1));
    var t = '';
    for (i = 0; i < s1.length; i++) {
        var cCode = s1.charCodeAt(i);
        var key = s.substr(s.length - 1, 1);
        var temp= String.fromCharCode( cCode - key );
        t += temp;
    }
    var unescaped = unescape(t);
    document.write(unescaped);
}

NOTE:

This question smells a lot like a homework question. It's generally frowned upon to ask us to do your homework for you, and it's usually good form to at least warn that it's homework you're doing.


问:
How does one handle an incorrect resource file?
I'm starting the parser that will handle one of the key features of my app and realizing exactly who easy it would be for me to screw up a resource file that is provided to the application. For example, a simple resource that I provide to my app is a JSON file that contains an entity layout (name, fascia, location etc...). It would be easy for me to leave out the name of the entity or misspell the JSON key.

Obviously catastrophic failures during parsing are to be handled in a try/catch, but how would subtle failures (such as a dyslexic spelling of name) be handled?

答:
How would subtle failures (such as a dyslexic spelling of name) be
  handled?

Unit testing.  I don't know what language you are using, but JUnit works great in Java and Scala.  You are writing something that takes in some kind of input and produces JSON?  Start by making a test that feeds it a known good input file and checks to see that the output is exactly what you want.  Once you have a few tests written, you can change your code and have run the test to have a sense that the basic functionality that was there before is still working.

Another possible solution is to make your application that reads the JSON really good at reporting errors, deciding when to reject input vs. continue processing after an error is encountered (fatal and non-fatal errors), and correcting for small common mistakes.


答:
I do this occasionally (in C#), particularly if I need to program against / parse a well-known and fixed XML structure or something similarly nested and string heavy...for instance a custom config block parser.

I build out a nested class structure matching the hierarchical structure of the XML w/ the class names corresponding to the elements containing a const string "ElementName" property and a similar property corresponding to each Attribute (if any).

It makes it very easy to program against the corresponding Xml.


答:
What's the difference between a "catastrophic failure during parsing" and a "dyslexic fail" (say a , instead of a ;, or a ' instead of a " - those two pairs of symbols are on neighboring keys on my keyboard), fundamentally, from the end-user's* point of view?

If the JSON** is malformed due to a typo, giving a good error message is usually not trivial because from the parser's point of view, the (catastrophic) error might not be where the actual error is from a human point of view. So, in my opinion, the case you're "dismissing" as a technical detail is the hard one to deal with.

If you have a valid JSON file, but missing (or extraneous) properties, giving a good error message (i.e. failing the right way) is comparatively trivial: just tell the user what you're expecting that's not there, or doesn't have the right kind of value. You can make that even easier to the user if you state in the error message things like "keys are case-sensitive" or "dates must be entered in dd/mm/yyyy format" or whatever is relevant.

How you technically implement that will depend on the language, but keeping a list of mandatory and optional parameters (with their value types and default values) is not technically challenging - you could, in fact, do that with a JSON file that would be used both as input to your parser and as a source for your docs.

Build and maintain that list, and you're done. Have a few testcase resources and make sure your parser (and "constructors") fails hard (at least during automated tests) when a mandatory property is missing, or yields a big warning if an unknown property is present (not in that list).

If you add mandatory properties to your code, but forget to update that list, your testcases will tell you – either by the parser detecting that, or the "constructors" yelling at you because they're missing data. Same thing if you change names or value types.

*You phrased your question in such a way that you seem to be the end-user. But if that resource loading is a key feature of your app, keep in mind that there will hopefully be many more people playing with that.

**Substitue any format here.

Title: How does one handle an incorrect resource file?

Body:
I'm starting the parser that will handle one of the key features of my app and realizing exactly who easy it would be for me to screw up a resource file that is provided to the application. For example, a simple resource that I provide to my app is a JSON file that contains an entity layout (name, fascia, location etc...). It would be easy for me to leave out the name of the entity or misspell the JSON key.

Obviously catastrophic failures during parsing are to be handled in a try/catch, but how would subtle failures (such as a dyslexic spelling of name) be handled?


问:
Can a recursive function have iterations/loops?
I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function).

However, while surfing the web for examples (the 8-queens-recursive problem), I found this function:

```<code>private boolean placeQueen(int rows, int queens, int n) {
    boolean result = false;
    if (row < n) {
        while ((queens[row] < n - 1) && !result) {
            queens[row]++;
            if (verify(row,queens,n)) {
                ok = placeQueen(row + 1,queens,n);
            }
        }
        if (!result) {
            queens[row] = -1;
        }
    }else{
        result = true;
    }
    return result;
}
</code>```

There is a while loop involved.

... so I'm a bit lost now. Can I use loops or not?

答:
Recursive calls and loops are just two ways / constructs to implement an iterative computation.

A while loop corresponds to a tail-recursive call (see e.g. here), i.e. an iteration in which you do not need to save intermediate results between two iterations (all the results of one cycle are ready when you enter the next cycle). If you need to store intermediate results that you can use again later you can either use a while loop together with a stack (see here), or a non tail-recursive (i.e. arbitrary) recursive call.

Many languages allow you to use both mechanisms and you can choose the one that better suits you and even mix them together in your code. In imperative languages like C, C++, Java, etc. you normally use a while or for loop when you do not need a stack, and you use recursive calls when you need a stack (you implicitly use the run-time stack).
Haskell (a functional language) does not offer an iteration control structure so you can only use recursive calls to perform iteration.

In your example (see my comments):

```<code>// queens should have type int [] , not int.
private boolean placeQueen(int row, int [] queens, int n)
{
    boolean result = false;
    if (row < n)
    {
        // Iterate with queens[row] = 1 to n - 1.
        // After each iteration, you either have a result
        // in queens, or you have to try the next column for
        // the current row: no intermediate result.
        while ((queens[row] < n - 1) && !result)
        {
            queens[row]++;
            if (verify(row,queens,n))
            {
                // I think you have 'result' here, not 'ok'.
                // This is another loop (iterate on row).
                // The loop is implemented as a recursive call
                // and the previous values of row are stored on
                // the stack so that we can resume with the previous
                // value if the current attempt finds no solution.
                result = placeQueen(row + 1,queens,n);
            }
        }
        if (!result) {
            queens[row] = -1;
        }
    }else{
        result = true;
    }
    return result;
}
</code>```

Body:
Recursive calls and loops are just two ways / constructs to implement an iterative computation.

A while loop corresponds to a tail-recursive call (see e.g. here), i.e. an iteration in which you do not need to save intermediate results between two iterations (all the results of one cycle are ready when you enter the next cycle). If you need to store intermediate results that you can use again later you can either use a while loop together with a stack (see here), or a non tail-recursive (i.e. arbitrary) recursive call.

Many languages allow you to use both mechanisms and you can choose the one that better suits you and even mix them together in your code. In imperative languages like C, C++, Java, etc. you normally use a while or for loop when you do not need a stack, and you use recursive calls when you need a stack (you implicitly use the run-time stack).
Haskell (a functional language) does not offer an iteration control structure so you can only use recursive calls to perform iteration.

In your example (see my comments):

// queens should have type int [] , not int.
private boolean placeQueen(int row, int [] queens, int n)
{
    boolean result = false;
    if (row < n)
    {
        // Iterate with queens[row] = 1 to n - 1.
        // After each iteration, you either have a result
        // in queens, or you have to try the next column for
        // the current row: no intermediate result.
        while ((queens[row] < n - 1) && !result)
        {
            queens[row]++;
            if (verify(row,queens,n))
            {
                // I think you have 'result' here, not 'ok'.
                // This is another loop (iterate on row).
                // The loop is implemented as a recursive call
                // and the previous values of row are stored on
                // the stack so that we can resume with the previous
                // value if the current attempt finds no solution.
                result = placeQueen(row + 1,queens,n);
            }
        }
        if (!result) {
            queens[row] = -1;
        }
    }else{
        result = true;
    }
    return result;
}


问:
What is the best objective way to measure language popularity trends? (What's better than TIOBE?)
The best way to get data on computer language popularity that I know is the TIOBE index.  But everyone knows that TIOBE is hopelessly flawed.  (If someone provides a link to support this, I'll add it here.)

So is there any data on programming language popularity that is generally considered meaningful?  The only other option I know is to look at the trends at indeed.com, which is inherently flawed, being based on job postings.

It isn't like I would make a future language decision solely based on an index, but it might provide a useful balance to the skewed perspective one obtains by talking to ones friends and colleagues.

To illustrate that bias, I'll point out that based on the experience of those I personally know, the only languages used professionally today (in order of popularity) are Java, C#, Groovy, JavaScript, Ruby, Objective C, and Perl.  (Though it is evident that C, C++ and PHP were used in the past.)

So my question is, everyone bashes TIOBE, but is there anything else?  If so, can anyone explain how we know the alternative has better methodology?  Thanks.

答:
Google trends is another one you can use.

There's no 100% correct answer or source of data in this space.  The best you can do is aggregate data from various sources and come up an accurate as possible conclusion from that.

ContentLicense: CC BY-SA 2.5


答:
The "create an smaller version of the problem" part can have loops. As long as the method calls itself passing as a parameter the smaller version of the problem, the method is recursive. Of course an exit condition, when the smallest possible version of the problem is solved and the method returns a value, must be provided to avoid an stack overflow condition.

The method in your question is recursive.

Title: Can a recursive function have iterations/loops?

Body:
I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function).

However, while surfing the web for examples (the 8-queens-recursive problem), I found this function:

```<code>private boolean placeQueen(int rows, int queens, int n) {
    boolean result = false;
    if (row < n) {
        while ((queens[row] < n - 1) && !result) {
            queens[row]++;
            if (verify(row,queens,n)) {
                ok = placeQueen(row + 1,queens,n);
            }
        }
        if (!result) {
            queens[row] = -1;
        }
    }else{
        result = true;
    }
    return result;
}
</code>```

There is a while loop involved.

... so I'm a bit lost now. Can I use loops or not?


问:
Why is the code section called a text section?
The section of an executable that contains code is sometimes called the .text section. In segmented memory architectures, a segment mapped as code is sometimes called a text segment. The unix error message “text file busy” (ETXTBSY) means “this file is a program that is being executed”.

How did text come to mean executable (machine) code?

 An ideal answer would:
explain the connection between the word and its meaning;
provide a citation for the origin or at least the history of the term;
give some idea of which communities use it.

答:
The term comes from assembly language.  I can't verify the etymology, but my guess is that the name comes from the other use of the section.  Whereas the .data section denotes variables that can change during the course of execution, the .text section contains data that doesn't change during execution, allowing it to be put into ROM if needed.  That makes it useful for code, yes, but also makes it useful for strings of text that don't change.  That's probably where the term came from.

To address Griffin's comment about first class functions, consider the following python 3 code:

```<code>def counter():
    x = 0
    def increment(y):
        nonlocal x
        x += y
        print(x)
    return increment
</code>```

The code you actually execute for increment ends up looking internally something like:

```<code>self.func_dict['x'] += y
print(self.func_dict['x'])
</code>```

That executable code can be put into ROM.  It never changes throughout the execution of the program, no matter how many times you call counter().  What does change is the self pointer and its member variables.  Those must be put into .data.  When you return increment, you are actually returning a new instance of an increment function object.  You are not dynamically creating new executable code every time.  The code itself is immutable even though the pointer to it is not.

The only code that must be stored in the .data section is that generated by eval(), because it is not known to the compiler or JIT compiler at the start of the program.  However, even that code is immutable.  If you change the string and call eval() again, you're not changing the code from the previous time you called eval(), you're creating a whole new set of code.

Although the programming model may make it kind of feel like code is mutable, actual self modifying code at the processor instruction level is dangerous and rarely found outside OS voodoo topics like process context switching.

Body:
The term comes from assembly language.  I can't verify the etymology, but my guess is that the name comes from the other use of the section.  Whereas the .data section denotes variables that can change during the course of execution, the .text section contains data that doesn't change during execution, allowing it to be put into ROM if needed.  That makes it useful for code, yes, but also makes it useful for strings of text that don't change.  That's probably where the term came from.

To address Griffin's comment about first class functions, consider the following python 3 code:

def counter():
    x = 0
    def increment(y):
        nonlocal x
        x += y
        print(x)
    return increment

The code you actually execute for increment ends up looking internally something like:

self.func_dict['x'] += y
print(self.func_dict['x'])

That executable code can be put into ROM.  It never changes throughout the execution of the program, no matter how many times you call counter().  What does change is the self pointer and its member variables.  Those must be put into .data.  When you return increment, you are actually returning a new instance of an increment function object.  You are not dynamically creating new executable code every time.  The code itself is immutable even though the pointer to it is not.

The only code that must be stored in the .data section is that generated by eval(), because it is not known to the compiler or JIT compiler at the start of the program.  However, even that code is immutable.  If you change the string and call eval() again, you're not changing the code from the previous time you called eval(), you're creating a whole new set of code.

Although the programming model may make it kind of feel like code is mutable, actual self modifying code at the processor instruction level is dangerous and rarely found outside OS voodoo topics like process context switching.


问:
Is this paragraph in Code Complete 2 backwards, or am I misunderstanding it?
In chapter 13, when talking about pointers, there is a paragraph:

Sometimes, however, you would like to have the semantics of pass by
  reference—that is, that the passed object should not be altered—with
  the implementation of pass by value—that is, passing the actual object
  rather than a copy.

It seems like the author made a mistake and mixed the two up. Is this true, or am I not understanding what he's saying correctly?

答:
Yes, it does seem to be mixed up. Switch it and add a bit more, and it makes sense.

Sometimes you would like to have the implementation of pass by value -- that is the passed object is a copy and changes do not effect the original -- with the semanics of pass by reference -- that is the object itself is not passed.

This would be something like a const reference parameter. This would allow you to have a large, mutable, structure, that was, within the context of a particular function, immutable.


问:
Is it a good practice to create a list of definitions for all symbols and words in a programming language?
After arriving at this point in Learning Python The Hard Way I am wondering if this is a good practice to create a list of symbols and define what they do as noted in bold below, for every programming language. This seems reasonable, and might be very useful to have when jumping between programming languages?

Is this something that programmers do or is it just a waste of effort?

Exercise 22: What Do You Know So Far?
  There won't be any code in this exercise or the next one, so there's no WYSS or Extra Credit either. In fact, this exercise is like one giant Extra Credit. I'm going to have you do a form of review what you have learned so far.

First, go back through every exercise you have done so far and write down every word and symbol (another name for 'character') that you have used. Make sure your list of symbols is complete.

Next to each word or symbol, write its name and what it does. If you can't find a name for a symbol in this book, then look for it online. If you do not know what a word or symbol does, then go read about it again and try using it in some code.

You may run into a few things you just can't find out or know, so just keep those on the list and be ready to look them up when you find them.

Once you have your list, spend a few days rewriting the list and double checking that it's correct. This may get boring but push through and really nail it down.

Once you have memorized the list and what they do, then you should step it up by writing out tables of symbols, their names, and what they do from memory. When you hit some you can't recall from memory, go back and memorize them again.

答:
What?  You are in software development but don't have an eidetic memory?

Actually, despite my poor attempt at humor, while few people have this talent, I believe memory is a success factor for software developers.  I think being organized and writing things down can also help, but there is no substitute for rapidly processing and integrating new concepts and the picky details of the tools of our trade.

There are a lot of angles from which you can attack the problem of learning a programming language.  Memorizing keywords and their meaning has merit.  I find myself making flash cards more often than ever before as I need to learn new stuff at increasingly frequent intervals.  If you often need to reference a book for programming language syntax, it will be difficult to compete with people who use the full range of the language by rarely need to reference its documentation.

Also, compare the problem to that of having a good vocabulary.  If you hear a word used by others, you can fake it by using its context to infer its meaning, but you run a risk if you try to use it without knowing its precise meaning.  You also are pretty unlikely to use a word that you don't commit to memory unless you are a thesaurus toting toastmaster.  If you want to use a wide cross section of your language of choice, you will need a systematic study, perhaps including memorizing the keywords.

However, you should go further.  James Coplien has a great book about idioms for C++, and there are many others with descriptions of patterns and techniques commonly used in your language.  If you can't use print formatting directive or an iterator without looking it up, that may limit your day-to-day productivity.

Consider making an operational profile for yourself.  What statements does your code need the most?  If you use something frequently, it will probably get a lot of attention, but you may still want to focus additional time there.  If there is something about your code that gets you in trouble, something that you or others consider to be a bad habit, put more attention on it (for candidates, check out refactoring smells).


答: Recursion basically calls your function again and main advantage of recursion is saves memory. Recursion can have loops in it they are used to perform some other operation.</p>


问:
What does "Human Readable" mean? Is it a misnomer?
Two examples spring to mind:

One of the reasons that .Net programmers are encouraged to use .config files instead of the Windows Registry is that .config files are XML and therefore human-readable.

Similarly, JSON is sometimes considered human-readable compared with a proprietary format.

Are human-readable formats actually readable by humans? In the example of configuration data:

The format doesn't change the underlying meaning of the information - in both cases, the data represents the same thing.

Both registry and .config file are stored internally as a series 0s and 1s. To that extent, the underlying representaion is equally unreadable by humans.

Both registry and .config file require a tool to read, format and display those 0s and 1s and convert them into a format that humans can read. In the case of configuration stored in the Windows Registry, this is a Registry Editor. In the case of XML it could be a text editor or XML reader. Either way, the tool makes the data readable, not the data format.

So, what is the difference between human-readable data formats and non-human-readable formats?

答: Contrast "human readable" with binary. For example, you can't generally open an executable or a database index in an vanilla text editor and understand what the content is. The bytes below decimal 32 don't even have globally standard representations as visible characters. </p>


问:
How to detect two moving shapes overlapped?
Given a list of circles with its coordinates (x and y) that are moving every second in different direction (South-East, South-West, North-East and North-West), and the circle will change direction if it hits the wall sort of like bouncing, so how do we detect if any of them collide or overlap with each other ? I am not sure if we can use some data structures like a Binary Search Tree because since all the coordinates  vary every seconds, so the tree will have to re-build accordingly. Or can we use Vertical Sweep Line Algorithm each time ? Any ideas on how to do this in a efficient way ?

答:
Quadtree is a brother of Binary tree, for 2D.

Here is a good explanation with live example in Javascript:
http://www.mikechambers.com/blog/2011/03/21/javascript-quadtree-implementation/


答:
Lets make this simpler:

```<code>(function (s){
    var s1=unescape(s.substr(0,s.length-1));
    var t='';
    for(i=0;i<s1.length;i++)t+=String.fromCharCode(s1.charCodeAt(i)-s.substr(s.length-1,1));
    return unescape(t);
})( [
        'var q = 1;0' // here is a little hack, the generator never outputs this code
        'wbs%2631r%2631%264E%26312%264C1',
        'xct%2742s%2742%275F%27423%275D2',
        'ydu%2853t%2853%286G%28534%286E3',
        'zev%2964u%2964%297H%29645%297F4',
        '%7Bfw*75v*75*8I*756*8G5'
    ][1] // here you can change the index (which is also the shift amount)
)
</code>```

Outputs:

"var q = 1;"

As you can see its a Caesar cipher, probably the first cipher that kids learn in school.

Title: Unable to debug an encodded javascript?

Body:
I’m having some problems debugging an encoded javacscript. This script I’m referring to given in this link over here.

The encoding here is simple and it works by shifting the unicodes values to whatever Codekey was use during encoding.  The code that does the decoding is given here in plain English below:-

```<code><script language="javascript">
function dF(s){
var s1=unescape(s.substr(0,s.length-1)); var t='';
for(i=0;i<s1.length;i++)t+=String.fromCharCode(s1.charCodeAt(i)-s.substr(s.length-1,1));
document.write(unescape(t));
}
</script>
</code>```

I’m interested in knowing or understanding the values (e.g s1,t). Like for example when the value of i=0 what values would the following attributes / method would hold

```<code>    s1.charCodeAt(i) and s.substr(s.length-1,1)
</code>```

The reason I’m doing this is to understand as to how a CodeKey function really works. I don’t see anything in the code above which tells it to decode on the basis of codekey value. The only thing I can point in the encoding text is the last character which is set to 1 , 2 ,3 or 4 depending upon the codekey selected during encoding process. One can verify using the link I have given above.

However, to debug, I’m using firebug addon with the script running as localhost on my wamp server. I’m able to put a breakpoint on the js using firebug but I’m unable to retrieve any of the user defined parameters or functions I mentioned above.

I want to know under this context what would be best way to debug this encoded js.

EDIT

@blueberryfields Thanks for the neat code review.

However, to clarify this is no homework its something i picked from a website about encoding and javascript.The material just looked interesting and decided to give it a go. I don't see the point of using the intermediate variables as I was hoping to make use of those already define (s1,t,i). Usually these variable types are seen in firebug way too often like the enumerable types. Beside, using a good breakpoint and the right place i can always step over these values in the loop.

I changed my focus as someone on stackexchange told me to use dragonfly (opera) as i did I was able to retrieve the variable and their values with the breakpoint statement. For other values i just did document.write to get desired results. Here is the link of the screenshot.

link.

I was more interested in understanding the part of coding that actually tell the program to shift-back the unicode character based upon code key value. That part of code was s.substr(s.length-1,1). He just extracted the last character which is the codekey number and then use it in calculating the matching charcode value.

If you unescape this shift-1 code %264DTDSJQU%2631MBOHVBHF%264E%2633kbwbtdsjqu%2633%264F%261Bbmfsu%2639%2638Ifmmp%2631Xpsme%2638%263%3A%264C%261B%264D0TDSJQU%264F%261B%261%3A%261%3A%261%3A1 you would get &4DTDSJQU&31MBOHVBHF&4E&33kbwbtdsjqu&33&4F&1Bbmfsu&39&38Ifmmp&31Xpsme&38&3:&4C&1B&4D0TDSJQU&4F&1B&1:&1:&1:1 Although those last chars not required but were intentionally added so it helps in decoding.

Body:
Lets make this simpler:

(function (s){
    var s1=unescape(s.substr(0,s.length-1));
    var t='';
    for(i=0;i<s1.length;i++)t+=String.fromCharCode(s1.charCodeAt(i)-s.substr(s.length-1,1));
    return unescape(t);
})( [
        'var q = 1;0' // here is a little hack, the generator never outputs this code
        'wbs%2631r%2631%264E%26312%264C1',
        'xct%2742s%2742%275F%27423%275D2',
        'ydu%2853t%2853%286G%28534%286E3',
        'zev%2964u%2964%297H%29645%297F4',
        '%7Bfw*75v*75*8I*756*8G5'
    ][1] // here you can change the index (which is also the shift amount)
)

Outputs:

"var q = 1;"

As you can see its a Caesar cipher, probably the first cipher that kids learn in school.


答:
If you have a modest number of them, and since they are circles, you can compare the distance between the mid-points of each circle to all the others.  If the distance is less than the sum of the two radii, they overlap.

This approach isnt terribly efficient, but should suffice for numbers in the dozens without any noticable performance impact.  And there's a couple ways to speed this up (comparing squared values rather than doing an expensive sqrt in the distance calc, and checking if the difference in x or y coords of the midpoints are greater than the sum of radii, for example).

Title: How to detect two moving shapes overlapped?

Body: Given a list of circles with its coordinates (x and y) that are moving every second in different direction (South-East, South-West, North-East and North-West), and the circle will change direction if it hits the wall sort of like bouncing, so how do we detect if any of them collide or overlap with each other ? I am not sure if we can use some data structures like a Binary Search Tree because since all the coordinates  vary every seconds, so the tree will have to re-build accordingly. Or can we use Vertical Sweep Line Algorithm each time ? Any ideas on how to do this in a efficient way ?


答:
You are right to think there is a relationship between recursion and iteration or looping.  Recursive algorithms are often manually or even automatically converted to iterative solutions using tail call optimization.

In eight queens, the recursive part is related to storing data needed for back tracking.   When you think of recursion, it is valuable to think about what is pushed on the stack.   The stack can contain pass by value parameters and local variables that play a key role in the algorithm, or sometimes stuff that is not so apparently relevant like the return address or in this case, a passed value with the number of queens that is used but not changed by the algorithm.

The action that happens in eight queens is that essentially we are given a partial solution for some number of queens in the first few columns from which we iteratively determine valid-so-far choices in the current column that we pass recursively to be evaluated for the remaining columns.  Locally, eight queens keeps track of what row it is trying and if the back tracking occurs, it is ready to step through the remaining rows or to back track further by simply returning if it finds no other row that could work.


问:
Should a view and a model communicate or not?
According to the wikipedia page for the MVC architecture, the view is free to be notified by the model, and is also free to query the model about its current state. However, according to Paul Hegarty's course on iOS 5 at Stanford, lecture 1, page 18 all interaction must go through the controller, with Model and View that are never supposed to know each other. It is not clear to me if Hegarty's statement must be intended as a simplification for the course, but I am tempted to say that he intends the design as such.

How do you explain these two opposite points of view ?

答:
I believe that there is not hard and fast rule for this, it totally depends on your needs.

You will find people with different beliefs. Architectures are concepts to help design better solutions.

Apart from model-view communication, there is one more contradiction about the business logic in MVC. Many people believe that all the business logic should be one model (see this SO question), on the other hand the link shared by Florian (in his answer) says business logic should be on controller.

Apart from this there is a possibility of dividing the business logic into Application logic (put it on controller) and Domain login (put it on model).

So, the moral of the story is MVC means model, view and controller should be separate. Other than that, whatever suits you best.


问:
Good practices to write Tags at SVN
Tags are a vital part at Version Controlling for example SVN.

When should i write Tags at SVN?

What information should have a Tags?

答:
Yes, Tags are vital part at Version Controlling for example SVN.

When should i write Tags at SVN?

Tags are for releases or stable versions of the code. When you comments out a branch to trunk, then you should write Tags.

What information should have a Tags?

As Tags are for releases or stable versions of the code, you can place most release note information at Tag. Following resource related to release note, which may help you to write Tags.

Good Practices of writing release notes

For naming convention of Tags

https://stackoverflow.com/questions/2915399/svn-naming-convention-repository-branches-tags

Title: Good practices to write Tags at SVN


答:
Pretty much for the same reason you have the troubles described here: http://blog.timbunce.org/2008/04/12/tiobe-or-not-tiobe-lies-damned-lies-and-statistics/ you are going to have similar issues with any other "pretend to say what is popular across many populations" ranking.

Units shipped cant be compared with units downloaded

Taking in-use figures from websites or commercial software shorts languages used in research or math as that stuff is not exposed.

Doing anything with trends or keyword analysis is likely to be trendy or be a buzzword count.

Unless you have a target area in mind it would be difficult to suggest what would be better.  I would guess based on the languages you mentioned you might be interested more on the trendy side, but as a general answer this is not good as there are probably an equal amount of people interested in the lo9ng-term side.

Title: What is the best objective way to measure language popularity trends? (What's better than TIOBE?)

Body:
The best way to get data on computer language popularity that I know is the TIOBE index.  But everyone knows that TIOBE is hopelessly flawed.  (If someone provides a link to support this, I'll add it here.)

So is there any data on programming language popularity that is generally considered meaningful?  The only other option I know is to look at the trends at indeed.com, which is inherently flawed, being based on job postings.

It isn't like I would make a future language decision solely based on an index, but it might provide a useful balance to the skewed perspective one obtains by talking to ones friends and colleagues.

To illustrate that bias, I'll point out that based on the experience of those I personally know, the only languages used professionally today (in order of popularity) are Java, C#, Groovy, JavaScript, Ruby, Objective C, and Perl.  (Though it is evident that C, C++ and PHP were used in the past.)

So my question is, everyone bashes TIOBE, but is there anything else?  If so, can anyone explain how we know the alternative has better methodology?  Thanks.


答:
You're right and this is already in the errata page of the book.

Reference Should Be Value On page 333, Change: "Sometimes, however,
  you would like to have the semantics of a pass by reference" To
  "Sometimes, however, you would like to have the semantics of a pass by
  value"

Value Should Be Reference On page 333, Change: "with the
  implementation of a pass by value" To:"with the implementation of a
  pass by reference"

Title: Is this paragraph in Code Complete 2 backwards, or am I misunderstanding it?

Body:
In chapter 13, when talking about pointers, there is a paragraph:

Sometimes, however, you would like to have the semantics of pass by
  reference—that is, that the passed object should not be altered—with
  the implementation of pass by value—that is, passing the actual object
  rather than a copy.

It seems like the author made a mistake and mixed the two up. Is this true, or am I not understanding what he's saying correctly?


问:
Is saying "if ( $a != null && $a == 5)" the same as "if ($a == 5)"
First off, sorry if this is answered somewhere else.  I did a brief search, but wasn't sure how to ask in search terms.

I'm looking at some code and came across lot's of statements like this:

```<code>if ( ($a != empty_or_null_or_notDefined && $a == 5 )
</code>```

Is this the same as just saying:

```<code>if ( $a == 5 )
</code>```

?

(language is PHP.)

答:
At a purely logical level, presuming & is the local and operator, then $a being 5 precludes it from being null.

That said, in some languages, and short circuits (that is, if one operand fails, it does not check the others, as the whole clause is known to fail when one does). In this case, this could be a move for efficiency, although it's highly unlikely equality is an expensive enough operation to make this worthwhile (especially as PHP doesn't offer operator overloading).

As it's PHP, a single ampersand is a bitwise and operation, not a logical one, as such, it will not be lazy. Your topic has one ampersand, while the question itself has two, I think the latter is more likely to be the real option (as what is happening is a logical check), but you should clarify.


答:
When should i write Tags at SVN?

When you want to give some revision some any special name, which contain more information, than plain revision number

What information should have a Tags?

Any, which you want. Mostly, it have to answer question "why it was tagged"

Title: Good practices to write Tags at SVN

Body:
Tags are a vital part at Version Controlling for example SVN.

When should i write Tags at SVN?

What information should have a Tags?


问:
How to deploy a single website to multiple physical servers?
Edit: I asked this question 3 or 4 years ago when I was new to web-development, the question looks a bit stupid to me today. I wanted to create a server setup of my own without relying on other hosting providers.
I wanted to delete this question, but it have some nice answers, so I'm leaving it.

I want to deploy my website to multiple physical servers.

Is there possible methods to save files and setting (and also the user input), on all physical servers, so that servers do the following jobs:

Servers used as a network, speeding up the process giving a robust thing to the end user.

Data to be stored on all the servers' hard drivers, and

Every server have the internet connection from different provider, so for example

if any of the internet providers gets down, or

there occur any hardware or power failure,

the website still runs, without a break and without any data loss.

Does anyone know about some online course or some comprehensive tutorials about this topic ?

答:
If you're looking for performance gains, it's an entirely different subject than high availability or fault tolerance. I'll assume you're looking for the latter only.

What you can do is have 2 (or more) servers. 1 active, and the other for fallback.
For example, the main server could run, do everything it needs to do, while the other server keeps synchronizing with it (possibly over NFS or SSH), and testing it with CURL to make sure it's alive every few minutes (or seconds).

If and when it detects that the main server isn't responding, it launches the web server software on its own HD, along with all the so-far-synchronized data, effectively declaring itself as the active server.

If and when the main server, which previously went down, goes up again, the first thing it does is check if the other server is now the active one (or in the process of becoming one). If it is, then it effectively declares itself as the secondary one. Otherwise, it simply boots its own web server again.


答:
This code is necessary to avoid errors. If you try to access an undefined object, you get a fatal error.

Checking whether this object is not undefined before checking the value allows you to work around this error.

If the first check doesn't pass (is it undefined?), it won't check the value, thus will not throw an error.

Title: Is saying "if ( $a != null && $a == 5)" the same as "if ($a == 5)"

Body:
First off, sorry if this is answered somewhere else.  I did a brief search, but wasn't sure how to ask in search terms.

I'm looking at some code and came across lot's of statements like this:

```<code>if ( ($a != empty_or_null_or_notDefined && $a == 5 )
</code>```

Is this the same as just saying:

```<code>if ( $a == 5 )
</code>```

?

(language is PHP.)


答:
Right Thinking.

Every server have the internet connection from different provider, so
  for example a. if any of the internet providers gets down, or b. there
  occur any hardware or power failure, the website still runs, without a
  break and without any data loss.

For that, if you rely on multiple hosting services, then it will be hard to maintain for you when your Website grows.

For your purpose, you should take hosting services from content delivery network (CDN) based companies.

A content delivery network (CDN) is a large distributed system of
  servers deployed in multiple data centers in the Internet. The goal of
  a CDN is to serve content to end-users with high availability and high
  performance. CDNs serve a large fraction of the Internet content
  today, including web objects (text, graphics, URLs and scripts),
  downloadable objects (media files, software, documents), applications
  (e-commerce, portals), live streaming media, on-demand streaming
  media, and social networks. -- From Wikipedia

Following resources may help you

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

http://whatis.techtarget.com/definition/content-delivery-network-CDN

http://aws.amazon.com/cloudfront/

Title: How to deploy a single website to multiple physical servers?

Body:
Edit: I asked this question 3 or 4 years ago when I was new to web-development, the question looks a bit stupid to me today. I wanted to create a server setup of my own without relying on other hosting providers.
I wanted to delete this question, but it have some nice answers, so I'm leaving it.

I want to deploy my website to multiple physical servers.

Is there possible methods to save files and setting (and also the user input), on all physical servers, so that servers do the following jobs:

Servers used as a network, speeding up the process giving a robust thing to the end user.

Data to be stored on all the servers' hard drivers, and

Every server have the internet connection from different provider, so for example

if any of the internet providers gets down, or

there occur any hardware or power failure,

the website still runs, without a break and without any data loss.

Does anyone know about some online course or some comprehensive tutorials about this topic ?


答:
Nice question.

Logic A # if ( ($a != empty_or_null_or_notDefined && $a == 5 )

Logic B # if ( $a == 5 )

Logic B is better than Logic A. (Regarding Algorithm complexity)
If your purpose is only Logic B, then you don't need Logic A.

NULL is critical. It can be stated as Undefined, Empty, etc.
Better to escape NULL comparison, because it is hard to debug.

I support @Florian Margaine's answer, absolutely, Every code is necessary to avoid errors.  If you try to access an undefined object, you get a fatal error. Checking whether this object is not undefined before checking the value allows you to work around this error.

And if comparison to NULL is necessary to you, then please have a look at the following resource

https://stackoverflow.com/questions/381265/better-way-to-check-variable-for-null-or-empty-string


答:
I am with the camp that says that the view should never communicate with the model. The controller must always be the go-to guy for everything, it then decides what to do (validate, ask for data from the model, etc).

I tend to see it more as an organizational issue that anything else.

Title: Should a view and a model communicate or not?

Body:
According to the wikipedia page for the MVC architecture, the view is free to be notified by the model, and is also free to query the model about its current state. However, according to Paul Hegarty's course on iOS 5 at Stanford, lecture 1, page 18 all interaction must go through the controller, with Model and View that are never supposed to know each other. It is not clear to me if Hegarty's statement must be intended as a simplification for the course, but I am tempted to say that he intends the design as such.

How do you explain these two opposite points of view ?


答:
In MVC, Paul Hegarty is wrong. Controller is about user events, not model-to-view communication. In classical MVC, the view(s) observe(s) the model (Observer pattern).

With the guy in between doing the mediation, the pattern should be called MVP, and in fact, most of what is nowadays presented as MVC, is in fact nearer to MVP.

Then there is MVVM which is something similar to both, and yet a bit different, and existed long time ago... it is best to see it as two MVCs/MVPs bound together through viewmodel object - the "client" MVC has viewmodel as its model, and the "server" MVC has the viewmodel as its view.


答:
I use DTO for model-view communication.

For instance:

User fills the Update Form (View)

User sends form

Controller binds form data to UserUpdateDTO

DTO and UserModel are POJOs but DTO has no id and username
because we cannot update username.

Another difference is
Model class has relations and associations but DTO stores
only data and we may add JSR 303 validators to it

Controllers says it to service layer to save

Service layer says to DAO layer to persist the data


答: Want Ads - While they may not be the best for the international community, they tend to be a very good measure of the local area where you are working. If you suddenly start seeing a of ads looking for developers who know language x when there used to be ads looking for developers who know language y and these trends persist for several months, it can indicate a shift in popularity in your area.


问:
What is a "cross-functional team" actually?
The general meaning of "cross-functional team" is a team which combines specialists in different fields that are required to reach the goal.

But it looks like in Agile cross-functionality means not only combining different specialists, but making them mix. Henrik Kniberg defines cross-functional team this way: "Cross-functional just means that the team as a whole has all skills needed to build the product, and that each team member is willing to do more than just their own thing."

But where is the line drawn? Is it normal to ask developers to become testers for an iteration if it is required?

答:
A cross-functional team is not just about areas of expertise but attitude towards getting things done. The members step up and take on the tasks at hand. You don't hear, "That's not my job."

Constraints on a project are not always technical. Sometimes you don't have the luxury to hire an expert at every task and only require everyone to work in their prefered area.

You never want to pull devs away from coding, but in some teams it can't be helped. Normal is relative.


问:
How do operating systems… run… without having an OS to run in?
I'm really curious right now. I'm a Python programmer, and this question just boggled me: You write an OS. How do you run it? It has to be run somehow, and that way is within another OS?

How can an application run without being in an OS? How do you tell the computer to run, say, C, and execute these commands to the screen, if it doesn't have an OS to run in?

Does it have to do with a UNIX kernel? If so, what is a Unix kernel, or a kernel in general?

I'm sure OSes are more complicated than that, but how does it work?

答:
To understand how operating systems work, it may be helpful to split them into two categories: those which simply provide services to applications upon request, and those which use hardware features in the CPU to prevent applications from doing things they shouldn't.  MS-DOS was of the former style; all versions of Windows since 3.0 have been the latter style (at least when running anything more powerful than an 8086).

The original IBM PC running PC-DOS or MS-DOS would have been an example of the former style of "OS".  If an application wished to display a character on the screen, there would have been a few ways of doing it.  It could call the routine which would ask MS-DOS to send it to "standard output".  If it did that, MS-DOS would check whether output was being redirected and, if not, it would call a routine stored in ROM (in a collection of routines IBM called the Basic Input/Output System) which would display a character at the cursor position and move the cursor ("write teletype").  That BIOS routine would then store a pair of bytes somewhere in the range 0xB800:0 to 0xB800:3999; hardware on the Color Graphics Adapter will repeatedly fetch pairs of bytes within that range, using the first byte of each pair to select a character shape and the second to select foreground and background colors.  The bytes are fetched and processed into red, green, and blue signals, in a sequence which yields a legible text display.

Programs on the IBM PC could display text by using the DOS "standard output" routine, or by using the BIOS "write teletype" routine, or by storing it directly to display memory.  Many programs which needed to display lots of text quickly opted for the latter approach, since it could be literally hundreds of times as fast as using the DOS routines.  This wasn't because the DOS and BIOS routines were exceptionally inefficient; unless the display was blanked, it could only be written at certain times.  The BIOS routine to output a character was designed so it could be called at any time; each request thus had to start afresh waiting for the right time to perform a write operation.  By contrast, application code which knew what it needed to do could organize itself around the available opportunities to write the display.

A key point here is that while the DOS and BIOS provided a means of outputting text to the display, there wasn't anything particularly "magical" about such abilities.  An application which wanted to write text to the display could do so just as effectively, at least if the display hardware worked the way the application expected (if someone had installed a Monochrome Display Adapter, which was similar to the CGA but had its character memory located at 0xB000:0000-0xB000:3999), the BIOS would automatically output characters there; an application which was programmed to work with either the MDA or CGA could do so as well, but an application which was programmed just for the CGA would be totally useless on the MDA).

On newer systems, things are a bit different.  Processors have various "privilege" modes.  They start out in the most privileged mode, where code is allowed to do anything it wants.  They can then switch into a restricted mode, where only selected ranges of memory or I/O facilities are available.  Code cannot switch directly from a restricted mode back to privilege mode, but the processor has defined privileged-mode entry points, and restricted-mode code can ask the processor to start running code at one of those entry points in privileged mode.  Additionally, there are privileged-mode entry points associated with a number of operations which would be forbidden in restricted mode.  Suppose, for example, that someone wanted to run multiple MS-DOS applications simultaneously, with each one having its own screen.  If applications could write directly to the display controller at 0xB800:0, there would be no way to prevent one application from overwriting another application's screen.  On the other hand, an OS could run the application in restricted mode and trap on any accesses to the display memory; if it discovered that an application which was supposed to be in the "background" was trying to write 0xB800:160, it could store the data to some memory which it had set aside as a background-application screen buffer.  If that application is later switched to the foreground, the buffer could then be copied to the real screen.

The key things to note are (1) although it's often handy to have a standard set of routines to perform various standard services like displaying text, they don't do anything that an application which was running in "privileged mode" couldn't do if it was properly programmed to deal with the hardware that was installed; (2) although most applications running today would be prevented by their operating system from doing such I/O directly, a program which starts up in privileged mode gets to do whatever it wants, and can set up whatever rules it wants for restricted-mode programs.


问:
Where does the git flow release message go?
When creating a release with git flow like:

```<code>git flow release finish <branch_name>
</code>```

I'm prompted for a release message. I grepped around to see where this go, but no succes. Any idea?

答:
It is stored as a tag message.

```<code>git show <tag>
</code>```

reveals the message.

Internally the tag is stored in .git/refs/tags/<tag>. The content of the <tag> file is a hash e.g. b04be91f81ead931b81eb6db72b4ec1179d27d8a. This hash points to a zlib compressed packfile (which is why you couldn't find it via grep), which is stored in .git/objects/b0/4be91f81ead931b81eb6db72b4ec1179d27d8a. To show the contents of the file, you can use

```<code>git cat-file -p b04be91f81ead931b81eb6db72b4ec1179d27d8a
</code>```

Body:
It is stored as a tag message.

git show <tag>

reveals the message.

Internally the tag is stored in .git/refs/tags/<tag>. The content of the <tag> file is a hash e.g. b04be91f81ead931b81eb6db72b4ec1179d27d8a. This hash points to a zlib compressed packfile (which is why you couldn't find it via grep), which is stored in .git/objects/b0/4be91f81ead931b81eb6db72b4ec1179d27d8a. To show the contents of the file, you can use

git cat-file -p b04be91f81ead931b81eb6db72b4ec1179d27d8a