问:
detect if a combination of string objects from an array matches against any commands
Please be patient and read my current scenario. My question is below.

My application takes in speech input and is successfully able to group words that match together to form either one word or a group of words - called phrases; be it a name, an action, a pet, or a time frame.

I have a master list of the phrases that are allowed and are stored in their respective arrays. So I have the following arrays validNamesArray, validActionsArray, validPetsArray, and a validTimeFramesArray.

A new array of phrases is returned each and every time the user stops speaking.

```<code>NSArray *phrasesBeingFedIn = @[@"CHARLIE", @"EAT", @"AT TEN O CLOCK",
                                @"CAT",
                                @"DOG", "URINATE",
                                @"CHILDREN", @"ITS TIME TO", @"PLAY"];
</code>```

Knowing that its ok to have the following combination to create a command:

```<code>COMMAND 1: NAME + ACTION + TIME FRAME
COMMAND 2: PET + ACTION
COMMAND n: n + n, .. + n

//In the example above, only the groups of phrases 'Charlie eat at ten o clock' and 'dog urinate'
//would be valid commands, the phrase 'cat' would not qualify any of the commands
//and will therefor be ignored
</code>```

Question

What is the best way for me to parse through the phrases being fed in and determine which combination phrases will satisfy my list of commands?

POSSIBLE solution I've come up with
One way is to step through the array and have if and else statements that check the phrases ahead and see if they satisfy any valid command patterns from the list, however my solution is not dynamic, I would have to add a new set of if and else statements for every single new  command permutation I create.

My solution is not efficient. Any ideas on how I could go about creating something like this that will work and is dynamic no matter if I add a new command sequence of phrase combination?

答:
I have minimal experience with  objective-c so I'm going to run though the solution I would build using c#, but will explain as I go.  It should be easy to replicate in any similar language.

I would start with defining  an enum to specify the phrase types:

```<code>enum PhraseTypes {
    name = 0,
    action = 1,
    pet = 2,
    timeFrames = 3
}
</code>```

I would then define a Rule as having the following structure:

```<code>class Rule {
    List<PhraseTypes> components;
    Action action; //or whatever makes sense for your app
}
</code>```

The users command could then be represented as:

```<code>List<String> command;
</code>```

The valid phrases could be:

```<code>List<String> validNamesArray;
List<String> validActionsArray;
// ...
</code>```

And then compiled into:

```<code>List<List<String>> validPhrases = new List<List<String>>( new List<String>[]
                {validNamesArray, validActionsArray, validPetsArray, validTimeFramesArray}
                                                        );
</code>```

Performing a check against the rules, and calling the correct action could then be done like this:

```<code>bool CheckCommandAgainstRules(Rules rules, List<String> command) {
    foreach (Rule rule in rules) {
        if (CheckCommandAgainstRule(rule, command)) {
            rule.Action(command);  //or whatever makes sense for your app
            return true;
        }
    }
    return false;
}

bool CheckCommandAgainstRule(Rule rule, List<String> command) {
    for (i = 0; i < rule.components.length; i++) {
        PhraseType phraseType = rule.components[i];
        String phrase = command[i];
        if(!validPhrases[(int)phraseType].Contains(phrase)) {
            return false;
        }
    }
    return true;
}
</code>```

This overall structure should easily scale to any number of rules and/or phrase types.

Edit:

1) Yeah, I figured that once you have solved the problem of determining if a command is valid, and identified which rule it matches the next issue is triggering some kind of action.  One way is to let the Rule know which action is required.. In c# I would use a delegate or a class with a known interface so I could call it's .run() method.  The best is likely  vary from language to language.

2) My understanding was that you are using phrase to mean an atomic group of one or more words e.g. "AT TEN O CLOCK" , "DOG" or "PLAY".  I have used command to represent a list of phrases as derived from user input.  Rereading your question it looks like you have used command to refer to a valid combinations of phrase types, this something I have been calling a Rule.

Body:
I have minimal experience with  objective-c so I'm going to run though the solution I would build using c#, but will explain as I go.  It should be easy to replicate in any similar language.

I would start with defining  an enum to specify the phrase types:

enum PhraseTypes {
    name = 0,
    action = 1,
    pet = 2,
    timeFrames = 3
}

I would then define a Rule as having the following structure:

class Rule {
    List<PhraseTypes> components;
    Action action; //or whatever makes sense for your app
}

The users command could then be represented as:

List<String> command;

The valid phrases could be:

List<String> validNamesArray;
List<String> validActionsArray;
// ...

And then compiled into:

List<List<String>> validPhrases = new List<List<String>>( new List<String>[]
                {validNamesArray, validActionsArray, validPetsArray, validTimeFramesArray}
                                                        );

Performing a check against the rules, and calling the correct action could then be done like this:

bool CheckCommandAgainstRules(Rules rules, List<String> command) {
    foreach (Rule rule in rules) {
        if (CheckCommandAgainstRule(rule, command)) {
            rule.Action(command);  //or whatever makes sense for your app
            return true;
        }
    }
    return false;
}

bool CheckCommandAgainstRule(Rule rule, List<String> command) {
    for (i = 0; i < rule.components.length; i++) {
        PhraseType phraseType = rule.components[i];
        String phrase = command[i];
        if(!validPhrases[(int)phraseType].Contains(phrase)) {
            return false;
        }
    }
    return true;
}

This overall structure should easily scale to any number of rules and/or phrase types.

Edit:

1) Yeah, I figured that once you have solved the problem of determining if a command is valid, and identified which rule it matches the next issue is triggering some kind of action.  One way is to let the Rule know which action is required.. In c# I would use a delegate or a class with a known interface so I could call it's .run() method.  The best is likely  vary from language to language.

2) My understanding was that you are using phrase to mean an atomic group of one or more words e.g. "AT TEN O CLOCK" , "DOG" or "PLAY".  I have used command to represent a list of phrases as derived from user input.  Rereading your question it looks like you have used command to refer to a valid combinations of phrase types, this something I have been calling a Rule.


问:
How maintainable are automated refactorings?
Resharper offered to turn my loop:

```<code>foreach (JObject obj in arr)
{
    var id = (string)obj["Id"];
    var accountId = (double)obj["AccountId"];
    var departmentName = (string)obj["DeptName"];
    i++;
}
</code>```

...into a LINQ statement. I acquiesced, and it produced this:

```<code>int i = 1 + (from JObject obj in arr let id = (string) obj["Id"] let accountId = (double) obj["AccountId"] select (string) obj["DeptName"]).Count();
</code>```

Gee whillikers, jumpin' Jehoshaphat, and Heavens to Murgatroid!

This makes me wonder if the robots becoming smarter than me is a good thing; how maintainable is that? Answer: it's not, since I can't understand it; R# may just as well have converted it to machine code, for all I can grok it.

I have to admit, though, it's "cool."

At what point does the perfect become the enemy of the good in this kind of scenario?

UPDATE

On a second pass through, R# tells me for that line of LINQ, "Local variable "i" is never used"

Letting it remove it, the line becomes:

```<code>var arr = JsonConvert.DeserializeObject<JArray>(s);
</code>```

Hmm! Now that's grokkable; the reason I was breaking the elements down into individual vars before was so that I could see what was in them:

```<code>MessageBox.Show(string.Format("Object {0} in JSON array: id == {1}, accountId == {2}, deptName == {3}", i, id, accountId, departmentName));
</code>```

...but with that messagebox commented out, I guess the above is better after all.

答:
Automated refactoring tools are not automated thinking tools. Just because you can apply some refactoring on a piece of code (you always can) doesn't mean you should. Never think you should do something just because a tool suggests it. You and your team are responsible for deciding what is maintainable and what is not.

That being said, automated refactorings are great and ReSharper might be best tool I have used. Refactoring tools can save you a lot of time, but they don't free you from thinking :)

ContentLicense: CC BY-SA 3.0


问:
Will it be a wrong idea to have

  Hello

```

答:
The html specification states that

A style element without a scoped attribute is restricted to appearing in the head of the document.

The scoped attribute is a boolean value indicating that it should be applied to just the sub tree rooted at the style element's parent element.

At this time only Firefox supports the scoped attribute. http://www.w3schools.com/tags/att_style_scoped.asp

Title: Will it be a wrong idea to have <style> in <body>?

Body:
In below code i placed internal style sheet with in body tag, instead of having in head.
For Single-Page-Application I am considering to do this for styles that is only applicable to that page alone, rather than having separate pagespecific.css file.

Is there a scenario where this has downside as i am not putting the same in head section?

```<code><!-- myPartial.html starts here -->
<!-- Like to keep styles unique to this html right here in this file -->
<div>
  <style>
    body { background-color: red; }
    #myText { color: white; }
  </style>

  <span id='myText'>Hello</span>
</div>
<!-- myPartial.html ends here -->
</code>```


问:
Are there any known effects on cognitive load of many files with one file per object?
There has been a trend in the Ruby/Rails community to create lots of objects that have very small functionality (SRP anyone?) and live in their own file. These are often extracted from large, bloated model files.

This could be good, but I think it is often changing one problem (bloated models with hundreds of lines of code) for another, worse problem (hundreds of small object files in subdirectories several layers deep).

Are there any known effects on the cognitive load difference between lots of small files and fewer large ones?

答:
I don't know the answer, but it's a question I've often asked myself while designing the structure of my systems.  The way I've thought about it lately is, if the SRP is all about "a class having only one reason to change", then what does that tell us about change?  The answer is that it tells us nothing about change. The phrase only tells us about classes, not about change.

I've tried to formulate a corollary about change, but haven't yet come up with anything particularly satisfying.  There's something about this answer (https://softwareengineering.stackexchange.com/a/213586/87944) in another question that I sort of like-- the way the answer mentions the difference between ease of changing types vs. operations,  that answer made me do some thinking.

I think in the end it comes down to cohesion of your system. A well designed system with high cohesion means that change is localised in a predictable way across classes, regardless of how many there are.

So to sum up: the cognitive load only becomes an issue when the time comes to make a change to the classes, and if the abstractions (types) in your system have high cohesion, then you should be able to reason about the system without undue cognitive load.  If you find that you can't reason about the code even though it seems to follow the SRP, then you probably have another S.O.L.I.D. violation, likely the D or the L.


问:
What is casting supposed to mean?
When coding in low level languages like C I find that casting sometimes means 'reinterpret these bytes as if it had always been of this other type' and at other times as 'convert this value intelligently into this other type'.

What is the original meaning of the word and is there any consistency in when to expect a conversion and when to expect a raw reinterpretation?

答:
```<code>cast (v): to receive form in a mold
</code>```

In C++ the various kinds of casts can be made more explicit, with reinterpret_cast meaning "treat these bytes as if they were already this other thing". In C you can make that absolutely explicit by using a union, casting with the (type) operator will attempt to keep the result numerically equivalent, up to loss of precision.

Title: What is casting supposed to mean?

Body:
cast (v): to receive form in a mold

In C++ the various kinds of casts can be made more explicit, with reinterpret_cast meaning "treat these bytes as if they were already this other thing". In C you can make that absolutely explicit by using a union, casting with the (type) operator will attempt to keep the result numerically equivalent, up to loss of precision.


问:
What is an example of a computationally impossible business problem?
I have coworker who refuses to accept the reality that Turing machines (and Von Neuman machines by extension) cannot solve their own halting problem stating:

You can do anything with enough time and money.

He also dislikes theoretical problems arguing that:

In our field, we'll never run into those questions. We're application developers, not theoretical scientists.

Is there a good example of a business problem that is computationally impossible that I could use to help convince him of this?

答:
I have taken a class recently on Business Process Model and Notation (BPMN). There it can easy be seen that workflows with many too splits, joins and loops become quickly impractical (though not necessarily impossible, AFAIK) to understand and control, (when you use too many OR-splits instead of XOR-splits).

For the software industry, I think the same holds for similar problems of "multiple condition coverage" in  code coverage analysis.

For a business, the way to go is to shrink the problem space, and not to throw more resources at the complex problem.
In my example, add constraints to the workflow, (or in code coverage analysis,  simplify the code), instead of working hard on finding all, say, N possible traces and outcomes where N is an unimaginably large number.

Aside from that I think there are many problems in network / graph analysis that are impossible to solve (trying to determine a network topology by iteratively walking all paths etc).


问:
ruby for desktop app or web app development
i am a beginner to ruby  . i just did some
minor research about why RUBY ? why choose RUBY ? whats new in it.
Whenever i do type in a word RUBY in google search there comes a
suggestion like RUBY on RAILS . so my mind changed to learn stuffs about
ruby on rails.

I went through some forums but got the same answer from everyone. RUBY
ON RAILS is a web development FRAMEWORK . once again i learnt stuffs
about what a framework is. There are lot of questions which is u know
like itching my mind.Varieties of answer from everyone. i dont know
which is the right one.

first if anyone wish to give me a reply .. tell me solution for this.

just like java we run ruby programs in command prompt by moving to the
directory in cmd where ruby is installed.it is similar to java. so can
we create a desktop application by using it.i mean like a file searching
program which is default in windows . We can create the same file
searching program using java swing and playing with some string
functions isn't it?
can we do the same with ruby .? thats my first one.

i will raise doubts on ruby on rails after i get cleared about the above
question.

答:
Yes, you can use Ruby for desktop applications (if it's a good choice is another question and may depend on the project). In addition to Ruby itself you will need some kind of widget toolkit or application framework that allows you to create windows and other GUI elements for the underlying operating system.

For Ruby exist bindings to several such toolkits like WxRuby to WxWidgets, FXRuby to FOX or QtRuby to the Qt framework (and a few more like ruby-gnome, ruby-tk, shoesrb, limelight, visual ruby). Or you can use JRuby and then use mostly anything available for Java.

Frameworks: there are many, sometimes quite different from each other. But as a general rule they are a combination of libraries and rules and boilerplate codes that make a certain complex task easier. This task may be something like a web site or a desktop application.

To start with for such a task you will need many libraries for the underlying tasks. You will use some database library to interface the database, some gui library to create windows, menus, buttons and other widgets. There are many ways to do this and many optional development patterns. MVC (Model View Controller) is quite fashionable, especially in web development with its special requirements.

So lets talk about Rails again. You need a model (database & business rules), a controller (take incoming request, gather data, process data and then tell the view to render the response web page) and the view (actually generating the html).

Many libraries are there to help with that and a lot of decisions to be made about how to organize your classes and file structure. Rails gives you a lot of defaults for that that work for a lot of typical projects.

In addition the framework will provide a lot of libraries of its own that help with the specific task. Rails for example makes it very easy to define models, validations and relations between models. It has helpers for the routing, for the controllers and in the view part for creating html, including javascript and integrating additional libraries and whole toolchains like the asset pipeline (generating CSS from SASS, JavaScript from CoffeeScript, minifying JavaScript and more of the more tedious everyday tasks in web dev).

The whole framework thing is a kind of project scaffolding that you than fill with your own code. If you start a new Rails project you have already have a database connection in place and some basic html rendering where otherwise you would have to write hundreds of lines of code to even get started.


答:
This part of the Webster dictionary gives the proper definition:

a :  to give a shape to (a substance) by pouring in liquid or plastic
  form into a mold and letting harden without pressure

  b : to form by this process

So, before casting, your "object" (not literally an OOP object) is in a given shape (type). When you re-cast it, that is "pour concrete" around it to make it into a new shape, that is what you do with casting. You have a number as a hexagon-shaped integer, and after casting, you will get a rectangle-shaped string.

Title: What is casting supposed to mean?

Body:
When coding in low level languages like C I find that casting sometimes means 'reinterpret these bytes as if it had always been of this other type' and at other times as 'convert this value intelligently into this other type'.

What is the original meaning of the word and is there any consistency in when to expect a conversion and when to expect a raw reinterpretation?


问:
Why are pointers to literals not possible?
Reference to a literal is possible only if the reference  is declared as constant.

But why is a pointer to a const object not possible in case of literals?
i.e.

```<code>int const& ref = 5;//
</code>```

But why is the same feature not available for a pointer, pointing to a constant object?

答:
In the C++ view of the world, a literal does not occupy any memory. A literal just exists.

This view makes that there is no address for a pointer to refer to when it would point to a literal and for that reason, pointers to literals are forbidden.

Const references are actually the exception here in that they allow apparent indirect access to a literal. What happens underneath is that the compiler creates a temporary object for the reference to refer to and that temporary object is initialized with the value of the reference.

This creating of a temporary that the reference gets bound to is only allowed for const references (and gets used in other scenarios as well, not only for literals), because that is the only case where a reference/pointer to a temporary won't have undesired side-effects.


问:
Implementation/Representation of Symmetries in Chessboards
In a 8X8 chessboard, I was wondering how to implement the symmetry of the board.

A lot of positions are just mirrors or rotations of one another (with no pawns or castling capabilities left the directions are indistinguishable).

By using a combination of vertical, horizontal and diagonal mirrorings of the board it is always possible to fix the position of a piece within the a1-d1-d4 triangle.

How to implement these symmetries on chess board?
How does implementation depends on choice of board representation chosen(Bit-boards, 0x88, 8x8 array, and so on) ?

Edit 1: The main goal is the implementation of the endgame engine generator and compress its results

答:
There are several ways to tackle rotation of a chess board.  The easiest way to implement it is the same way we think about it.  You create a grid of 8x8, and each position on the grid may or may not have a chess piece on top.  To mirror that grid, you simply create another chess board, and place each piece in the old chess board in its mirrored location.

This, however, can be simplified by removing the grid altogether.  The grid is arbitrary and serves primarily for us to understand better.  So you could use a chess board object to emulate all positions on the chess board, but the only information it would actually require are the types and positions of the chess pieces themselves.

The chess piece itself can be abstracted away into type and position information.  If you do not need to know how it moves, then the only reason the type would be useful is for you to compare with other chess pieces and ensure that other than position, types are the same in order to say that it is the same.

The chess board can mirror itself simply by returning another chess board instance with the positions altered (i.e. for each chess piece's x coordinate, piece.x = 9 - piece.x).

At that point, the problem simply becomes iterating the chess pieces of one chess board and another and verifying that all the positions and types are the same (you can optimize by checking the number of pieces first).

Note that if you don't require comparing mirrored versions of chessboards, you can optimize further by using only one instance and computing where a chess piece, if it were mirrored, would be relative to that current spot and then check for the existence and type of that piece.

Hope that helps.  I think it's important to present an interface that is easy for you to understand and let the underlying implementation optimize how data is represented and/or utilized.


问:
Will we go back(?) to fixed-point arithmetic in the near future?
As far as I recall, this has been the ongoing trend of the past, I'm just a student, so I might be wrong:

Long ago: Integer numbers and calculations. Very precise, however cannot present a big range.

At a later point: Added single-precision floating point numbers (floats), and also added FPU's which are incredibly fast at calculating with them.

Quite recently(?): Double-precision floating point numbers (doubles) are starting to become more common. For example in OpenGL Shader Language they are steadily introducing more and more methods that work with doubles natively. I think they are also working on FPU's for doubles?

But also there has been a change to 64-bit processing a few years ago, so I've got a few questions:

Are there more options now to calculate with fixed-point numbers (maybe two int64 registers?)?

Why are there, as far as I know, no specific units for fast integer calculation with respect to fixed-point numbers?

Maybe most of what I'm saying does not make much sense, but I think the question remains valid. Is there a switch we switch to fixed-point arithmetic in the near future?

答:
No.

There is not a snowball's chance in Hell that numerical computing will switch (back) to fixed-point arithmetic in the near future, or in ANY future.

There are several reasons for this, the biggest one being that doing fixed-point arithmetic requires that the programmer keep track of the final position of the decimal (binary) point in the calculation.  This is a LOT of work.  The whole point of floating-point arithmetic is to let the computer do the decimal (binary) point bookkeeping, and let the programmer worry about the algorithm.

Key concept: You do not want to run your computation out to the limits of machine accuracy and precision, as some computations take a LONG time to converge to that limit.  You just want to get an answer that is "good enough" for your particular purposes.  Usually, this is quite a bit less than what the machine in theory can do.

There do exist fast integer multipliers, in the world of integer digital signal processors.  Hardware integer divide exists on some processors, but not all.  There just isn't that much call for it, as integer division is not that common, and there isn't that much that call for it, compared to the on-chip real estate required to make it much faster than doing it in software, or compared to the difference in effort for integer division vs. floating-point division.

EDIT: To clarify, based on a comment: A floating-point divide unit requires an integer divider inside it, and then some extra stuff to handle normalization of the result mantissa and calculation of the result exponent.  The extra stuff is small compared to the integer divider itself.  Once you are providing floating-point addition, subtraction, and multiplication, and you decide to provide integer division, the extra cost of providing floating-point division is generally small.

The Control Data 6600 initially provided four-function floating point, and integer addition, subtraction, and multiplication, but did NOT provide integer division.  It wasn't seen as critically necessary for the machine's core customer base.  The CDC engineers later noticed that they could use the double-precision floating-point hardware to provide a reduced-range (48 bits vs. 60 bits) integer divide capability, almost for free.

One large Freescale (Motorola) integer DSP that I know of provides a "divide step" instruction: The programmer must stack as many of those instructions as he needs bits in his result to do a full-up division.  It is a fair pain to use.  I had to deal briefly with it a few years ago, while troubleshooting a normalized least mean squares (adaptive filter) application.

Read Hamming's Numerical Methods for Scientists and Engineers.  (Dover Press is the student's friend.)  In the very beginning of the book, he goes into some detail about why floating-point is used for numerical computation.  Also, ask around the EE department, and see if they have a digital signal processing elective.


问:
Why do we still use floats?
I understand why floats served a purpose in the past.  And I think I can see why they're useful in some simulation examples today.  But I think those example are more exceptional than common.  So I don't understand why floats are more prevalent in simple simulations rather than very high precision integers.

A classic argument is that floats provide a greater range, but high precision integers can meet this challenge now. For example: with modern 64-bit processors, we can do fast integer calculations up to 2^64. The solar system is a little less than 10 billion km in width. 10 billion km divided by 2^64 is about 5 microns. Isn't being able to represent position within the solar system to the precision of half a human hair enough?

On the flip-side, rounding errors from floating calculations can present problems.  You need to consider the scale of the calculations to make certain that you're not inadvertently introducing error to your simulation.

So why do personal computers even need FPUs anymore?  Why not just leave floats to the supercomputers?

答:
Your argumentation against floating point numbers is very fragile,
probably because of naivety. (No offense here, I find your question is
actually very interesting, I hope my answer will also be.)

A classic argument is that floats provide a greater range, but high
  precision integers can meet this challenge now. For example: with
  modern 64-bit processors, we can do fast integer calculations up to
  2^64. The solar system is a little less than 10 billion km in
  width. 10 billion km divided by 2^64 is about 5 microns. Isn't being
  able to represent position within the solar system to the precision
  of half a human hair enough?

You seem to make an implicit statement, according to which once we know
the scale of our problem, we can use fixed point arithmetic with respect
to this scale to solve that problem.

Sometimes, this is a valid approach, and this is the one picked by
Knuth to implement distance computations in TeX.  What makes the use
of fixed point arithmetic pertinent in this case is that all
quantities appearing within a computation are either integers or distances
occurring in a typesetting problem.  Because the field of applications
is so narrow, it makes sense to choose a very small unit length, much
smaller than what the human eye can perceive, and to convert all
quantities into multiples of this unit.  This leads to a very important result: in the typographical problems relying on this representation of numbers, we never need to multiply two lengths together, so that loss of precision caused by multiplications in fixed point arithmetic do not occur.

Most of the times, it is however a terrible approach, here are a few
reasons why:

There exists physical constants and you cannot always adapt their
units in a sensible way.

Consider your solar system setting. The gravitational constant is
6.67×10−11 N·(m/kg)2, the speed of light is 3.00x10+5 m/s, the mass
of the Sun is 1.9891×10+30 kg and the mass of the Earth is
5.97219×10+24.  In your fixed point setting, you will not be able
to represent the gravitational constant to a satisfying precision.
So you will change the unit.  But by doing so, you have to replace
each number—replacing well-known, familiar quantities, by cryptic
values.  Furthermore, it is very likely that finding a system to
appropriately represent all constants you need
might not even be possible. Think to quantum physicits working
with infinitely small particles whose speed is near the speed of light.

There exists mathematical unitless constants.

The value of Pi 3.1415 (up to the 4th decimal place) without any unit attached. There is
actually a lot of similar useful constants that cannot be
accurately represented in an arbitrary fixed point system.  In the
solar system setting you described, we can represent Pi with 6 decimal places,
which gives a terrible accuracy when computing the circumference of
a planet orbit, for instance.

In a fixed point system, we need to know in advance the size of
the quantity you are computing.

Assume that we still do not know the value of the gravitational constant. We would
make a lot of measures and write a computer program to find an approximation of that
constant.  Unfortunately, in the solar system setting you described, the gravitational
constant is represented by 0, which should be the, rather useless, result of our

computation.

Some mathematical functions will not work well with fixed precision
arithmetic, because of their growth rate.

The most important ones are the exponential and the gamma function, which practically
means that every program working with anything else than polynomials will be flawed.

In fixed point arithmetic, it is very hard to multiply and divide
numbers correctly.

This is because if we do not know a priori the size of the numbers, we cannot tell
if their product will fit in the representation. That is, we would have to check
manually for precision underflow before each multiplication.

Conclusion

While the conclusion of your question implies that fixed point arithmetic could be
sufficient for all-purpose computations and that floating point
arithmetic should be reserved to supercalculators, it is precisely the
converse which is true: floating point arithmetic is a very good and
very sensible tool for all-purpose computations, while fixed point
will only do well in very specific, well analysed, cases.

OwnerDisplayName: anon

Title: Why do we still use floats?


问:
WCF service to get an atom feed
I am very new to programming and my first task is to create a WCF service that will take an ATOM feed and expose it to my application. Now, I've read up on XML serialization and syndication but it doesn't seem to be what I need in my (lack of) experience.

Here is a snippet of the feed. It's generated by a seedlist spi

```<code><atom:generator version="1.2" lconn:version="4.5.0.0">
Seedlist Service Backend System</atom:generator>
<wplc:timestamp isPartial="false">AAABQtdnfpE=</wplc:timestamp>
<atom:category term="ContentSourceType/Wikis" scheme="com.ibm.wplc.taxonomy://feature_taxonomy"
label="Wikis"/>
<atom:title>Wikis : 0 entries of Seedlist WIKIS</atom:title>
<atom:updated>2013-12-09T13:49:13+01:00</atom:updated>
</code>```

Do I need to create objects for all these elements?

And what about these wplc elements?

```<code><wplc:action do="update"/>
<wplc:fieldInfo id="FIELD_ENTRY_TYPE" name="item type"
description="item type - page, file or wiki" type="string"
contentSearchable="false" fieldSearchable="true"
parametric="false" returnable="true" sortable="false"
supportsExactMatch="false"/>
<wplc:fieldInfo id="FIELD_TAG" name="Tag"
description="Document tag" type="string"
contentSearchable="true" fieldSearchable="true"
parametric="false" returnable="true" sortable="false"
supportsExactMatch="true"/>
</code>```

All the examples, tutorials and explanations I find are of simple xml files
So can I just use XML Reader to achieve this? And if so, I need some help.

Here is a sample WCF I found:

```<code>public class Service1 : IService1
    {
        public string GetData(string value)
        {
            WebRequest request = WebRequest.Create("http://wheremyxmlis/file.xml");
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            XmlReader reader = XmlReader.Create("http://wheremyxmlis/file.xml");
        reader = new XmlTextReader("http://wheremyxmlis.xml");

        try
        {

            reader = new XmlTextReader("http://wheremyxmlis/file.xml");

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.Write("<{0}>", reader.Name);
                        break;
                    case XmlNodeType.Text:
                        Console.Write(reader.Value);
                        break;
                    case XmlNodeType.CDATA:
                        Console.Write("<![CDATA[{0}]]>", reader.Value);
                        break;
                    case XmlNodeType.ProcessingInstruction:
                        Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
                        break;
                    case XmlNodeType.Comment:
                        Console.Write("<!--{0}-->", reader.Value);
                        break;
                    case XmlNodeType.XmlDeclaration:
                        Console.Write("<?xml version='1.0'?>");
                        break;
                    case XmlNodeType.Document:
                        break;
                    case XmlNodeType.DocumentType:
                        Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
                        break;
                    case XmlNodeType.EntityReference:
                        Console.Write(reader.Name);
                        break;
                    case XmlNodeType.EndElement:
                        Console.Write("</{0}>", reader.Name);
                        break;
                }
            }
        }

        finally
        {
            if (reader != null)
                reader.Close();

            response.Close();
</code>```

答:
This is the solution I managed to come up with and it works!

This is just a class file added to the WCF Service library

```<code>public class Item
{
    public string Link { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public string Author { get; set; }
    public DateTime Updated { get; set; }
    public string FeedType { get; set; }

    public string Tag { get; set; }
    public Item()
    {
        //Link = "";
        //Title = "";
        //Name = "";
        //Content = "";
        //Updated = DateTime.Today;
        //    FeedType = FeedType.RSS;
    }
}

/// <summary>
/// A simple RSS, RDF and ATOM feed parser.
/// </summary>
public class FeedParser
{
    /// <summary>
    /// Parses the given <see cref="FeedType"/> and returns a <see cref="IList&lt;Item&gt;"/>.
    /// </summary>
    /// <returns></returns>
    public IList<Item> Parse(XDocument doc, string feedType)
    {
        switch (feedType)
        {
            case "RSS":
                return ParseRss(doc);
            case "RDF":
                return ParseRdf(doc);
            case "Atom":
                return ParseAtom(doc);
            default:
                throw new NotSupportedException(string.Format("{0} is not supported", feedType.ToString()));
        }
    }

    /// <summary>
    /// Parses an Atom feed and returns a <see cref="IList&lt;Item&gt;"/>.
    /// </summary>
    public virtual IList<Item> ParseAtom(XDocument doc)
    {
        try
        {
            // Feed/Entry
            var entries = from item in doc.Root.Elements().Where(i => i.Name.LocalName == "entry")
                          select new Item
                          {
                              FeedType = "Atom",
                              Title = item.Elements().First(i => i.Name.LocalName == "title").Value,
                              Author = item.Elements().First(i => i.Name.LocalName == "author").Value,                     //must add child element "name"
                              Content = item.Elements().First(i => i.Name.LocalName == "summary").Value,
                              Tag = item.Elements().First(i => i.Name.LocalName == "field").Value,                       //must specify FIELD_TAG
                              Link = item.Elements().First(i => i.Name.LocalName == "link").Attribute("href").Value,
                              Updated = ParseDate(item.Elements().First(i => i.Name.LocalName == "updated").Value),

                          };
            return entries.ToList();
        }
        catch (Exception ex)
        {
            return new List<Item>();
        }
    }

    /// <summary>
    /// Parses an RSS feed and returns a <see cref="IList&lt;Item&gt;"/>.
    /// </summary>
    public virtual IList<Item> ParseRss(XDocument doc)
    {
        try
        {
            // RSS/Channel/item
            var entries = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")
                          select new Item
                          {
                              FeedType = "RSS",
                              Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
                              Author = item.Elements().First(i => i.Name.LocalName == "name").Value,                 //Newly added
                              Link = item.Elements().First(i => i.Name.LocalName == "link href").Value,
                              Updated = DateTime.Parse(item.Elements().First(i => i.Name.LocalName == "updated").Value),
                              Title = item.Elements().First(i => i.Name.LocalName == "title").Value
                          };
            return entries.ToList();
        }
        catch
        {
            return new List<Item>();
        }
    }

    /// <summary>
    /// Parses an RDF feed and returns a <see cref="IList&lt;Item&gt;"/>.
    /// </summary>
    public virtual IList<Item> ParseRdf(XDocument doc)
    {
        try
        {
            // <item> is under the root
            var entries = from item in doc.Root.Descendants().Where(i => i.Name.LocalName == "item")
                          select new Item
                          {
                              FeedType = "RDF",
                              Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
                              Author = item.Elements().First(i => i.Name.LocalName == "name").Value,
                              Link = item.Elements().First(i => i.Name.LocalName == "link href").Value,
                              Updated = DateTime.Parse(item.Elements().First(i => i.Name.LocalName == "updated").Value),
                              Title = item.Elements().First(i => i.Name.LocalName == "title").Value
                          };
            return entries.ToList();
        }
        catch
        {
            return new List<Item>();
        }
    }

    private DateTime ParseDate(string date)
    {
        DateTime result;
        if (DateTime.TryParse(date, out result))
            return result;
        else
            return DateTime.MinValue;
    }
}
 }
</code>```

And here is the existing Service1.cs that I modified

```<code>public class Service1 : IService1
{
    public IList<Item> GetData()
    {

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("URL of the seedlist");

        request.Method = "GET";

        request.Accept = "application/atom+xml";

        request.ContentType = "application/atom+xml;type=entry";

        request.Credentials = new NetworkCredential("username", "password");

        ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        XDocument xDoc = XDocument.Load(new StreamReader(response.GetResponseStream()));

        FeedParser parser = new FeedParser();

        var items = parser.Parse(xDoc, "Atom");

        return items;

    }
    //for testing purpose only, accept any dodgy certificate...
    public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    public Item GetItemByLink(string url)
    {
        var items = GetData();
        foreach (var item in items)
        {
            if(item.Link == url)
            {
                return item;
            }

        }
        return null;

    }
}
</code>```

Title: WCF service to get an atom feed

Body:
This is the solution I managed to come up with and it works!

This is just a class file added to the WCF Service library

public class Item
{
    public string Link { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public string Author { get; set; }
    public DateTime Updated { get; set; }
    public string FeedType { get; set; }

    public string Tag { get; set; }
    public Item()
    {
        //Link = "";
        //Title = "";
        //Name = "";
        //Content = "";
        //Updated = DateTime.Today;
        //    FeedType = FeedType.RSS;
    }
}

/// <summary>
/// A simple RSS, RDF and ATOM feed parser.
/// </summary>
public class FeedParser
{
    /// <summary>
    /// Parses the given <see cref="FeedType"/> and returns a <see cref="IList&amp;lt;Item&amp;gt;"/>.
    /// </summary>
    /// <returns></returns>
    public IList<Item> Parse(XDocument doc, string feedType)
    {
        switch (feedType)
        {
            case "RSS":
                return ParseRss(doc);
            case "RDF":
                return ParseRdf(doc);
            case "Atom":
                return ParseAtom(doc);
            default:
                throw new NotSupportedException(string.Format("{0} is not supported", feedType.ToString()));
        }
    }

    /// <summary>
    /// Parses an Atom feed and returns a <see cref="IList&amp;lt;Item&amp;gt;"/>.
    /// </summary>
    public virtual IList<Item> ParseAtom(XDocument doc)
    {
        try
        {
            // Feed/Entry
            var entries = from item in doc.Root.Elements().Where(i => i.Name.LocalName == "entry")
                          select new Item
                          {
                              FeedType = "Atom",
                              Title = item.Elements().First(i => i.Name.LocalName == "title").Value,
                              Author = item.Elements().First(i => i.Name.LocalName == "author").Value,                     //must add child element "name"
                              Content = item.Elements().First(i => i.Name.LocalName == "summary").Value,
                              Tag = item.Elements().First(i => i.Name.LocalName == "field").Value,                       //must specify FIELD_TAG
                              Link = item.Elements().First(i => i.Name.LocalName == "link").Attribute("href").Value,
                              Updated = ParseDate(item.Elements().First(i => i.Name.LocalName == "updated").Value),

                          };
            return entries.ToList();
        }
        catch (Exception ex)
        {
            return new List<Item>();
        }
    }

    /// <summary>
    /// Parses an RSS feed and returns a <see cref="IList&amp;lt;Item&amp;gt;"/>.
    /// </summary>
    public virtual IList<Item> ParseRss(XDocument doc)
    {
        try
        {
            // RSS/Channel/item
            var entries = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")
                          select new Item
                          {
                              FeedType = "RSS",
                              Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
                              Author = item.Elements().First(i => i.Name.LocalName == "name").Value,                 //Newly added
                              Link = item.Elements().First(i => i.Name.LocalName == "link href").Value,
                              Updated = DateTime.Parse(item.Elements().First(i => i.Name.LocalName == "updated").Value),
                              Title = item.Elements().First(i => i.Name.LocalName == "title").Value
                          };
            return entries.ToList();
        }
        catch
        {
            return new List<Item>();
        }
    }

    /// <summary>
    /// Parses an RDF feed and returns a <see cref="IList&amp;lt;Item&amp;gt;"/>.
    /// </summary>
    public virtual IList<Item> ParseRdf(XDocument doc)
    {
        try
        {
            // <item> is under the root
            var entries = from item in doc.Root.Descendants().Where(i => i.Name.LocalName == "item")
                          select new Item
                          {
                              FeedType = "RDF",
                              Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
                              Author = item.Elements().First(i => i.Name.LocalName == "name").Value,
                              Link = item.Elements().First(i => i.Name.LocalName == "link href").Value,
                              Updated = DateTime.Parse(item.Elements().First(i => i.Name.LocalName == "updated").Value),
                              Title = item.Elements().First(i => i.Name.LocalName == "title").Value
                          };
            return entries.ToList();
        }
        catch
        {
            return new List<Item>();
        }
    }

    private DateTime ParseDate(string date)
    {
        DateTime result;
        if (DateTime.TryParse(date, out result))
            return result;
        else
            return DateTime.MinValue;
    }
}
 }

And here is the existing Service1.cs that I modified

public class Service1 : IService1
{
    public IList<Item> GetData()
    {

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("URL of the seedlist");

        request.Method = "GET";

        request.Accept = "application/atom+xml";

        request.ContentType = "application/atom+xml;type=entry";

        request.Credentials = new NetworkCredential("username", "password");

        ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        XDocument xDoc = XDocument.Load(new StreamReader(response.GetResponseStream()));

        FeedParser parser = new FeedParser();

        var items = parser.Parse(xDoc, "Atom");

        return items;

    }
    //for testing purpose only, accept any dodgy certificate...
    public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    public Item GetItemByLink(string url)
    {
        var items = GetData();
        foreach (var item in items)
        {
            if(item.Link == url)
            {
                return item;
            }

        }
        return null;

    }
}


问:
How do you split work on web apps?
About a year ago at my workplace we decided to get into developing a web app for internal use (as part of a more intricate system which is irrelevant to this question). No one really had experience in web development, so probably some of our decisions were wrong, but all in all we've had success with the tool we were developing. Since we did have experience developing in Python, we chose Django as our platform.

My question is about "who does what". The way we split our work was: there is one team which handles all the Python code - which means all the Django urls, views and models, as well as the actual backend to handle asynchronous task execution (something a bit like Celery). A different team (more precisely, a single person in a different development group - but this is just implementation) is responsible for the templates (data binding), javascript, design, HTML, CSS, etc.

We have been working like this, as I said, for about a year now. I'm starting to think that maybe the line of responsibilities between the two teams is wrong. The reason is that there's a pretty big overhead whenever we need to interact - which is a lot. For example, when we add a new table and we want to display it, we need to let the "frontend guy" know what the url would be and what it would contain. Then we need to integrate out work to see if everything's alright. Sometimes we didn't pass enough context to the template to make it work and there's a slow ping-pong of information between us.

So my question is this - what is the accustomed way to split work on web apps? Who takes care of the different modules - models, views, urls, templates, design, user experience, HTML, CSS, javascript?

答:
In small teams you need some cross over of skills, otherwise you're spending a lot of time communicating ideas between devs who may have differing understandings of how those ideas might be implemented (as you have found). Better to make each dev responsible for a single feature, including front end and back end. Communication on ideas then only needs to be at the conceptual level.

Of course not all devs have their strengths and weaknesses, and I've not found that expecting the same performance on all tasks from all devs is practical. Assign features based on skill set. If the feature is more front end than back, give it to the front end guy, and vice versa.

As projects get bigger, then you'll see more specialization in developers. In this scenario, the communicative effort is not such a problem as the feature is profitable / valuable enough to make spending the time worth while.

Title: How do you split work on web apps?


问:
Lisp/Clojure: Removing unnecessary parentheses through conventions
I am fascinated to Lisp as it is simple yet powerful. I am just a beginner and I know there have been lots of discussions on removing parentheses from Lisp and its dialects. Yet I request Lisp ninja's to take few minutes answering this.

Will there be any side effects in Lisp/Clojure if they had followed 2 conventions below:

```<code>;; function declaration
defn function-name param-1 .... param-n
  ...
  function-body ;; not (function-body)
  ...

;; function call
function-name param-1 ... param-n ;; not (function-name param-1 ... param-n)
</code>```

While still using () or [] for inline and nested expressions.

```<code>(println "hello, ") (println "world !!!") ;; inline
= a (- 2 3) ;; nested
</code>```

答:
You can do that, and much more, using sweet-expressions. There is already a working implementation of sweet-expressions for Scheme, which I encourage you to study. The basic idea is that you replace the standard S-expression reader with a sweet-expression reader; everything else stays the same, and you retain homoiconicity and the ability to use macros.

The question is how to implement sweet-expressions in Clojure, since curly braces are already used as a notation for maps, sets, and metadata.


答:
Because sometimes even a 64-bit integer won't give you enough range.

For example, in the physics code I'm currently working on, I need to convert some molecular masses between grams per mole (which the input / output format uses) and kilograms per molecule (which the internal calculations need for unit consistency).

There are about 279 molecules in a mole, so this particular conversion involves multiplying or dividing the quantities by a factor of 1,000 × NA ≈ 6.022 × 1026 ≈ 289.

Sure, this particular issue could be handled in fixed point, simply by using different fixed-point numeric types for per-mole and per-molecule quantities, but that adds a lot of complexity to code that doesn't really need it.  And this is far from an isolated case — the physics calculations themselves often involve multiplication with things like Boltzmann's constant ≈ 2-76.  In theory, I could handle all of that by using a lot of different fixed-point types and keeping track of which numbers need to be stored using which type, but why bother?  Floating point lets me use a single numeric type to store all of them.

Besides, the kicker here is that these molecular masses are ultimately based on experimental data.  None of them are known to more than ten significant digits or so, and even that is way more than the precision of some other parameters that enter the calculations.  Even single-precision floats would be more than enough to store them — although I'm actually using doubles because, well, there's no real reason not to.

Title: Why do we still use floats?

Body:
I understand why floats served a purpose in the past.  And I think I can see why they're useful in some simulation examples today.  But I think those example are more exceptional than common.  So I don't understand why floats are more prevalent in simple simulations rather than very high precision integers.

A classic argument is that floats provide a greater range, but high precision integers can meet this challenge now. For example: with modern 64-bit processors, we can do fast integer calculations up to 2^64. The solar system is a little less than 10 billion km in width. 10 billion km divided by 2^64 is about 5 microns. Isn't being able to represent position within the solar system to the precision of half a human hair enough?

On the flip-side, rounding errors from floating calculations can present problems.  You need to consider the scale of the calculations to make certain that you're not inadvertently introducing error to your simulation.

So why do personal computers even need FPUs anymore?  Why not just leave floats to the supercomputers?


答:
My preference is to work on "features" rather than tiers of an application, whether it be a website or otherwise.

Any kind of "tiering" be it in an application or some other boundary (physical geography, groups in a company) is a barrier to development.

Communication needs are increased, and there are more potential blockers.

Title: How do you split work on web apps?

Body:
About a year ago at my workplace we decided to get into developing a web app for internal use (as part of a more intricate system which is irrelevant to this question). No one really had experience in web development, so probably some of our decisions were wrong, but all in all we've had success with the tool we were developing. Since we did have experience developing in Python, we chose Django as our platform.

My question is about "who does what". The way we split our work was: there is one team which handles all the Python code - which means all the Django urls, views and models, as well as the actual backend to handle asynchronous task execution (something a bit like Celery). A different team (more precisely, a single person in a different development group - but this is just implementation) is responsible for the templates (data binding), javascript, design, HTML, CSS, etc.

We have been working like this, as I said, for about a year now. I'm starting to think that maybe the line of responsibilities between the two teams is wrong. The reason is that there's a pretty big overhead whenever we need to interact - which is a lot. For example, when we add a new table and we want to display it, we need to let the "frontend guy" know what the url would be and what it would contain. Then we need to integrate out work to see if everything's alright. Sometimes we didn't pass enough context to the template to make it work and there's a slow ping-pong of information between us.

So my question is this - what is the accustomed way to split work on web apps? Who takes care of the different modules - models, views, urls, templates, design, user experience, HTML, CSS, javascript?


问:
How to do structured code reviews
We need to do pre-check-in code reviews. We are using Visual Studio and TFS.

The built in code review functionality, is a bit odd to me. If I "reject" a check-in and comments what needs work, the review goes away.

When the developer then makes the changes, he requests a new review, and I start all over again.

Now, let's just say there are 10 files in this check-in. Maybe 7 of them were originally fine. Now, I have to review them again, as we are doing a brand new review. OR, I can track myself, what I have done.

I can also, ONLY compare code with the original version, not the one from the reject review.

So, my questions are:

what do you guys do?

What are your experiences with pre-checkin code reviews?

答:
I prefer to do the checkin, assuming the developer has done the work correctly (ie be optimistic about their code quality)

If it turns out a review requires rework, then the dev can checkin fixes - in many ways this is exactly the approach taken with bugs, commit; build; test; commit fixes. Its not a problem with releases, why should a code review be any different?

I always create a ticket for the review, just like any other task - and track the progress of it, so the dev commits, he creates a new code review task for the commit and assigns it to the reviewer who then uses it to record any review failures that need work - and passes it back to the dev who fixes and re-assigns, or closes it.

The developer should be working on a branch rather than the mainline trunk, you can then perform the review without holding him up - he can continue to work on other tasks, while he waits for you to perform the review.

In the old days I used ReviewBoard for reviews - this requires you to upload a diff (the SCM was automated to provide these and create the review tasks). Now I'd use Redmine which can integrate the review process with the SCM tool and its inbuilt ticket tracker. (you will need the CodeReview plugin though).

In all cases, review after commit - its the only way to keep productivity up.

quick edit: the benefit of post-commit include:
a) if you mark the revision you reviewed, the coder cannot cheat and tweak their code when the commit it after the review...
b) the SCM tool gives you a diff of all the changes made since the last review, making review easier.
c) waiting for the review doesn't block the dev from working.

I would work with branches in this case anyway: dev works on a branch, it gets reviewed and merged onto a 'for testing' branch, is tested and then gets merged onto a 'for release' branch. This way, you can easily see that the process for review is exactly like the process for test so you can manage your entire delivery process the same way.

Title: How to do structured code reviews


问:
How to organise the different bits and pieces in an agile environment?
Trying to make our shop an agile environment, we struggle with some bits and pieces of that world. While not making it waterfally, we do have to have some sort of agreement on what a new feature needs to do. We follow the KISS and "minimally viable product" principle. Still, after discussing a story, we end up with:

UI/UX design

Acceptance criteria

Constraints

Use cases

Some extra specifications (like what fields to show in tables etc)

As tools we use JIRA, Greenhopper, Balsamiq, Glyphy and Confluence and they are working very well but we're not quite sure where to store which bits and how to make this work together well.

How do you guys approach that. Please include details on how far you go detailing the feature before development starts.

答:
When first starting the project, the epic stories go into JIRA OnDemand with little more than a title and perhaps a basic description to allow for prioritization and some very very rough estimation.

Then our product owners start tackling from the top to prepare the stories by filling out acceptance criteria into the description of the story, and attaching any screenshots, PDFs, etc. of wireframes or designs that have been completed for that story directly to the story in JIRA.

At this point, we still are only using the Plan view of the Agile board, and haven't created sub-tasks.

Our teams then go through the estimation process to have the story points added to each story.  As estimation and sprint planning occurs, stories may get broken down into multiple smaller stories on the plan board in order to support taking the work into the next sprint.

Once we have a sprint ready, we begin creating the sub-tasks on the stories for the items.  We keep these sub-tasks very light-weight (usually just a title to remind us) but sometimes if the team has some implementation ideas we will add that to the appropriate task.

Our source design files are not kept in JIRA, but in the appropriate design area on our network, or our client's, or DropBox, or wherever is agreed upon for the project.

That's a rough overview of what we are doing, but in direct relation to your list:

UI/UX design: Source files in its own repository, appropriate outputs directly on the stories in JIRA

Acceptance criteria: We had toyed with using sub-tasks for these, but have found that maintaining directly on the story in the description has been easier for tracking.

Constraints: Depending on the constraint, this is either noted directly on the story (if story-specific) or is tracked as its own story that needs to be met with specific development effort and testing (for example, accessibility support).

Use Cases: We keep our test cases/use cases as a special type of sub-task below the story so that the team can easily find all of the cases that will need to be supported and tested, and can also then track progress of completion by moving them through test and completing them.

Additional specifications: We store these directly on the story, if short. If a visual or full spreadsheet is required, these are attached as files on the story.


答:
What works for me and my company may not work for your (or for others).

We take a pragmatic approach and take the parts of the "development process" that work best for us. Some of these will be agile, some will be waterfall.

On some projects with some clients, some parts of the process will have more emphasis.

Title: How to organise the different bits and pieces in an agile environment?

Body:
Trying to make our shop an agile environment, we struggle with some bits and pieces of that world. While not making it waterfally, we do have to have some sort of agreement on what a new feature needs to do. We follow the KISS and "minimally viable product" principle. Still, after discussing a story, we end up with:

UI/UX design

Acceptance criteria

Constraints

Use cases

Some extra specifications (like what fields to show in tables etc)

As tools we use JIRA, Greenhopper, Balsamiq, Glyphy and Confluence and they are working very well but we're not quite sure where to store which bits and how to make this work together well.

How do you guys approach that. Please include details on how far you go detailing the feature before development starts.


问:
Async function iterated calls
I'm new to using async calls in ajax. My problem is that I have two server "tasks": one that just checks if session is set (fast), and another that sets the session (slower). I want to check if the session is set and if not, set it. And I want to try X number of times (I'm unsure if I really need to but that, but that is another question). If I just do it with a “while” or a “for” and not do think about that it is async, I will generate problems like to many calls, and it will not be check session then set session. I could to it on the server, but I do not want to send the request data if session is set, only if it is not set. Below is the way I'm trying to do it now, but I'm unsure if there is a better way of doing it? The code below just implements the idea and is not tested.

The idea is that send the counter back and forth between checking and sending session in the success function. What I do not like about the code is that the set session really is just understandable in context of checkSession. If I in some time come back to the code and just want to setSession, I would have a magic number of X to make sure it does not check the session also. Is there a smoother way of doing this? If the code smells even worse, please tell me.

```<code>self.start = function() {
    self.checkSession(0);
};
self.checkSession = function(count) {
    server.CheckSession(function(returnValue){
        if(returnValue == false && count < 4){
           count++;
           self.setSession(count);
        }},function(err){});};
self.setSession = function(count) {
      var sessionData = someData;
      server.SetSession(sessionData, function(d){
          self.checkSession(count);
}, function(err){});};
</code>```

答:
I think you must call your first ajax synchronously using declared async = false; in your ajax call.

It will call your asynchronous ajax function synchronously so that after getting response from the ajax it will execute next code.

Title: Async function iterated calls


问:
How to deal with the "programming blowhard"?
So I'm sure everyone has run into this person at one point or another, someone catches wind of your project or idea and initially shows some interest. You get to talking about some of your methods and usually around this time they interject stating how you should use method X instead, or just use library Y. But not as a friendly suggestion, but bordering on a commandment. Often repeating the same advice over and over like a overzealous parrot.

Personally, I like to reinvent the wheel when I'm learning, or even just for fun, even if it turns out worse than what's been done before. But this person apparently cannot fathom recreating ANY utility for such purposes, or possibly try something that doesn't strictly follow traditional OOP practices, and will settle for nothing except their sense of perfection, and thus naturally heave their criticism sludge down my ears full force. To top it off, they eventually start justifying their advice (retardation) by listing all the incredibly complex things they've coded single-handedly (usually along the lines of "trust me, I've made/used program X for a long time, blah blah blah").

Now, I'm far from being a programming master, I'm probably not even that good, and as such I value advice and critique, but I think advice/critique has a time and place. There is also a big difference between being helpful and being narcissistic. In the past I probably would have used a somewhat stronger George Carlin style dismissal, but I don't think burning bridges is the best approach anymore.

Do you have any advice on how to deal with this kind of verbal flogging?

答: Hit them with the "You should never use something you don't understand" line.</p>

ContentLicense: CC BY-SA 2.5


答:
Why not just use one call setOrReturnSession, which either returns the current session if it's already set, or creates a new session and returns that.

Yes it's marginally slower to send your session data across the wire on every call, but it's much much faster than running both calls synchronously almost every time.

It also means that all your session logic stays on the server where it belongs, rather than having it smeared across the client and server the way you do now.

Title: Async function iterated calls

Body:
I'm new to using async calls in ajax. My problem is that I have two server "tasks": one that just checks if session is set (fast), and another that sets the session (slower). I want to check if the session is set and if not, set it. And I want to try X number of times (I'm unsure if I really need to but that, but that is another question). If I just do it with a “while” or a “for” and not do think about that it is async, I will generate problems like to many calls, and it will not be check session then set session. I could to it on the server, but I do not want to send the request data if session is set, only if it is not set. Below is the way I'm trying to do it now, but I'm unsure if there is a better way of doing it? The code below just implements the idea and is not tested.

The idea is that send the counter back and forth between checking and sending session in the success function. What I do not like about the code is that the set session really is just understandable in context of checkSession. If I in some time come back to the code and just want to setSession, I would have a magic number of X to make sure it does not check the session also. Is there a smoother way of doing this? If the code smells even worse, please tell me.

```<code>self.start = function() {
    self.checkSession(0);
};
self.checkSession = function(count) {
    server.CheckSession(function(returnValue){
        if(returnValue == false && count < 4){
           count++;
           self.setSession(count);
        }},function(err){});};
self.setSession = function(count) {
      var sessionData = someData;
      server.SetSession(sessionData, function(d){
          self.checkSession(count);
}, function(err){});};
</code>```


问:
Help putting together an Open Source Friendly contract but does not allow day job work to be Open Sourced
So I just was hired at a place that had only one Developer and that was the co owner. Their employee handbook had something to the effect of the following.

All IP, inventions or software you develop while at X company is the
  property of the company. Additionally you will have to provide a list
  of all prior inventions, software or IP developed prior to working for
  company x.

This is an issue for me because I have both side projects and occasionally contribute to open source stuff and would like to continue to have the ability to to both.

I talked about it with the owner and he agreed to making changes and asked me for an outline that is fair for both parties. He would take that to a lawyer and they would go over it and apply it. So with that I'm looking for some wording I could submit to that effect to helping me put this together in such a way that I and any other software developers are protected as well as company x and its software. That or a resource or guideline for this sort of thing.

To clarify, the company's software isn't allowed to be made open but the employees will be allowed to work on side project both of an open-source and private nature as long as they don't come to compete with the company's best interest. If it helps we are in the USA.

答:
When it comes to formalizing contracts, you shouldn't rely on what people on the internet tell you. Any single word needs to be chosen carefully, and when you are careless with the wording, then either the whole contract is void because it contradicts the law or it might says something which is completely different from what you actually wanted it to say.

The sentence in your question above is a good example for the latter. What they want to say is likely something like:

"We would like to know what obligations and ties you still have to
  prior projects you were involved in".

But what it actually says is:

"Give us a list of every idea you ever had, every single program you
  have ever written (published or not) and every piece of art you ever
  produced, including that picture you drew when you were three, and
  when you forget something and we find out we can fire you immediately".

Hire a lawyer specialized in IP- and employment law. Have a meeting with the lawyer, an employer representative and an employee representative, explain to him what the goals of the contract are ("We would allow [scenario A] but we don't want [scenario B] to happen"), and let him write the contract.


答:
Company ownership of software that you develop is a legal matter; see Joel Spolsky's excellent description and analysis for more details.  As such, it's really up to a lawyer to figure out wording that's acceptable.

Regarding the rationale of asking for past work, see this question.

If you're looking for non-legal-quality wording, I've seen a corporate code of ethics that includes language similar to the following:

We may wish to pursue employment or opportunities besides our employment with Acme.  We will not do so if it competes with Acme or interferes with our ability to fulfill our responsibilities to Acme.

We may develop ideas, processes and technology on Acme's behalf. This “intellectual property” belongs to Acme. Each of us must assign the rights to any such intellectual property to Acme.

This kind of language is probably not rigorous enough for a contract and may not work in court, but for an employee handbook, it should be fine.

Title: Help putting together an Open Source Friendly contract but does not allow day job work to be Open Sourced

Body:
So I just was hired at a place that had only one Developer and that was the co owner. Their employee handbook had something to the effect of the following.

All IP, inventions or software you develop while at X company is the
  property of the company. Additionally you will have to provide a list
  of all prior inventions, software or IP developed prior to working for
  company x.

This is an issue for me because I have both side projects and occasionally contribute to open source stuff and would like to continue to have the ability to to both.

I talked about it with the owner and he agreed to making changes and asked me for an outline that is fair for both parties. He would take that to a lawyer and they would go over it and apply it. So with that I'm looking for some wording I could submit to that effect to helping me put this together in such a way that I and any other software developers are protected as well as company x and its software. That or a resource or guideline for this sort of thing.

To clarify, the company's software isn't allowed to be made open but the employees will be allowed to work on side project both of an open-source and private nature as long as they don't come to compete with the company's best interest. If it helps we are in the USA.


问:
How should an embedded OS be combined with user code?
As a side-effect of an embedded project I've been working on, I've developed a small operating system for an ARM processor. While the OS and my user code are in separate directories and have clean boundaries between them, they're built into a single image using a single Makefile.

I'd like to release the OS as open source. It consists of an exokernel and userland driver libraries.

What I'm trying to decide is how a user of this OS should combine it with their own code at build time so they have a single image to flash. I can think of three possibilities:

1) Have the user include the OS source files as part of their project. They'd be recreating the setup I currently have, and it's how FreeRTOS, for example, appears to do it (although it only has three files).

2) Have the OS build itself into a .a file that the user code can link with. That would allow the user full control over memory placement using their own linker script (and allow the linker to tell them when a combined text, BSS or data section exceeds its space).

3) Have the OS build itself into a raw binary that expects to have the user code concatenated onto the end of it. The user code would begin with a small header (placed by the linker script) that had the address of the main function. The user code would also link with a .a file of just the userland drivers, not the kernel.

(1) would make it easiest for me to develop the OS and my user code in parallel with git subtree. (2) seems to have the most useful link process. (3) gives the biggest separation.

If you were using it, which would you prefer and why?

答:
For a small-systems, hardcore embedded OS, the first option is the only really viable one.

The problem is that for nearly every chipset, you would have to make small adjustments to the interfacing with the hardware and that gives you a high risk that the OS needs to be re-compiled for the new chipset.

So, the first option is not only the easiest for you, but also the easiest for getting it incorporated in the next project.


问:
How to simulate a REST API?
I am working on a new project which will query data from a 3rd party REST API. This is for a real time sports data feed, so the feed only works when a game is actually taking place.

Although the 3rd party provides good documentation (XSD, etc), they have no way to simulate a game happening, and so to test code I have written against this API I would have to wait for an actual game to be happening.

My only recourse is to write code to simulate a game on my own, but it seems like a lot of work. How would you approach this?

答: Wait until a game is happening. Capture every event from the feed. Write a simulator that replays the events at the appropriate times. Voila, you have a feed simulator with real data.

Title: How to simulate a REST API?


答:
Clauses like that are sometimes constrained by local law. For example, in Washington state (USA):

[...]an employment agreement which provides that an employee shall assign or offer to assign any of the employee's rights in an invention to the employer does not apply to an invention for which no equipment, supplies, facilities, or trade secret information of the employer was used and which was developed entirely on the employee's own time, unless (a) the invention relates (i) directly to the business of the employer, or (ii) to the employer's actual or demonstrably anticipated research or development, or (b) the invention results from any work performed by the employee for the employer. Any provision which purports to apply to such an invention is to that extent against the public policy of this state and is to that extent void and unenforceable.
   [ Source ]

Also, employers may be interested in major contributions or previous inventions for reasons that don't include ownership. They may be looking to find out if there are any licensing or IP conflicts that could arise from previous projects.

All that said, only your personal lawyer is qualified or can be trusted to look out for your interests and dispense advice on how to approach your specific situation.


问:
GPL and confidential business rules in a single page application
I am designing a web app for a client who wants to keep some of his business rules private, we have an NDA. In a nutshell, customers use the app to book a service, and employees use it to keep track of bookings. Since the front end is public (and untrustworthy), all of the decisions that are determined by business rules have to happen on the server.

Now, if I use a very nice GPLv3 licensed module, then that SPA has to be licensed under a compatible license, like MIT, because the app (including the module) is being distributed to everyone who visits the site. That's fine, it isn't possible to hide anything on the front end anyways. I don't contribute enough back to the community, and I would love to release an example of a production grade SPA as open source. It would be a great way to start a blog.

The server would implement a publicly defined API, and the front end would work with any server that implements the API. I would include a simple server with the GPL licensed app so that it can be run by anyone. The server doesn't depend on the client, because could it could be replaced with curl.

What I am wondering is, in this scenario, could I keep my client's unique business rules private in a server app without violating the rules or intentions of the GPL?

答:
Yes, you can keep your client's business rules private and no, you don't need to distribute the server side code.

If the server side services were using the GPL'd library, you would fall into a particular exception that doesn't consider hosting a web service as distribution.

Start with this question from the FSF FAQ.

A company is running a modified version of a GPL'ed program on a web site. Does the GPL say they must release their modified sources?

  The GPL permits anyone to make a modified version and use it without ever distributing it to others. What this company is doing is a special case of that. Therefore, the company does not have to release the modified sources.

 emphasis added

If it's the web app (the SPA in this case) that includes the GPL'd library, then it's  important to remember that the web app has a separate license from the web services that are being provided.  Since all of the confidential business rules are on the server, there is no risk of disclosure via GPL.  The client license doesn't necessarily pertain to the server license.

Nothing within the spirit of the GPL would impose the GPL license upon the server just because a client is GPL'd.

Finally, if you're concerned that the API offered through the services may disclose something of a confidential nature, then wrap those services with a facade that obfuscates what is actually happening.


问:
When to favor ASP.NET WebForms over MVC
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?

答:
This is a stale question with a lot of answers but none had the answer I would have expected to be listed.

The short answer is:

Use ASP.NET MVC if you intend to properly build a web application with modern programming conventions and industry embraced patterns for the ASP.NET platform. On the down side you will be expected to know how HTML and client-side resources (Javascript, CSS) work as well as ramp up on the MVC programming mindset which has a steep learning curve but reaches a sudden end once grasped.

Use ASP.NET Web Forms if you're using or want to use a GUI-centric, RAD (Rapid Application Development), drag-and-drop approach to prototyping something very quickly, i.e. push-button / data grid behavior wired up within 15 minutes, and the solution is not intended to be something supported by developers. Or, Use ASP.NET Web Forms if you have a background in GUI or Windows Forms development and you desire to transfer your knowledge to the Web.

But to look at this properly, you have to understand the history of each.

ASP.NET Web Forms was Microsoft's answer to those who had been building dynamic web applications using Visual Basic 6 ActiveX controls, VB6 DLLs on the server, and ASP Classic. At the time, web development using these Microsoft tools was a real mess. Along with the entirety of the .NET Framework which was the output of Microsoft essentially going back to the drawing board on how to do productive business programming on the Windows stack, ASP.NET Web Forms was, in its day, amazing and beautiful.

The whole approach was to give developers the best of both worlds of something very similar to Windows application development, but with the power of internet services. The idea was that, just as with a VB6/WinForms "Form" (a window) likewise a web page is a form (just like a window, see), and on that form you could drag-and-drop labels, textboxes, data grids, buttons, and other things that VB/WinForms GUI developers were accustomed to.

To make a button do something, after dragging-and-dropping it you just double-click it in the designer and boom you're in the code editor, telling the form what to do when that "click" event happens. This was exactly how Windows GUI developers created software using GUI tooling of VB6 and competing tools, except now the code is executing on the server! Wow!

This was 2002 technology. Amazing and beautiful in its time as an answer to internet-enabled GUI solutions for RAD development, it brought a sense of power to a messy world of software developers that had business objectives that they needed to accomplish.

Unfortunately, this programming model emphasizes so much the metaphor of Windows GUI programming that it carries with it the burden of its necessary implementation details, all the encumbering baggage necessary to accommodate the event life cycles and the tucking away the ugly details of the simple HTML and script that these drag-and-drop components and controls would output. And at the end of the day, developers supporting real applications inevitably had to dig deep into these components or write their own, and consequently they would fight battles with this infrastructure, battles which would leave behind piles upon piles of cruft, pulled hair, and tears.

Back up. Wash your hands. Let's look at the business problem again. What are our business objectives?

We need to build and manage web applications. Our constraints are that we have the World Wide Web, which sits on HTTP, HTML, Javascript, and CSS, and on the server we have business rules, databases, and a small handful of great programming languages (e.g. C#). Do we really need this Windows GUI metaphor to drive our development methodology? Why can't we just focus on the application problems and do away with the GUI metaphors?

This is where ASP.NET MVC comes in. It started out by a rebellion of developers who called themselves "Alt.Net" who wanted to get back to proper and pure software development principles. No more muss and fuss, just focus on business objectives and software best practices.

What this really translates to in this case is:

Separation of concerns. For example, a data component doesn't need to know how its data is going to be rendered, nor should view markup be encumbered with database connection configuration details, and in this way a developer can focus in on his area of concern when editing and testing code.

Exposure and full support for exposure to the nitty gritty of HTML and related resources. In Web Forms, HTML is tucked away, developers are discouraged from fussing with that. In ASP.NET MVC, developers are rather encouraged to manage those details; in fact it's a necessity. The advantage here is that the developer can re-learn to appreciate the clean semantics of HTML, CSS, and script, and work with it rather than against it.

Testability of business objects. Controllers and models are much better suited for programmatic unit testing, so that implementations can be validated to meet business objectives, and changes can be verified that they will not break. With Web Forms it was difficult to test as components were not designed to be tested individually and the entire development output revolved around page forms and their event lifecycles with the muck of business logic and presentation logic deeply intertwined.

Note that HTML is already a very high-level markup language, as is Javascript a high-level programming language. The whole story would have been different if we were dealing with Assembly language and C.

Expanding upon #2, then, another objective of ASP.NET MVC is to enable developers to organize the front-end details of the 'view' portion of their solutions and take advantage of the rich foundation that the rest of the industry has built upon the front-end client platform.

You will find that ASP.NET MVC developers feel at home utilizing rich Javascript libraries and client-side templating techniques without fighting with the server-side architecture. This was not originally the case with ASP.NET Web Forms, because Web Forms doesn't want you to look at the HTML or script at all, except if you really have to, in which case, beware, it is not for the faint of heart.

Title: When to favor ASP.NET WebForms over MVC


答:
Lisps are very unique in how they are defined. Lisps are not defined in terms of text but in terms of Lisp data structures. E.g. in Python a function definition is defined like this:

the letter d followed by the letter e followed by the letter f followed by whitespace followed by an identifier denoting the name followed by the character ( followed by …

Whereas in a Lisp a function definition is defined like this:

a list with three elements, the first of which is the string "def", the second of which is a list of strings denoting the names of the parameters, and the third is the code of the function also represented as a list

Likewise, a function call is a list whose first element is a string denoting the name of the function to be called and the other elements are the arguments to the function.

How you write down those lists and strings is irrelevant. You could use the traditional Lisp syntax, you could use JSON, YAML, XML or whatever. The important thing is that code is just a data structure. How that data structure is represented is irrelevant.

Title: Lisp/Clojure: Removing unnecessary parentheses through conventions

Body:
I am fascinated to Lisp as it is simple yet powerful. I am just a beginner and I know there have been lots of discussions on removing parentheses from Lisp and its dialects. Yet I request Lisp ninja's to take few minutes answering this.

Will there be any side effects in Lisp/Clojure if they had followed 2 conventions below:

```<code>;; function declaration
defn function-name param-1 .... param-n
  ...
  function-body ;; not (function-body)
  ...

;; function call
function-name param-1 ... param-n ;; not (function-name param-1 ... param-n)
</code>```

While still using () or [] for inline and nested expressions.

```<code>(println "hello, ") (println "world !!!") ;; inline
= a (- 2 3) ;; nested
</code>```


答:
You could export all confidential business rules to a configuration file which is interpreted by your server-sided framework. That way you could license the framework under GPL, while the business rules can be kept confidential. The business rules likely only apply to your one customer, and anyone else will likely want to replace them with their own business rules, so you are doing them a favor by giving them an obvious place to do so.

But keep in mind that this will make your software a lot more complex than just hardcoding the business rules. One could argue that it will pay off by making maintainance easier, but depending on how complex the business rules are, the opposite might be a case due to the inner plattform effect.

Title: GPL and confidential business rules in a single page application

Body:
I am designing a web app for a client who wants to keep some of his business rules private, we have an NDA. In a nutshell, customers use the app to book a service, and employees use it to keep track of bookings. Since the front end is public (and untrustworthy), all of the decisions that are determined by business rules have to happen on the server.

Now, if I use a very nice GPLv3 licensed module, then that SPA has to be licensed under a compatible license, like MIT, because the app (including the module) is being distributed to everyone who visits the site. That's fine, it isn't possible to hide anything on the front end anyways. I don't contribute enough back to the community, and I would love to release an example of a production grade SPA as open source. It would be a great way to start a blog.

The server would implement a publicly defined API, and the front end would work with any server that implements the API. I would include a simple server with the GPL licensed app so that it can be run by anyone. The server doesn't depend on the client, because could it could be replaced with curl.

What I am wondering is, in this scenario, could I keep my client's unique business rules private in a server app without violating the rules or intentions of the GPL?


问:
Does CTRL+C works in the whole world
I would like to know if CTRL+C (copy) keyboard shortcut works on all Windows versions above '98, all Non-English Windows and on all keyboards (English, German, Chinese...)?</p>

答:
Yes, if nothing else to avoid confusing users. However the original mappings were

```<code> Shift+Delete = Cut
 Ctrl+Insert = Copy
 Shift+Insert = Paste
</code>```

This should still work and are language independent.

Title: Does CTRL+C works in the whole world

Body:
Yes, if nothing else to avoid confusing users. However the original mappings were

 Shift+Delete = Cut
 Ctrl+Insert = Copy
 Shift+Insert = Paste

This should still work and are language independent.


问:
subclass of immutable object not immutable, can this work?
So I'm finishing up refactoring some code to remove a number of previously-mutable objects and add a better generic processing for all the classes in the domain.  Just as I thought I was finishing I eralized that there is one sub-class that has some additional state.

The additional state is a link to other classes that are used as part of the logic for knowing when new domain objects will be created, deleted, or modified.  However, this sub-class is only created at bootup, or when someone runs a command to re-read and update to new configuration files.  I know that this object will always be created before any of the other objects in my domain that are dependent on it are, such that anyone pointing to this object are all gaurenteed to point to the same instance.  I effectively have the Memorization pattern by an accident of how the structure is created.

I could refactor away the mutability; but it would require a bit of work modifying bootup logic that I would prefer to avoid.  Or I could change the has and equals methods to ignore this one set of mutable values so my model will treat this object exactly like it's immutable parent and trust that my knowledge of the method it is constructed prevent me from aliasing issues when I do try to use it's mutable traits.

So how 'wrong' is it to bend my contract for thie class this way be?

答:
It is legitimate, and sometimes useful, to have a subtype of a mutable type which includes additional immutable information not present in the base.  It is also legitimate to have a subtype add mutable members to a type whose base members are immutable, provided that the base type makes no promises about the immutability of any members other than its own.  It is generally illegitimate for subtypes of a type which promises immutability to add any visibly-mutable state, whether or not that state can be observed through a base-type reference.

The problem is that a guarantee of immutability generally implies a guarantee that persisting an object reference is equivalent to persisting the object state, and that references to the object may be freely shared as a means of sharing the current state.  Such guarantees will not really hold if the object has any mutable state, whether or not such state is visible through a base class reference.

What I would suggest as an approach is to have an abstract ReadableFoo type, with MutableFoo and ImmutableFoo subtypes.  It may be helpful to have AsMutable, AsNewMutable, and AsImmutable abstract methods in the base type so that an object which received a ReadableFoo could use it as intended.


问:
Visitor Pattern still useful in languages supporting class extensions?
Is the visitor pattern useful in languages supporting class extensions?

Why bother implementing it, when you have open classes or can subclass. If you want new functionality for a class you could just subclass it, so unless I'm missing something, is it still (very) useful in languages supporting class extensions?

答:
Though as you write it is not technically needed to implement the double-dispatch functionality, it is still used. For example in Pharo Smalltalk (Smalltalk has class extension, they are easy to do, and you can package them easily with *Package method category) 3.0 visitor pattern is used - see AST-Core package.

The reason for this is organizational - a visitor encapsulates "ways how to handle these cases" and for the human apprehending the code it may be valuable to have it at one place, with familiar names.

If there would be user-friendly AST-based pivotable multidimensional (insert-your-own-buzzword) code browsers/editors, there would be no need for Visitor patterns per se in these languages. But we still browse the code in chunks like packages / classes.