答:
The good professor is, fortunately, still with us and the best way to ascertain a definitive answer is to write him and ask his opinion.

That said, I don't think the absolute number matters as much as the function that factorials represent.  Whether or not Knuth realized it at the time, the model he established with that statement works very well for looking backward at what was practical to compute in prior decades and forward through those that followed.

In 1973, our capacity to generate, store, transfer and process data was limited enough to make 10! a reasonable "far edge" figure to shoot for.  I doubt Knuth (or anyone else, for that matter) would have been able to predict the exponential improvements in almost everything we've enjoyed since then, but factorials have fit the actual numbers nicely.

I've seen this firsthand:  A decade ago, I worked on a project where we were developing ways to store and process about 50M records while at the same time pondering how we'd do an order of magnitude more.  A decade later, I'm doing a similar project. My target figures have shifted, all in a factorial fashion:

```<code>                      2002           2012
Small Test .......  9! / 362K ... 10! / 3.6M
Large Test ....... 10! / 3.6M ... 11! /  40M
Capacity Goal .... 11! /  40M ... 12! / 479M
Capacity Dream ... 12! / 479M ... 13! / 6.3B
</code>```

The groups doing both projects bandied about much rounder figures than those, but the factorials aren't very far off.  The Googles and Facebooks of the world have the resources to do the kinds of things my current project only dreams about, but from where I sit, 13! in a decade or less doesn't seem that far out of reach.

I wasn't thinking about large quantities of data in 1992, but hindsight says I'd probably have been looking at everything one factorial less.

Title: Is this statement from Knuth's fundamental algorithms still applicable today?

Body:
In a sense, 10! (ten factorial) represents an approximate dividing
  line between things which are practical to compute and things which
  are not.

This is from Knuth's TAOCP Fundamental Algorithms book (1973).
Is this still a valid statement or has computing power rendered it obsolete ?

Body:
The good professor is, fortunately, still with us and the best way to ascertain a definitive answer is to write him and ask his opinion.

That said, I don't think the absolute number matters as much as the function that factorials represent.  Whether or not Knuth realized it at the time, the model he established with that statement works very well for looking backward at what was practical to compute in prior decades and forward through those that followed.

In 1973, our capacity to generate, store, transfer and process data was limited enough to make 10! a reasonable "far edge" figure to shoot for.  I doubt Knuth (or anyone else, for that matter) would have been able to predict the exponential improvements in almost everything we've enjoyed since then, but factorials have fit the actual numbers nicely.

I've seen this firsthand:  A decade ago, I worked on a project where we were developing ways to store and process about 50M records while at the same time pondering how we'd do an order of magnitude more.  A decade later, I'm doing a similar project. My target figures have shifted, all in a factorial fashion:

                      2002           2012
Small Test .......  9! / 362K ... 10! / 3.6M
Large Test ....... 10! / 3.6M ... 11! /  40M
Capacity Goal .... 11! /  40M ... 12! / 479M
Capacity Dream ... 12! / 479M ... 13! / 6.3B

The groups doing both projects bandied about much rounder figures than those, but the factorials aren't very far off.  The Googles and Facebooks of the world have the resources to do the kinds of things my current project only dreams about, but from where I sit, 13! in a decade or less doesn't seem that far out of reach.

I wasn't thinking about large quantities of data in 1992, but hindsight says I'd probably have been looking at everything one factorial less.


问:
Is looking at random code snippets useful to quickly determine the quality of a project?
To get an idea of the quality of a project that I've never seen before (usually open source projects that I'm considering whether or not to use), I often start by opening random files and eyeballing fine details of the code.

I look for things like:

Style (does it follow accepted conventions for the language and is it consistent)

Quality and consistency of comments

Common language specific gotchas (e.g. consistently not using === in javascript)

Does it look logically structured

I find this gives me a good idea of the skill of the developer/s that wrote the code, even if I know absolutely nothing about what the code is meant to be doing.

Do people think this is useful? What does one need to take into account for quickly assessing the quality of a project's code base, assuming no knowledge of how it actually works?

答: I think looking at small sections of code is a great way - if it is coded well, variables/classes/methods are named well and it is commented well, then understanding what a small section does and what its purpose is should be easy. If you have great difficulty understanding a small block (like anything brace-to-brace), then it is probably not coded all that well.</p>

ContentLicense: CC BY-SA 3.0


问:
Architecture(structure)-oriented vs. feature-oriented project structure
The project, I have involved, has an architecture-oriented project's file/folder structure:

```<code>Root
|____ Node1
    |____ Event Handlers
    |         |___ <all event handlers of project>
    |____ Events
    |         |___ <all events of project>
    |____ Request Handlers
    |         |___ <all request handlers of project>
    |____ Requests
    |         |___ <all requests of project>
    |____ ...
</code>```

It is a clear from the architectural point of view of system (has been proposed by development team).

It is a feature-oriented structure has been proposed by designer team:

```<code>Root
|____ Feature #1
    |____ Event Handlers
    |         |___ <all event handlers of Feature #1>
    |____ Events
    |         |___ <all events of Feature #1>
    |____ Request Handlers
    |         |___ <all request handlers of Feature #1>
    |____ Requests
    |         |___ <all requests of Feature #1>
    |____ ...
</code>```

This variant is closer to designers and it describes clearly a feature to be implemented.

Our teams have started a holy war: what is the best approach. Could somebody help us and explain cons and pros of the first and second ones. Maybe there is a third one that is more useful and beneficial for both of us.

Thank you.

答:
I would vote for the second one. In the first structure, event handlers for FeatureA are completely unrelated to event handlers for FeatureB. It seems that developers will be working on one feature at a time, and if you're working on a FeatureX request, it's far more likely that you'll need to tweak a FeatureX request handler than, say, a FeatureZ request.

By the way, I love how you asked this question from a neutral point of view.

ContentLicense: CC BY-SA 2.5


问:
Should the methods of a class call its own getters and setters?
Where I work I see lots of classes that do things like this:

```<code>public class ClassThatCallsItsOwnGettersAndSetters {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        setField("value");
        //do stuff
        String localField = getField();
        //do stuff with "localField"
    }
}
</code>```

If I wrote this from scratch, I would have written the methodWithLogic() like this instead:

```<code>public class ClassThatUsesItsOwnFields {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        field = "value";
        //do stuff
        //do stuff with "field"
    }
}
</code>```

I feel that when the class calls its own getters and setters, it makes the code harder to read.  To me it almost implies that complex logic is happening in that method call even though in our case it almost never is.  When I'm debugging some unfamiliar code, who's to say that the bug isn't some side effect in that method?  In other words, it makes me take lots of side trips on the journey of understanding the code.

Are there benefits to the first method? Is the first method actually better?

答:
I would say No..

If your getters/setters just get and set (no lazy initialization, no checks, etc) then just use your variables. If in the future you change your getters/setters, you can very well change your methodWithLogic() (because its your class that's changing) and you can call a getter/setter instead of direct assignment. You can document this call for the getter/setter (as it will be strange to call a getter/setter when the rest of your class code is directly using the variable).

The JVM will inline frequent calls to getters/setters. So, its never a performance issue. The gain of using variables is readability and IMHO, I would go for it.

Hope this helps..


问:
Open Source Cloud Computing
Recently I realized that the most popular social platforms on the net are in the hand of just a few companies, Google, Twitter, Facebook, to name just a few. Taking into account the world changing power of these frameworks I am looking for a non-profit, democratic alternatives to these sites. (Mozilla is a non-profit project, however it could not thrive without the backing of Google.)

In my imagination, the ideal approach (see explanation below) would be a distributed approach as used in file sharing programs or tools like seti@home. Every user willing to take part in the project would have to install software on his or her computer to act as a node in the network that would make up a social space similar to Google+, Facebook or Twitter but with a non-commercial approach. This approach could also be used for a "democratic" cloud to store data.

Is anyone aware of projects that go in this direction?

I call it "ideal approach" for a couple of reasons. No need for big server farms or hardware maintaining costs. Invulnerability against most hack attack because it's distributed and there is no central node. Just some I could think of right now.

答:
There are several such projects. The most publicized system (but certainly not the first) is Diaspora, which is a social network made of many individually-operated servers, called "pods". Pods can be freely set up using the AGPL-licensed source code. An individual user can set up a personal pod, or can join a public pod. Regardless of what pod your account is set up on, you can interact with users from other pods (it's a bit like email: if you use Gmail and I use Yahoo mail and another person runs their own mail server, there's no reason why we can't all communicate).

I don't know what "non-commercial" has to do with anything, though -- plenty of pods display ads to their users and some could even charge for access (e.g., in exchange for promises of very good uptime). Of course, users are free to move to a pod that doesn't display ads or charge money, if they wish.

Title: Open Source Cloud Computing


问:
What phases of a traditional waterfall project should Scrum replace?
My team and I are using Scrum to manage software development projects. In my company there has been a move towards more structure in all IT projects using a waterfall methodology. This is fine by me as there are lots of non-software-development projects which will benefit greatly from this and it is not  threatening our use of Scrum.

However, we need to work out how our Scrum processes (which do a great job of taking a Product Owner's requirements and turn them into working software) fit into the broader project process.

Our new waterfall project process includes explicit activities for the following things (not necessarily sequentially and not necessarily in this order):

Production and approval of business case.

Resourcing.

Requirements analysis.

Design.

Build.

Test.

Training.

Communications.

Go live.

Risk & Issue Management.

Benefits realisation.

Bear in mind that a project may be required to deliver more than just software. It may also include server infrastructure to host the software and network / desktop infrastructure to make it available to users.

I think Scrum will manage 3, 4, 5 & 6 happily but probably only for teams who find it adds value, which is probably only software development...

We could get other teams to use it for the production of infrastructure deliverables, but they don't see the need or benefit and nor do I (Scrum is good for large, risky projects and they are building a bunch of standard PCs).

Likewise we could have a User Story in the Product Backlog for the Project Manager (not typically a member of the Scrum Team) to produce a benefits realisation plan.

Are we approaching this correctly?
Is there a better way to integrate these two styles of working or are they exclusive and we should use one or the other?

答:
Scrum is a complete project management methodology that addresses all aspects of the project lifecycle. Unlike projects managed using a sequential process where things generally happen once and then are revisited if necessary as the project progresses, Scrum embraces a more iterative approach - everything is addressed during each iteration.

Of the list of things you identified, the only one that may happen up-front, at the start of the project is the creation of the business case. Some kind of purpose, vision, and scope is likely to be established once, and then only revisited as necessary. Everything else happens in every iteration, with the Scrum Master typically being responsible for ensuring the project has sufficient resources, facilitating communication between internal entities, and managing project risks. The requirements are provided and prioritized through the Product Owner, and the team is responsible for estimating the amount of work required to realize each requirement and then continually refine the design, implementation, test, and documentation work products throughout the project. Every iteration, in theory, results in a product that is ready to be deployed to a customer (a "potentially shippable product").

The process by itself doesn't typically address exactly how training and "go live" or deployment activities happen. Obviously, if your development team is responsible for supporting any of these activities, you'll want to build time for them into each iteration and keep those in mind when you're doing your sprint planning activities. If they are handled by a different team, there's nothing that says they must use Scrum. They should, however, expect a working product that contains new features and/or bug fixes on a regular basis (at the end of every timeboxed iteration), but if they do anything with that working product is up to them.

It might not be appropriate for every project to use the same lifecycle, especially if it doesn't add value or if it would be too difficult or time consuming to transition from their current processes to something new and different. As an example, your team that produces and maintains the infrastructure might not be able to produce all of the hardware within a single software development iteration. You need to plan your new deployments based on the activities - you can't deploy hardware that's not done, nor can you ship incomplete software.

If software development will benefit from using an iterative and incremental methodology, there's nothing wrong with them using it even if everyone else is still using a sequential methodology. As long, of course, as it doesn't negatively impact business - are you still releasing high quality software that adds value to the customer on time, on budget? Are your processes clashing in such a way that leads to people being idle? Consider those, and minimize downtime while maximizing value delivered to your customers.


问:
shadow simulation from buildings
Is it possible to calculate shadow areas of buildings or simulate shadows of buildings in a city, using the heights of these buildings and the sun angle and azimuth?

The basic light tracing concept using trigonometry is known. However, how would one come up with simulated shadow of group of buildings in one place?

答:
Are you actually ray-tracing?  If so, you backtrace from the point being rendered to the light source.  If it intersects one of the buildings, its in a shadow.

If you are using OpenGL/DirectX for real-time graphics, there are other solutions - look around online as thats a fairly big topic.

OwnerDisplayName: Yudine

Title: shadow simulation from buildings


问:
Selling a Joomla extension with third party jquery plugin
Let's suppose I want to create an extension for Joomla that uses a jQuery plugin or any third party library. Imagine that I create a Joomla module that uses jquery Nivo Slider plugin (MIT License) http://nivo.dev7studios.com/license/. I'm not sure If I could sell this module with this license.

Could I sell it if the plugin has a GPL License?

答:
With GPL, You can sell anything, as long as the whole product is under GPL as well. GPL doesn't prevent you from asking money for stuff, it prevents you from preventing users the four freedoms that the GPL is trying to grant. The GPL license doesn't ask you to give stuff away for free, it asks you to also provide the source along with the code and let your users use the product as they please (as long as that usage still complies with the GPL).

With MIT, you can do almost anything with the library, including bundling the code in a proprietary, closed source application/extension/library.

OwnerDisplayName: alejandrodf

OwnerDisplayName: Sergiu Dumitriu


答: One thing that hasn't been mentioned is that getter and setters (as all methods) are virtual in Java. This adds another feature to always using them in your code. Another user could extend your class, overwriting your getters and setters. Your base class would then be using the subclass's data instead of its own. In a language where you explicitly mark virtual functions, this is much more handy since you can predict and declare which functions this can be done with. In Java, this is something you would always have to be aware of. If it is desired behavior then using them in your code is a good thing, otherwise not so much.</p>

Title: Should the methods of a class call its own getters and setters?

Body:
Where I work I see lots of classes that do things like this:

```<code>public class ClassThatCallsItsOwnGettersAndSetters {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        setField("value");
        //do stuff
        String localField = getField();
        //do stuff with "localField"
    }
}
</code>```

If I wrote this from scratch, I would have written the methodWithLogic() like this instead:

```<code>public class ClassThatUsesItsOwnFields {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        field = "value";
        //do stuff
        //do stuff with "field"
    }
}
</code>```

I feel that when the class calls its own getters and setters, it makes the code harder to read.  To me it almost implies that complex logic is happening in that method call even though in our case it almost never is.  When I'm debugging some unfamiliar code, who's to say that the bug isn't some side effect in that method?  In other words, it makes me take lots of side trips on the journey of understanding the code.

Are there benefits to the first method? Is the first method actually better?


问:
Is this XOR value swap algorithm still in use or useful
When I first started working a mainframe assembler programmer showed me how they swap to values without using the traditional algorithm of:

```<code>a = 0xBABE
b = 0xFADE

temp = a
a = b
b = temp
</code>```

What they used to swap two values - from a bit to a large buffer - was:

```<code>a = 0xBABE
b = 0xFADE

a = a XOR b
b = b XOR a
a = a XOR b
</code>```

now

```<code>b == 0xBABE
a == 0xFADE
</code>```

which swapped the contents of 2 objects without the need for a third temp holding space.

My question is: Is this XOR swap algorithm still in use and where is it still applicable.

答:
When using xorswap there's a danger of supplying same variable as both arguments to the function which zeroes out the said variable due to it being xor'd with itself which turns all the bits to zero. Of course this itself would result in unwanted behavior regardless of algorithm used, but the behavior might be surprising and not obvious at first glance.

Traditionally xorswap has been used for low-level implementations for swapping data between registers. In practice there are better alternatives for swapping variables in registers. For example Intel's x86 has a XCHG instruction which swaps the contents of two registers. Many times a compiler will figure out the semantics of a such function (it swaps contents of the values passed to it) and can make its own optimizations if needed, so trying to optimize something as trivial as a swap function does not really buy you anything in practice. It's best to use the obvious method unless there's a proven reason why it would be inferior to say xorswap within the problem domain.


答:
The key to the answer is in the question - "working a mainframe assembler programmer" - in the days before the compiler.  When humans hunkered down with assembly instructions and hand crafted exact solutions for a particular piece of hardware (that may or may not work on another model of the same computer - issues such as the timing of hard drives and drum memory had impact on how code was written - read The Story of Mel if one feels the need to be nostalgic).

Back in these bygone days, registers and memory were both scarce and any trick to not have to beg for another byte or word of memory from the lead architect was time saved - both in writing the code and execution time.

Those days are gone.  The trick of swapping two things without using a third is a trick.  Memory and registers are both plentiful in modern computing and humans don't write assembly anymore.  We've taught all of our tricks to our compilers, and they do a better job of it than we do.  Chances are the compiler did something even better than what we would have done.   In most cases, sometimes we need to write assembly in some inner bit of a tight loop for some reason... but it isn't to save a register or a word of memory.

It might be useful again if one is working in a particularly limited microcontroller, but optimizing a swap isn't likely the source of one's problem then - trying to be too clever is more likely a problem.

Title: Is this XOR value swap algorithm still in use or useful

Body:
When I first started working a mainframe assembler programmer showed me how they swap to values without using the traditional algorithm of:

```<code>a = 0xBABE
b = 0xFADE

temp = a
a = b
b = temp
</code>```

What they used to swap two values - from a bit to a large buffer - was:

```<code>a = 0xBABE
b = 0xFADE

a = a XOR b
b = b XOR a
a = a XOR b
</code>```

now

```<code>b == 0xBABE
a == 0xFADE
</code>```

which swapped the contents of 2 objects without the need for a third temp holding space.

My question is: Is this XOR swap algorithm still in use and where is it still applicable.


答:
Will it work?  Yes.

Should you use it?  No.

This sort of micro-optimization would make sense if:

you have looked at the code the compiler generates for the straightforward way of doing this (assignment and a temporary) and decided that the XOR approach generates faster code

you have profiled your app, and found the cost of the straightforward approach outweighs the clarity of the code (and resulting savings in maintainability)

To the first point, unless you've done this measurement, you should be trusting the compiler.  When the semantics of what you're trying to do are clear, there are a lot of tricks the compiler can do, including rearranging variable access so that the swap is not needed at all, or in-lining whatever machine level instructions provide the fastest swap for a given data type.  "Tricks" such as the XOR swap make it harder for the compiler to see what you are trying to do, and thus make it less able to apply such optimizations.

To the second point, what are you gaining for the added complexity?  Even if you've measured and found the XOR approach faster, is this having enough impact to justify a less clear approach?  How do you know?

Finally, you should look into whether there is a standard swap function for your platform/language -- the C++ STL, for instance, provides a template swap function which will tend to be highly optimized for your compiler/platform.


答:
Why do the feature-inventors care about the implementation details?  If that is the separation between the sides of the argument, then I think the answer is clear.  People inventing ideas/features do not determine the file structure that is needed by the implementers.

This is a particularly important issue when a feature's implementation spans multiple dlls, exes, databases, or other software pieces.

Title: Architecture(structure)-oriented vs. feature-oriented project structure

Body:
The project, I have involved, has an architecture-oriented project's file/folder structure:

```<code>Root
|____ Node1
    |____ Event Handlers
    |         |___ <all event handlers of project>
    |____ Events
    |         |___ <all events of project>
    |____ Request Handlers
    |         |___ <all request handlers of project>
    |____ Requests
    |         |___ <all requests of project>
    |____ ...
</code>```

It is a clear from the architectural point of view of system (has been proposed by development team).

It is a feature-oriented structure has been proposed by designer team:

```<code>Root
|____ Feature #1
    |____ Event Handlers
    |         |___ <all event handlers of Feature #1>
    |____ Events
    |         |___ <all events of Feature #1>
    |____ Request Handlers
    |         |___ <all request handlers of Feature #1>
    |____ Requests
    |         |___ <all requests of Feature #1>
    |____ ...
</code>```

This variant is closer to designers and it describes clearly a feature to be implemented.

Our teams have started a holy war: what is the best approach. Could somebody help us and explain cons and pros of the first and second ones. Maybe there is a third one that is more useful and beneficial for both of us.

Thank you.


问:
Which k-best shortest-path algorithms should I consider?
I'm solving a graph-search optimization problem. I need to find the k best acyclic shortest-paths through a directed weighted graph.

I know there are a number of exact and approximate k-best algorithms, but most of the recent research seems to be oriented toward very large, very sparsely-connected graphs (e.g. road routing and directions), and my graph is neither.

Distinguishing aspects of my problem:

The graph consists of approximately 160 vertices.

The graph is nearly fully connected (bidirectionally, so ~160^2 ~= 25k edges)

k will be quite small (probably less than 10)

The maximum path length will probably be bounded and very small as well (e.g. 3-5 edges)

I said 'acyclic' above, but just to reiterate - solutions must not include cycles. This isn't an issue for 1-best shortest path, but it becomes a problem for k-best - for example, consider a road routing - the 2nd shortest path from A to B might be the same as the 1-best, with a quick trip around a block somewhere. That's might be mathematically optimal, but not a very useful solution. ;-)

We may need to re-weight edges on-the-fly for each calculation. An edge cost consists of a weighted sum of several factors, and the final requirements (whenever we get them) may allow a user to specify their own prioritization of those weighting factors, altering edge weights. This is a relatively small graph (we should be able to represent it in a few hundred KB), so it's probably reasonable to clone the graph in memory, apply the re-weighting, and then execute the search on the cloned graph. But if there's a more effective method of performing the search while computing weights on-the-fly, I'm interested.

I'm looking at the algorithms described in Santos (K shortest path algorithms), Eppstein 1997 (Finding the k Shortest Paths), and others. Yen's algorithm is of interest, primarily because of the existing Java implementation. I'm not scared to read the research papers, but I thought it was worth throwing out the details of my problem and asking for pointers to save some reading time.

And if you have pointers to Java implementations, even better.

答:
I would say this question can be easily googled and is also a duplicate:

https://stackoverflow.com/questions/12773525/k-shortest-alternative-path-algorithm-java-implementations

https://stackoverflow.com/questions/7208720/finding-kth-shortest-paths

That being said, I already used and implemented Eppstein and recommend it. I found it quite elegant. If I remember right, it may be optimal as well, and the following paper explains it very nicely:

http://pdf.aminer.org/001/059/121/finding_the_k_shortest_paths.pdf

OwnerDisplayName: AaronD


问:
Difference between daemon and child thread?
As per my knowledge daemon thread is a thread that runs in background(low priority thread) and also a child thread runs in the background when the parent thread runs foreground so where does the difference lie between a child and a daemon thread?

It's in case of java and can you explain referring to other languages too.

答:
Daemons (or Demons) and parent | child threading concepts are orthogonal to each other.  In other words, the basis of your question is wrong.  Likewise, priorities can be assigned to processes and threads, but priority is orthogonal to the definition of a demon, parent thread, or child thread status.

An application is a program that has been written and becomes a process when it is executed.  An application is made up of a process and zero, one, or more threads.  The Wikipedia entry on Threads does a good job of explaining the difference between a process and a thread.

processes are typically independent, while threads exist as subsets of a process

processes carry considerably more state information than threads, whereas multiple threads within a process share process state as well as memory and other resources

processes have separate address spaces, whereas threads share their address space

processes interact only through system-provided inter-process communication mechanisms

context switching between threads in the same process is typically faster than context switching between processes.

A couple of notes -

threads may or may not share the same address space, it is OS dependent.

take the comment about context switching with a grain of salt - this will be OS and chipset dependent.

"Process" and "thread" are sometimes used interchangeably in conversations.  It's common to call the process the "parent thread" even though this isn't technically correct since it's a process.  Any thread spawning additional threads would be considered parent threads as well.

A daemon is a background process or application, generally without any interactive elements but that's not a hard requirement.  A demon can have any priority assigned to it, not just low priority.  In addition to the process, a daemon may have some child threads associated with it.

All of these terms are independent of the programming language used to write the application.  Some languages provide better support for threads than other languages do.


问:
How to handle the input file provided in programming contests?
In programming contests like Google CodeJam, Facebook Hacker Cup, each question is provided with an input file for testing one's code for that program. I get struck at this point only.

I don't understand whether that input file should be read by my program or it is just for testing the correctness of my program for various test cases given in that input file and I can copy past each test case given in the input file one by one manually and see whether the output provided by my program is right or wrong.

It would be very helpful for me if anyone who has been actively participating in such competitive contests can share their views.

答: You need to write code to read that file.  When you submit your program, it will be tested against other unpublished data files in the same format.</p>


问:
Creating huge decision tree
I'm to write an event correlator. A fundamental part of the system will be a decision tree that recognizes the origin of the fault basing on recorded states and log files.

Often many accidents will differ with minor details and many decisions taken will be made basing on fuzzy, incomplete or unreliable data, but most of these decisions can be written down as binary logic functions.

Thing is, there will be a lot of them. I expect at least 100 nodes in the decision tree, and I may underestimate the value by an order of magnitude. And on top of that,  as new, unexpected patterns emerge, unforseen failures happen leaving new traces, or with extension of the system new failure modes become viable, the decision tree will have to be maintained.

(and it won't always be a pure tree structure - some faults of the same effect have two or more modes of appearance, some of these branching off into different modes, e.g. event A means failure X, event B means: check event C. If C is true, it's also failure X, but if not, it's failure Y. Although I can always normalize it into X1 and X2, which are technically identical but different from the tree point of view.) Also, the tree will be often fairly deeply nested so I'm afraid a simple series of nested if() will quickly slip out of control.

Now my question is, how to store / write / build that tree so that it could be compilable into something the machine can digest, but still maintainable for the developers?

Note this is for an embedded system, so heavyweight solutions like JBoss don't really fit unless they appear only on the compiler side, and the final system runs a compiled ruleset in something much more machine friendly.

(the system is written in C++, it also makes extensive use of JSON, and will run on an ARM9 CPU if that's of any help.)

答:
Here is an idea for such a DSL. Say you have 6 input variables (your "events"). Lets assume those variables are binary (the idea can be generalized to non-binary variables). Now your DSL should contain statements like

```<code>(0|*|1|0|1|1) => Action_A()
(0|0|1|0|0|*) => Action_B()
(1|1|1|0|*|*) => Action_C()
default       => ActionDefault()
</code>```

Each row contains a precondition (the part left to the =>), saying which input variable must have which value. The part right to the => is the action to be applied. A "*" means that the corresponding input variable can be either 0 or 1. The semantics can be compared to the pattern matching mechanics of awk, perl, or xslt.

How does this help you? Well, now you can do two things

write a simple validator which checks that all your preconditions are mutally exclusive. If you don't want or need a "default" action, you can let this out and instead let your validator additionally check that you did not miss a case.

write a code generator which translates that DSL into C++ code, which may then look similar to this:

```<code>if(event_1==0 && event_3==1 && event_4==0 && event_5==1 && event_6==1)
    Action_A();
</code>```

The validator will help you to keep things maintainable, and the generated C++ code should compile into something "machine friendly", as you required.

If your input variables are not binary (100 nodes by a depth of 2-3 decisions is not possible just by binary inputs), you will have to extend that DSL, it should be straightforward how to accomplish that. For example, use (0,1,4|*|*) for a precondition (event_1==0 || event_1==1||event_1==4).

EDIT: if you have many input variables and the requirement to check only a few of them, this could be adapted by using "named parameters", for example

```<code>    (var_1==[0,1,4]|var_3==0|var_25==[1-10]) => Action_A()
</code>```

Of course, you could also code this directly in C++, which won't become much longer, but the advantage of using a small, formal DSL is that now you have a chance to write a validator for this.

Title: Creating huge decision tree

Body:
Here is an idea for such a DSL. Say you have 6 input variables (your "events"). Lets assume those variables are binary (the idea can be generalized to non-binary variables). Now your DSL should contain statements like

(0|*|1|0|1|1) => Action_A()
(0|0|1|0|0|*) => Action_B()
(1|1|1|0|*|*) => Action_C()
default       => ActionDefault()

Each row contains a precondition (the part left to the =>), saying which input variable must have which value. The part right to the => is the action to be applied. A "*" means that the corresponding input variable can be either 0 or 1. The semantics can be compared to the pattern matching mechanics of awk, perl, or xslt.

How does this help you? Well, now you can do two things

write a simple validator which checks that all your preconditions are mutally exclusive. If you don't want or need a "default" action, you can let this out and instead let your validator additionally check that you did not miss a case.

write a code generator which translates that DSL into C++ code, which may then look similar to this:

if(event_1==0 && event_3==1 && event_4==0 && event_5==1 && event_6==1)
    Action_A();

The validator will help you to keep things maintainable, and the generated C++ code should compile into something "machine friendly", as you required.

If your input variables are not binary (100 nodes by a depth of 2-3 decisions is not possible just by binary inputs), you will have to extend that DSL, it should be straightforward how to accomplish that. For example, use (0,1,4|*|*) for a precondition (event_1==0 || event_1==1||event_1==4).

EDIT: if you have many input variables and the requirement to check only a few of them, this could be adapted by using "named parameters", for example

    (var_1==[0,1,4]|var_3==0|var_25==[1-10]) => Action_A()

Of course, you could also code this directly in C++, which won't become much longer, but the advantage of using a small, formal DSL is that now you have a chance to write a validator for this.


答:
I have always been more comfortable with the second approach, but I always have a "feature" called general or common for the truly shared/base classes.

Approach two keeps truly separate things separate, but without the "common" area it sometimes separates things into areas that they don't fit well.


问:
Why do we use story points instead of man days when estimating user stories?
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?

答:
I think one of the main advantages is that humans and developers specifically are actually pretty bad at estimating time.  Think of the nature of development too -- it's not some linear progression from start to finish.  It's often "write 90% of the code in 10 minutes and then tear your hair out debugging for 17 hours."  That's pretty hard to estimate in the clock timing sense.

But using an abstraction takes the focus off of the actual time in hours or days and instead puts the focus on describing the relative expense and complexity of a task as compared to other tasks.  Humans/developers are better at that.  And then, once you get humming with those point estimates and some actual progress, you can start to look at time more empirically.

I suspect that there is also an observer effect that happens with time estimates that wouldn't happen with point estimates.  For instance, the incentive to sandbag an estimate and deliver way "ahead of schedule" is going to be muted with indirection in a point based system.


答:
If you're using Fibonacci numbers (or something similar), it limits the number of options when estimating a story.  I worked with a group that used low numbers only: 1, 2, 3, 5, 8, and 13.  We had a reference story that was a 5.  This enabled us to easily make snap decisions on a story's complexity while doing Planning Poker.  The other side effect was that anything rated a 13 probably had insufficient information and needed to be broken down further.  I seriously doubt it would have been that easy and straightforward if we were using raw hours.

Your Product Owner speaks your stakeholders' language and should be able to translate between story points and man-hours (or other units) as needed.  During my time as a PO, I had some hard data that 1 story point = 4 man-hours, but obviously every team is different.

Edit:

With the knowledge that 1 point = 4 hours, you could theoretically change your Planning Poker deck to 4, 8, 12, 20, 32, and 52.  But those numbers feel harder to deal with.  I think I would mentally abstract the values back to something simple, e.g., "less than a day", "more than a week", etc.  And if I'm going to do that, I might as well stick with the abstract unit-less story points.

Title: Why do we use story points instead of man days when estimating user stories?

Body:
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?


答:
Man days or man hours are as you say concrete.  So when a task is estimated at 5 hours and takes 6 it is now a late task.

When you have a story that is a 3 points and it takes 6 hours, it took 6 hours, it's not late, it just took six hours.  The velocity measurement than is more a factor of how many of those points you get done in a sprint, and that number can fluctuate, because it isn't concrete.  You also are not measuring each task, but the total of all the tasks.  When you have hours on each task, the temptation is there to measure each task.  When that happens, you get no benefit to the sprint for finishing under the time and it is a consequence for finishing over the time of any given task.

It can be a transition to thinking in terms of points.  One place I worked before we even introduced agile used t-shirt sizes just to get an idea on the level of effort.  Points are just an extension of that.

That isn't to say there isn't controversy, or some arbitrary assignment to the points. We have members of our team that almost always vote the lowest number, and complain when they think a task is a 1 and we think it is a 3 that we are suffering from point inflation.


答:
The abstraction is sort of the point. Using the 'man day' as a measurement has a number of pitfalls, including:

If the team isn't familiar with the tech they are going to be using, then it can be really hard to give real-time estimates of how long a task might take. They are much more likely to be able to give good relative estimates - e.g. "task A will probably take twice as long as task B".

Different people work at different rates! If you use 'man days' you pretty much have to change the time estimate when a task is passed from one developer to another. Who defines how much work constitutes a 'man day' anyway?

If you want to estimate man-days it's a simple calculation:

```<code>user points in story / average user points per developer per day = estimated man days
</code>```

Body:
The abstraction is sort of the point. Using the 'man day' as a measurement has a number of pitfalls, including:

If the team isn't familiar with the tech they are going to be using, then it can be really hard to give real-time estimates of how long a task might take. They are much more likely to be able to give good relative estimates - e.g. "task A will probably take twice as long as task B".

Different people work at different rates! If you use 'man days' you pretty much have to change the time estimate when a task is passed from one developer to another. Who defines how much work constitutes a 'man day' anyway?

If you want to estimate man-days it's a simple calculation:

user points in story / average user points per developer per day = estimated man days


答:
Have to agree with the second approach, given the two options.  The first one just looks like an amorphous blob.  At least the second one has some shape.

It really depends on how big the project is.  If the "features" are large, they each need their own distinct bucket.


问:
Should database-models (conceptual or physical) be reviewed by DBAs?
Where I work, new applications that are being developed that will use their own relational database, must have their database-models (conceptual, then physical ) reviewed and aproved by DBAs.

Things looked after are normalization, antipatterns, table and column naming standards, etc.

Is this really a DBA's responsability to do this ?

or should it be, in a greater extend, the responsability of app designers and architects ?

答: Depends on how database-savvy your developers are, but normally yes.  DBAs are usually better at spotting potential performance issues, plus it gives them a heads-up in case they need to do anything special or unusual when creating the database (allocating space on multiple drives, setting up failover plans, allocating unusually large buffers or temp segments, etc).  Plus, as you point out, they need to enforce any naming standards and data domains.  They also will point out if some data you are using is already being stored in another database, to reduce data duplication.</p>


答:
Yes, that practice seems pretty standard to me.

If you have DBAs (whose expertise should include database  modeling, normalization, table-naming structure, etc.) I would expect you would want to use them...

Why would you have DBAs and not want their their expertise and input?  It seems like it is the obvious choice.

Title: Should database-models (conceptual or physical) be reviewed by DBAs?

Body:
Where I work, new applications that are being developed that will use their own relational database, must have their database-models (conceptual, then physical ) reviewed and aproved by DBAs.

Things looked after are normalization, antipatterns, table and column naming standards, etc.

Is this really a DBA's responsability to do this ?

or should it be, in a greater extend, the responsability of app designers and architects ?


问:
Compress range of numbers into blocks of used or unused
Given a numerical range and a list of used numbers that fall within that range I need to compress the range into blocks of used and unused numbers.

For example:

```<code>range: 0 to 10
used:  3,4,5,9
</code>```

I need an output like

```<code>0-2: free
3-5: used
6-8: free
9:   used
10:  free
</code>```

Not sure where to start with this, so any guidance appreciated.

答:
As I commented, this is very similar to run length encoding, in fact if used is sorted it is arguably a bit easier!

With run length encoding you would start with the first number in an array and scan forward counting the number between each transition between used/unused (or in your case recording the start and end index which is essentially equivalent).

However if used is sorted you already know where the first transition from unused->used is so you can start there and scan used for the next transition from used->unused, you then also know the next unused->used transition as its the next used number.

if used isn't sorted you could either sort it first (likely a good idea if used is small compared to range) or you could use range and used to first construct a full array of used and unused numbers e.g. 00011100010 and run length encode this.


问:
How does one handle sensitive data when using Github and Heroku?
I am not yet accustomed with the way Git works (And wonder if someone besides Linus is ;)).

If you use Heroku to host you application, you need to have your code checked in a Git repo. If you work on an open-source project, you are more likely going to share this repo on Github or other Git hosts.

Some things should not be checked in the public repo; database passwords, API keys, certificates, etc...
But these things still need to be part of the Git repo since you use it to push your code to Heroku.

How to work with this use case?

Note: I know that Heroku or PHPFog can use server variables to circumvent this problem. My question is more about how to "hide" parts of the code.

答:
The preferred method of keeping passwords/api keys secret on heroku is to set config values via the heroku commandline application. The following example taken from a heroku dev center article

(The below example, and my entire answer relate to rails apps)

```<code>$ cd myapp
$ heroku config:add S3_KEY=8N029N81 S3_SECRET=9s83109d3+583493190
Adding config vars and restarting myapp... done, v14
S3_KEY:     8N029N81
S3_SECRET:  9s83109d3+583493190
</code>```

Then reference these config values in your code using the ENV[] variable

```<code>AWS::S3::Base.establish_connection!(
  :access_key_id     => ENV['S3_KEY'],
  :secret_access_key => ENV['S3_SECRET']
)
</code>```

This way your sensitive passwords are not stored in the git repository.  (Note: When running the app locally, set these values in your .bashrc file

Also, I'm not sure what type of application you are running, but in Rails, heroku does not use your database.yml file, it simply sets your database username/password according to your app settings. So you can avoid saving those credentials in git

Also, also, if you are running your own application and want it to remain private, a great alternative to github is bitbucket which offer free private repositories.

Body:
The preferred method of keeping passwords/api keys secret on heroku is to set config values via the heroku commandline application. The following example taken from a heroku dev center article

(The below example, and my entire answer relate to rails apps)

$ cd myapp
$ heroku config:add S3_KEY=8N029N81 S3_SECRET=9s83109d3+583493190
Adding config vars and restarting myapp... done, v14
S3_KEY:     8N029N81
S3_SECRET:  9s83109d3+583493190

Then reference these config values in your code using the ENV[] variable

AWS::S3::Base.establish_connection!(
  :access_key_id     => ENV['S3_KEY'],
  :secret_access_key => ENV['S3_SECRET']
)

This way your sensitive passwords are not stored in the git repository.  (Note: When running the app locally, set these values in your .bashrc file

Also, I'm not sure what type of application you are running, but in Rails, heroku does not use your database.yml file, it simply sets your database username/password according to your app settings. So you can avoid saving those credentials in git

Also, also, if you are running your own application and want it to remain private, a great alternative to github is bitbucket which offer free private repositories.


问:
Is it necessary to add the default case while using switch cases?
During a recent code review I was asked to put default cases in all the files wherever switch block is used, even if there is nothing to do in default. That means I have to put the default case and write nothing in it.

Is this the right thing to do?
What purpose would it serve?

答:
You should always have a default unless you have provably and permanantly covered all cases.  It costs nothing, and it's insurance against failure to maintain your switch statement in an evolving program.

If you're really sure you don't care about any other cases, the default: break;//don't care
but the default default should be something like default: throw new Error("unexpected value");

Likewise, you should never "drop through" a nontrivial case construct without adding a comment to the effect that you intend to drop through.  Java got this one wrong at the design stage.


问:
Is it possible to use python as a shell replacement?
Recently I was looking at python's shutil and subprocess etc... And I started wondering: wouldn't it be ok to use python instead of e.g. bash?

What am I missing?

答:
Convenience of syntax, mostly.

In python, running a process requires subprocess.call(...); renaming a file shutil.move(), etc. Bash syntax is much more direct for those tasks.

Yes, Python is a great language, but the explicit syntax to execute (for bash) simple tasks is going to get in the way of doing day-to-day work real fast.


问:
What is dependency Analysis and how is it done?
I saw this in a job posting for an ASP.net developer.

"An understanding of basic software development practices such as ...and Dependency Analysis."

I read the wikipedia entry for Dependency Analysis and understand that it basically means one thing depends on the other so you can't reorder or parallelize them.

What does this mean in practice?  Is there a tool that is used to do a Dependency Analysis?  What should I know about it for an interview and in practice if I get the job?

答:
When you say Dependency Analysis, the first tool that comes to mind is NDepend.

Here's a great blog post by Scott Hanselman explaining how you can use it to analyze dependencies in your code.

You can use NDepend to create dependency graphs of your assemblies, use CQL (Code Query Language) to query for overly complicated classes and methods, and perform a number of other code analysis tasks.


问:
How to do scalar multiplication and matrix inverse when variables are of size 1000 bits?
I am doing arithmetic operations on really huge numbers.

For example, I am given six variables, a_{11}, a_{12}, a_{21}, a_{22}, x_1, and x_2.

Although the above are math terms, these six variables are each 1000-bit integers.

What I want to do is to calculate (1) two numbers z_1 and z_2, and (2) the matrix inverse.

(1) z_1 = a_{11}*x_1 + a_{12}*x2 and z_2 = a_{21}*x_1 + a_{22}*x2

(2) if A is a matrix defined as A=[a_{11} a_{12}; a_{21} a_{22}], want to compute A^{-1}

I know how to do the above when these six variables are ordinary floating points.

But my question is how to compute them in C or Python when the six variables are all of size 1000-bit?

Body:
Python's long type (docs here) is arbitrary precision. So in the interest of saving a precious resource (i.e. your time) I would try that first and see if it is Good Enough™. Also take a look at NumPy if you are dealing with big chunks of big data.

Update:

Yes, you can just assign a big, honking number. E.g.

x = 1071508607186267320948425049060001810561404811705533607443750388370351051124936122493198378815695858127594672917553146825187145285692314043598457757469857480393456777482423098542107460506237114187795418215304647498358194126739876755916554394607706291457119647768654216766042983165262438683720566806937638839928883123

or in binary

y = 0b1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010

print x
print y
print x+y


问:
Possible to implement OOP without using extensive heap operations?
Is the concept of OOP intimately tied to allocating objects on the heap? Is it possible to write normal OOP without creating excessive objects on the heap?</p>

答: No, OOP has nothing to do with where objects reside in memory. For example, instances of the same class can be allocated statically, on the heap, or on the stack in C++. In other languages, like Python, memory management is almost transparent, so the question of location doesn't really apply.</p>

OwnerDisplayName: martineau


问:
Pattern for mobile app data synchronisation using HTTP over 3G networks
I have a mobile app built using jquerymobile, PhoneGap and some custom CSS and JavaScript.  The data objects are received in JSON and used to display different forms to the user. For example

```<code>{ id: 1, type: personal_details, question_1: "First name", question_2: "Last name" },
{ id: 2, type: work_details, question_1: "Occupation", question_2: "Experience" }
</code>```

The user fills out these forms and sends the data back to a .NET application. Things work great when there is a good 3G connection but that is not always the case.

As each form is sent there is a danger that not all the forms will make it back together. In our example the personal details could be sent first, the connection is lost and the work details are left on the mobile device or lost on the network either of which frustrates my users.

What is the best strategy to handle and recover elegantly from network failures? Relying on the HTTP response codes doesn't seem to be working. E.g.

```<code>for ( form in forms ) {
    $.ajax({
        url: 'http://ac.me',
        data: form,
        success: function (){
            // delete from localStorage
        },
        error: function (){
            // show error message 'try again later'
        }
    });
}
</code>```

The request can fail and the error function is never called. The alternative I see is sending all the forms in one JSON string but I am concerned about the performance implications of SQL server processing many short requests or fewer longer requests.

答:
You're actually probably better off sending them all at once.

HTTP Requests are Expensive You need to remember that the act of making HTTP requests are, generally speaking, expensive. It's why you're supposed to merge your JavaScript into one file and make sprites for web sites.

Why are they expensive? And why does that matter even on a mobile application (even if, for the sake of argument, you're doing it natively)? Because it's the act of making the connection itself that makes it expensive. To open an HTTP connection, the client and the server go through a number of steps:

DNS lookup. Is the server actually there? Can the client connect to it?

SYN It is? Great! Start the handshake transaction (this is known as a "SYN" packet).

SYN-ACK The server responds with the next step of the handshake transaction, known as a "SYN-ACK" packet.

ACK The client responds again, with the third, and final step of the handshake. If all three steps are successful, then the connection is established. Now, we can actually get to our request.

Send the request. This is where your data is actually getting sent.

Wait for response. The server has to do something with request, which takes time, especially if a database or heavy calculations are involved.

Receive Response The server sends back the response. This takes time based on the response size and connection integrity, just like the send request step.

Load The client now has to do something with the information it got back from the server. Usually, it's rendering it to an output device, or triggering another event.

FIN The client sends a "FIN" packet that closes the HTTP connection

(Check out this breakdown on the anatomy of an HTTP connection for more information.)

HTTP Requests Have Many Network-Based Failure Points Take a look again at the above list of steps that a transaction goes through. Six of the 9 steps will cause the connection to fail and your data to be lost if the network connection is dropped. That's a lot of failure points. You repeat those failure points every time you make an HTTP request. So, the more times you make the request, the more chances you have of a request failing due to network issues.

JSON Objects Aren't That Big JSON objects, being only text, are quite tiny when done properly. They can get pretty large, but you'd have to be sending a ton of data (most likely more data than you actually need and can probably filter down, such as search results with too vague a search term) to do so. Compared to the cost of making the HTTP connection, you have to get pretty large to offset it with too much JSON data.

JavaScript Gets No Response From Dropped Connections This is why your "error" function is not being called on a dropped connection (an "error" response is still a response from the server). JavaScript will wait indefinitely, unless it's told otherwise, for a response. If the network connection drops, JS isn't aware of it, and will continue to wait for a response that never comes. Your best bet for this issue is to set a timeout mechanism and retry the connection if the previous one times out.

HTTP Requests Have Nothing to do with SQL Server You should have an application layer, which exposes an API to your client, between your client and SQL Server. As such, you can format the database requests in a way that makes sense for it, regardless of what you do on the client side.


问:
How will the new development of Java influence its interoperability with languages like Scala and Clojure?
As far as I understand, both Scala and Clojure have been designed as new languages that

depend on the JVM, and

easily integrate with Java code, in the sense that they allow to use Java classes inside Scala and Clojure code.

Starting with Java 8 (and maybe even more strongly with subsequent versions of Java), there will be changes in the semantics of the Java language.

I wanted to ask how these changes will impact the interoperability between Java and Scala / Clojure and what the consequences will be. For example, since lambdas in Java 8 are not objects (see e.g. here), Scala and Clojure might have to deal with Java values that are not objects. Would this be a problem?

I can think of the following scenarios:

The Scala or Clojure language will be extended to adapt to the new Java semantics (to handle the new non-object values) and support interoperability with Java.

The Scala or Clojure language will not be extended. This would only be possible if the new Java features like function values can be mapped to existing concepts. E.g., in Scala even a function is an object, so I guess Java functions would again be wrapped into some kind of objects when they become visible to Scala.

The Scala or Clojure language will continue to support interoperability up to Java 6 or 7, without following latest Java's development. This would require that older versions of Java be still supported (at least by OpenJDK or another project), so that these languages can be based on a more conservative / stable branch of Java.

Summarizing: can we expect that the future development of Java will have an impact on languages like Scala and Clojure to maintain interoperability with Java? Is there some (link to) ongoing discussion on this topic already?

Note

I can imagine that Scala, Clojure, and other JVM-based languages won't have any major problems updating their implementation to newer versions of the JVM (and that new JVM features will make this implementation even easier). My question focuses on features of Java as a language and whether / how other JVM-language will be able to "see" / use these new features, not on whether JVM-based languages will run on the latest JVM's.

答:
Scala's about to be left behind when Java adds lambdas because Java lambdas get assigned a type according to the context they're used in, whereas Scala lambdas get assigned a type based on their arities, parameter types and return types, so e.g.,

```<code>executor.execute(() -> { System.out.println("hello world"); });
</code>```

from Java 8 can be written in Scala as:

```<code>executor execute new Runnable {
    override def run() { println("hello world") }
}
</code>```

unless you use/write some wrappers converting Scala's () => Unit to Runnable.

Body:
Scala's about to be left behind when Java adds lambdas because Java lambdas get assigned a type according to the context they're used in, whereas Scala lambdas get assigned a type based on their arities, parameter types and return types, so e.g.,

executor.execute(() -> { System.out.println("hello world"); });

from Java 8 can be written in Scala as:

executor execute new Runnable {
    override def run() { println("hello world") }
}

unless you use/write some wrappers converting Scala's () => Unit to Runnable.


问:
how do you seperate from designing question to programming questions?
As i try to program a solution to a request arise. I can't separate the difference between implementation problems and design problems.

How do you specifically express the design problem?

答:
Firstly: design looks at the system from a more high level view than implementation.

Every software question has both design and implementation aspects. In terms of design, you need to know how the request will fit with your current implementation. If you do not have a current implementation (its a new project) then you need to weigh all desired aspects of the project to determine how everything will fit together. You should do this before worrying about the implementation, since the implementation depends on this work.

After you have an idea of how the system should look, then do it. Just start implementing your idea of the solution. Most likely you will realize during the implementation that you forgot to address an problem. When that happens, just slow down, answer the design decision, and then implement that.

If your customers are asking you straight programming requests, then you should never agree to a definitive answer without thinking it overnight. This will allow you to consider alternatives that they may not have realized. The customer may (not always, but potentially) have heard about a new technology and thought they MUST have it. You as the developer need to use technologies for a distinct reason, and "because the customer said it was awesome" is not a very good reason.

To a small extent, everything in software development is related. Using the waterfall methodology (which is still used as the basis for many methodologies today - a topic for another time perhaps) allows for small upstream adjustments as needed. That said, design looks at the system from a farther view point then implementation. Use that as a means to determine what level the question addresses.


问:
Why store a function inside a python dictionary?
I'm a python beginner, and I just learned a technique involving dictionaries and functions. The syntax is easy and it seems like a trivial thing, but my python senses are tingling. Something tells me this is a deep and very pythonic concept and I'm not quite grasping its importance. Can someone put a name to this technique and explain how/why it's useful?

The technique is when you have a python dictionary and a function that you intend to use on it.  You insert an extra element into the dict, whose value is the name of the function. When you're ready to call the function you issue the call indirectly by referring to the dict element, not the function by name.

The example I'm working from is from Learn Python the Hard Way, 2nd Ed. (This is the version available when you sign up through Udemy.com; sadly the live free HTML version is currently Ed 3, and no longer includes this example).

To paraphrase:

```<code># make a dictionary of US states and major cities
cities = {'San Diego':'CA', 'New York':'NY', 'Detroit':'MI'}

# define a function to use on such a dictionary
def find_city (map, city):
    # does something, returns some value
    if city in map:
        return map[city]
    else:
        return "Not found"

# then add a final dict element that refers to the function
cities['_found'] = find_city
</code>```

Then the following expressions are equivalent. You can call the function directly, or by referencing the dict element whose value is the function.

```<code>>>> find_city (cities, 'New York')
NY

>>> cities['_found'](cities, 'New York')
NY
</code>```

Can someone explain what language feature this is, and maybe where it comes to play in "real" programming? This toy exercise was enough to teach me the syntax, but didn't take me all the way there.

答:
Using a dict let's you translate the key into a callable. The key doesn't need to be hardcoded though, as in your example.

Usually, this is a form of caller dispatch, where you use the value of a variable to connect to a function. Say a network process sends you command codes, a dispatch mapping lets you translate the command codes easily into executable code:

```<code>def do_ping(self, arg):
    return 'Pong, {0}!'.format(arg)

def do_ls(self, arg):
    return '\n'.join(os.listdir(arg))

dispatch = {
    'ping': do_ping,
    'ls': do_ls,
}

def process_network_command(command, arg):
    send(dispatch[command](arg))
</code>```

Note that what function we call now depends entirely on what the value is of command. The key doesn't have to match either; it doesn't even have to be a string, you could use anything that can be used as a key, and fits your specific application.

Using a dispatch method is safer than other techniques, such as eval(), as it limits the commands allowable to what you defined beforehand. No attacker is going to sneak a ls)"; DROP TABLE Students; -- injection past a dispatch table, for example.

Body:
Using a dict let's you translate the key into a callable. The key doesn't need to be hardcoded though, as in your example.

Usually, this is a form of caller dispatch, where you use the value of a variable to connect to a function. Say a network process sends you command codes, a dispatch mapping lets you translate the command codes easily into executable code:

def do_ping(self, arg):
    return 'Pong, {0}!'.format(arg)

def do_ls(self, arg):
    return '\n'.join(os.listdir(arg))

dispatch = {
    'ping': do_ping,
    'ls': do_ls,
}

def process_network_command(command, arg):
    send(dispatch[command](arg))

Note that what function we call now depends entirely on what the value is of command. The key doesn't have to match either; it doesn't even have to be a string, you could use anything that can be used as a key, and fits your specific application.

Using a dispatch method is safer than other techniques, such as eval(), as it limits the commands allowable to what you defined beforehand. No attacker is going to sneak a ls)"; DROP TABLE Students; -- injection past a dispatch table, for example.


答:
It's to enable estimation to get better over time, without the estimators all having to adjust their estimation.

Rather than everyone involved in the estimate having to think like "OK.. looks like 2 man days.. but last sprint we underestimated everything, so maybe it's really 2.5 man days. Or 3?", they carry on the same as always. "5 story points!"

Then, you adjust your estimation of how many story points the team can get through in a sprint, based on actual measured achievement in previous sprints. "We've been doing 90-110 story points per sprint previously!"

I would say the theory behind this is that developers are better at estimating relative complexity of different dev tasks than they are at estimating absolutes. Especially if multiple people are estimating a task which could be done by any one of them (and not everyone works at the same speed as everyone else).

Cynical alternative: I've seen it said that developers never come in under time estimates. If something takes longer than was estimated, you've gone over. But if something takes less time than estimated, developers may fiddle with it, gold-plate, or just slow down and take it easy since they've been given a cushy assignment. Taking the real units of time out of an estimate may curb these tendencies. End cynical alternative.


问:
How should I represent an enumerated type in a relational database?
I am working on developing a relational database that tracks transactions that occur on a device I'm working on for my company. There are different types of transactions that could occur on the device, so we have a "trans_type" field in one of our main record tables. My group has decided to make the type of this field an integer and treating it as an enumerated type. My intuition tells me that it would be a better idea to make this field a string so that our database data would be more readable and usable. My co-workers seem to be worried that this would cause more trouble than it is worth. That string comparisons are too costly and the possibility of typos is too great of a barrier.

So, in your opinion, when dealing with a field in a relational database that is essentially an enumerated value, is it a better design decision to make this field an integer or a string? Or is there some other alternative I've overlooked?

Note: explicit enumerated types are not supported by the database we are using. And the software we are developing that will interface with this database is written in C++.

答:
Enumerated types should be a separate table in your database that have an id number and a string name and any other columns you might find useful. Then each type exists as a row in this table. Then in your table you are recording the transactions the "trans_Type" field should be a foreign key to the key of that reference table. This is a standard practice in database normalization.

This way you have stored the one official name string, get to use number comparisons for performance, and have referential integrity that every transaction has a valid type.


答:
An common practice is to create a trans_types table, and then have your main table reference it with foreign key named trans_type_id. This ensures that your records will only reference valid enumerated types.

Example:

```
trans_type
----------
  id
  name

transactions
------------
  id
  trans_date
  details
  trans_type_id (FK to trans_type.id)

```

Example Data:

```

trans_type

ID |  NAME
----------
1  |  SUBMIT
2  |  CANCEL

transactions

ID | trans_date  | trans_type_id
---------------------------------
1  | 2012-12-31  | 1
2  | 2013-01-09  | 2
```

Title: How should I represent an enumerated type in a relational database?

Body:
I am working on developing a relational database that tracks transactions that occur on a device I'm working on for my company. There are different types of transactions that could occur on the device, so we have a "trans_type" field in one of our main record tables. My group has decided to make the type of this field an integer and treating it as an enumerated type. My intuition tells me that it would be a better idea to make this field a string so that our database data would be more readable and usable. My co-workers seem to be worried that this would cause more trouble than it is worth. That string comparisons are too costly and the possibility of typos is too great of a barrier.

So, in your opinion, when dealing with a field in a relational database that is essentially an enumerated value, is it a better design decision to make this field an integer or a string? Or is there some other alternative I've overlooked?

Note: explicit enumerated types are not supported by the database we are using. And the software we are developing that will interface with this database is written in C++.

Body:
An common practice is to create a trans_types table, and then have your main table reference it with foreign key named trans_type_id. This ensures that your records will only reference valid enumerated types.

Example:

trans_type
----------
  id
  name

transactions
------------
  id
  trans_date
  details
  trans_type_id (FK to trans_type.id)

Example Data:

trans_type

ID |  NAME
----------
1  |  SUBMIT
2  |  CANCEL

transactions

ID | trans_date  | trans_type_id
---------------------------------
1  | 2012-12-31  | 1
2  | 2013-01-09  | 2


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
There are 2 hard problems in computer science: cache invalidation, naming things, and off-by-1 errors.

    — Leon Bambrick (@secretGeek)

(Actually, everything from http://q4td.blogspot.com/search/label/programming seeing as I curate the list.)

LastEditorDisplayName: Roger Pate


问:
Why doesn't the .NET world have anything like rails/grails/django/roo?
It seems to me that rapid-development web platforms are going to radically change the world of web applications.

It has been five years since Rails 1.0 was released for Ruby, and since that time we have seen Grails for Groovy, Django for Python, and Roo for Java.

But to my knowledge (which is probably limited, being a Java/Groovy progammer) there is no similar framework for C#.

Does such a thing exist?  If not, why not?

Edit:  It's quite possible I'm not using the right words when I say "rapid-development," but I'm talking about frameworks that can conceivably allow you to build a working blog engine in 30 minutes.  You couldn't reasonably do this with, say, Java, Spring, and Hibernate, given the various configuration needed to allow your controllers to be found, and both configuration and code necessary for your entities to persist and be retrieved.

So I'm talking about frameworks that handle all of the CRUD with a convention-over-configuration mentality.  If someone has the right words for what I'm talking about, let me know.

答:
It seems to me that there is no name yet for this kind of framework you are all talking about in this thread. I call them for the moment just RAILS-like Frameworks: Frameworks that increment productivity by orchestrating other existing frameworks with the purpose of solving the basic needs of most web applications, but at the same time hiding all the complexities from the developer.

By basic needs I mean the implementation of a Persistence Provider, a Dependency Inyection Container, a Logging tool, an MVC platform, an HTML Template Engine, a Web Site Template Starter Kit with CSS presets, a Security Framework and some Javascript Library for AJAX features and other cool stuff. The RAILS-like Frameworks orchestrate all these frameworks and tools on the basis of the Domain model (the entities of your system with its attributes).

Thanks to the Convention-over-Configuration principle, these frameworks avoid the need of defining lots of configuration files usually required by the frameworks they orchestrate (like Spring, Spring MVC, Hibernate, Log4J, etc.), assuming configurations by default based on naming, structure and metadata included in the same classes definitions.

Thanks to the dynamic languages that these frameworks make use (like Ruby, Groovy, Python, Clojure, etc.), with the exception of SpringRoo that implements dynamic behaviour in Java by using AspectJ, the functionality that belongs to the frameworks underneath are extended and are made available to the developer in such a uniform and elegant manner that he/she is just aware of the underlying technologies.

Finally thanks to the Scaffold technique, unit tests, integration tests, controllers and views are automatically generated for the main functions (CRUD) over each one of the domain objects defined by the developer.

In the .NET world nothing has been developed yet, following all the previous definitions. But nothing prevents that from occurring soon. There are great frameworks, tools and libraries already available in the .NET world that can be orchestrated by a new RAILS-like framework made for the CLR. There are Unity, Spring.NET and Castle Windsor among others for the Dependency Inyection needs. Entity Framework 4, NHibernate and iBatis.NET are pretty good .NET Persistence Providers. ASP.NET MVC have strongly arrived with support for various Template Engines besides the traditional ASP.NET.

Even if nobody achieves to use a DLR language to build this kind of framework, anyone with enough will can follow the SpringSource path and implement a RAILS-like framework with some static language like F#, C# or VB.NET, making use of an Aspect-Oriented Container (like AspectSharp or Gripper-LOOM.NET) to obtain dynamic behaviour.

I would love to know about any group of people trying to develop such framework in .NET.

OwnerDisplayName: Rodrigo Salinas


答:
If the values are coming into the database as integers, store them that way. There's no need to put the over-head of converting to strings while writing to the database. You can always relate to a lookup table with the string/text values (More Normalized).

This has the added advantage of updating the string value in a single location instead of running some sort of update routine. Instead of 1 = 'Red' it could equal 'Really Red'

This is not ideal for reporting performance compared to just needing one table with string values (Denormalized). An index on this field would make performance good enough.

Most RDBMS will allow enough horsepower. Although your idea of being able to 'read' the table in its plain data form, joining a table is no big deal. Just get in the habit of using a view or some similar object.


答:
@Martijn Pieters did a good job explaining the technique, but I wanted to clarify something from your question.

The important thing to know is that you are NOT storing "the name of the function" in the dictionary. You are storing a reference to the function itself. You can see this using a print on the function.

```<code>>>> def f():
...   print 1
...
>>> print f
<function f at 0xb721c1b4>
</code>```

f is just a variable that references the function you defined. Using a dictionary allows you to group like things, but it isn't any different from assigning a function to a different variable.

```<code>>>> a = f
>>> a
<function f at 0xb721c3ac>
>>> a()
1
</code>```

Similarly, you can pass a function as an argument.

```<code>>>> def c(func):
...   func()
...
>>> c(f)
1
</code>```

Title: Why store a function inside a python dictionary?

Body:
I'm a python beginner, and I just learned a technique involving dictionaries and functions. The syntax is easy and it seems like a trivial thing, but my python senses are tingling. Something tells me this is a deep and very pythonic concept and I'm not quite grasping its importance. Can someone put a name to this technique and explain how/why it's useful?

The technique is when you have a python dictionary and a function that you intend to use on it.  You insert an extra element into the dict, whose value is the name of the function. When you're ready to call the function you issue the call indirectly by referring to the dict element, not the function by name.

The example I'm working from is from Learn Python the Hard Way, 2nd Ed. (This is the version available when you sign up through Udemy.com; sadly the live free HTML version is currently Ed 3, and no longer includes this example).

To paraphrase:

```<code># make a dictionary of US states and major cities
cities = {'San Diego':'CA', 'New York':'NY', 'Detroit':'MI'}

# define a function to use on such a dictionary
def find_city (map, city):
    # does something, returns some value
    if city in map:
        return map[city]
    else:
        return "Not found"

# then add a final dict element that refers to the function
cities['_found'] = find_city
</code>```

Then the following expressions are equivalent. You can call the function directly, or by referencing the dict element whose value is the function.

```<code>>>> find_city (cities, 'New York')
NY

>>> cities['_found'](cities, 'New York')
NY
</code>```

Can someone explain what language feature this is, and maybe where it comes to play in "real" programming? This toy exercise was enough to teach me the syntax, but didn't take me all the way there.

Body:
@Martijn Pieters did a good job explaining the technique, but I wanted to clarify something from your question.

The important thing to know is that you are NOT storing "the name of the function" in the dictionary. You are storing a reference to the function itself. You can see this using a print on the function.

>>> def f():
...   print 1
...
>>> print f
<function f at 0xb721c1b4>

f is just a variable that references the function you defined. Using a dictionary allows you to group like things, but it isn't any different from assigning a function to a different variable.

>>> a = f
>>> a
<function f at 0xb721c3ac>
>>> a()
1

Similarly, you can pass a function as an argument.

>>> def c(func):
...   func()
...
>>> c(f)
1


问:
php return values
I have a codeigniter app and in my model, I always return true or false for all functions, and if I have data that needs to be passed, I also set a property that contains my data.

The only trouble is, in my controller, if I have to call 3 or 4 methods in my model, the code gets really repetitive.

```<code>If ( $this->my_model->functionA() )
{
    $localvar = $this->my_model->data();
}
else
{
    show_error("Error A");
}
If ( $this->my_model->functionB() )
{
    $localvar = $this->my_model->data();
}
else
{
    show_error("Error B");
}
If ( $this->my_model->functionC() )
{
    $localvar = $this->my_model->data();
}
else
{
    show_error("Error C");
}
</code>```

I'm wondering if i change the logic so that the functions don't return true, but return the data instead... does it simplify things alot?
I think I'd still need code like this:

```<code>If (! $this->my_model->functionA() )
{
    show_error("Error A");
}
else
{
    $localvar = $this->my_model->data();
}
</code>```

Or is there a way I can combine my $localvar assignment statement with the if statement?

Is there a better way to do this?

答:
Since you're checking for system errors, I would use exceptions instead of just return values.
And keep in mind your model preserves state, so its data does not need to be returned for every function.  This is far more readable:</p>

```<code>try {
    $this->my_model->functionA();
    $this->my_model->functionB();
    $this->my_model->functionC();
    $localvar = $this->my_model->data();
}
catch (Exception $e) {
    show_error($e->getMessage());
}
</code>```

Title: php return values

Body:
Since you're checking for system errors, I would use exceptions instead of just return values.
And keep in mind your model preserves state, so its data does not need to be returned for every function.  This is far more readable:

try {
    $this->my_model->functionA();
    $this->my_model->functionB();
    $this->my_model->functionC();
    $localvar = $this->my_model->data();
}
catch (Exception $e) {
    show_error($e->getMessage());
}


问:
Is a Unique ID column needed in a many-to-many (junction) table?
Getting a few projects started with EF, but I had some questions about join tables and keys etc. Lets say I have a table of applications and a table of permissions. Applications have many permissions and each permission can belong to many applications (many-to-many).

Now, the Application and Permission tables are easy:

```<code>Applications
--------------
PK  ApplicationID
    Name

Permissions
--------------
PK  PermissionID
    Name
</code>```

But what's the BEST way to do the join table? I have these two options:

```<code>ApplicationPermissions
-----------------------
PK  ApplicationPermissionID
CU  ApplicationID
CU  PermissionID
</code>```

OR

```<code>ApplicationPermissions
-----------------------
CPK ApplicationID
CPK PermissionID

PK = Primary Key
CPK = Composite Primary Key
CU = Composite Unique Index
</code>```

Have you ever been burned doing it one way over the other? is it strictly preference? It has occurred to me that a lot of the "differences" will be abstracted away by my repository pattern (for example, i would almost never create an entire permission object and add it to an application, but do it by ID or unique name or something), but I guess I'm looking for horror stories, one way or the other.

答:
I believe you mean "junction" table, not "join" table.

There is no need for a junction table to have it's own ID field. You would never need to join or filter on such an ID. You would only join or filter on the ID's of the tables you're mapping. An ID on a junction table is a waste of disk space.

So the "best" option is to avoid the ID. Typically a junction table will have 2 covering indexes. Each covering index using one of the mapped ID's as the primary sort field.

But "best" is not by a long shot. It's a very minor issue to have a redundant ID field. You will not have any horror stories over a small amount of wasted disk. The ID won't "steal" the clustered index because you don't want to cluster on the mapped combo anyway.

If your framework wants all tables to have an ID, then go for it. If your team's database standards dictate all tables must have an ID then go for it.  If not, then avoid it.


答: Technically no, but "normal OOP" assumes dynamic allocation, for which a heap is a good general-purpose mechanism.  You could certainly try using some other method, but you'd probably wind up re-inventing the heap.</p>

Title: Possible to implement OOP without using extensive heap operations?

Body: Is the concept of OOP intimately tied to allocating objects on the heap? Is it possible to write normal OOP without creating excessive objects on the heap?</p>


问:
Are there differences between Functionality and Functional Requirements
I'm writing some documentation in a project in a tool. In this tool of mine, and write in specific area, I have here use Case, Business Rule, N-Diagram Types, and Functionality and Functional Requirements.

So I got me wondering, Are there differences between Functionality and Functional Requirements?

In my vision, a Functionality a implementation of a Functional Requirement, is it correct? What other differences one can find between them?

答:
Functionality is what a program does.

Functional requirements are what you want the program to do.


问:
Referential integrity in a database where tuples are not physically deleted
Many modern Relational Database Management Systems automatically support referential integrity, i.e. when you try to delete a tuple which has a reference (in the form of foreign key, for example), the DBMS doesn't complete the operation and brings an error.

Consider a database where every table has an attribute, which indicates if a tuple is deleted or not. So no data is actually deleted from the database, but is marked as deleted instead. If a tuple is marked as deleted, all its references need to be marked as deleted too or an error should occur. How can this be supported?

Is performing additional checks (programmatically or with triggers) before deleting a tuple the only way to have referential integrity? Are there any accepted practices or algorithms?

Edit: This flag is mostly used for statistics, and partially for data recovery after a long period of time. It is filter with a special meaning, and right now when queries are made, referential integrity is checked right in the query, which is extremely error prone and not reliable at all.

答:
Setting a "deleted" flag on a tuple doesn't actually delete the tuple, nor does it necessarily mark the tuple for actual deletion. The "deleted flag" merely provides a way for applications to filter out the records that have been flagged as deleted.

So deleting a record from a table having records related by referential integrity still works the same way.  All of the related records must still be deleted (including the ones "marked as deleted").

Why would one do this?  Because the "deleted flag" allows trivial recovery of the deleted record, by simply setting its "deleted flag" to false.  Some systems allow "retirement" of such records by permanently removing them from the database after a certain period of time.


问:
How and why to decide between naming methods with "get" and "find" prefixes
I always have trouble figuring out if I should name a certain method starting with getSomething versus findSomething.

The problem resides in creating helpers for poorly designed APIs. This usually occurs when getting data from an object, which requires the object as a parameter. Here is a simple example:

public String getRevision(Item item) {
    service.load(item, "revision");
    // there is usually more work to do before getting the data..
    try {
        return item.get_revision();
    }
    catch(NotLoadedException exception) {
        log.error("Property named 'property_name' was not loaded", exception);
    }
    return null;
}
```

How and why to decide between naming this method as getRevision() or findRevision()?

答: To me, find implies there can possibly be more than one result present.  get implies only one.


问:
does haskell have dependent types?
I know Haskell already has the ability to parametrise a type over another type (similar to template programming in C++), but I'm wondering whether Haskell can also parametrise a type over values – whether it supports dependent types. With dependent types, you can have a type that's parametrised over integers, for example vectors of size n, matrices of size n×m, etc.

If not, why not? And is there any possibility that it will be supported in the future?

答:
Haskell doesn't quite have full dependent types, although it can get very close with extensions like DataKinds and TypeFamilies.  The issue at the moment, as far as I know, is that value-level Haskell has explicit bottoms but type-level Haskell does not.

This doesn't stop you from parametrizing types over other types, including the DataKind-lifting of values.  As of GHC 7.6, and with DataKinds enabled, you can use type-level naturals and strings, as well as type-level tuples, type-level lists, and the type-level liftings of any (non-higher-kinded, non-generalized, non-constrained) algebraic data types, which is similar to (but much more general than) C++'s ability to use integers in templates.

Title: does haskell have dependent types?


答:
get is appropriate in any case _ in fact it is often assumed that in order to get something you need to find that first. So if you're not sure, use get.

I would use find for methods like findMinimum() or findOptimal(), i.e. where there is some special algorithm which calculates the return value, and doesn't simply make a request to the DB, file system, remote server, etc. to receive some data.

Title: How and why to decide between naming methods with "get" and "find" prefixes

Body:
I always have trouble figuring out if I should name a certain method starting with getSomething versus findSomething.

The problem resides in creating helpers for poorly designed APIs. This usually occurs when getting data from an object, which requires the object as a parameter. Here is a simple example:

public String getRevision(Item item) {
    service.load(item, "revision");
    // there is usually more work to do before getting the data..
    try {
        return item.get_revision();
    }
    catch(NotLoadedException exception) {
        log.error("Property named 'property_name' was not loaded", exception);
    }
    return null;
}
```

How and why to decide between naming this method as getRevision() or findRevision()?


答:
I use Get when I know the retrieval time will be very short (as in a lookup from a hash table or btree).

Find implies a search process or computational algorithm that requires a "longer" period of time to execute (for some arbitrary value of longer).


答: I would say that find may fail but get shouldn't.