问:
Why does IEEE 754 Single Float have 8 bits for exponent but only allow 38 base ten Max Value
Why is it that the IEEE 754 standard provide 8 bits for the exponent but puts a range maximum of 38 on the largest acceptable exponent?

Seems kind of ridiculous to have the data storage there but not allow it to actually be used.

I wanted to pack data into this exponent for some encoding I'm doing, but I can't use all the bits because I can't pack an exponent larger than 38! I was hoping to pack values up to 256 using all bits (2 ^ 8).

答:
IEEE 754 standard single-precision (i.e., 32-bit) floats reserve 1 bit for the sign bit, 8 for the exponent, and 23 for the mantissa. I'm not sure where you're getting a value of 38 (base 10) from as the "maximum" exponent. Please clarify in the comments if I'm interpreting this incorrectly.

Since the exponent is 8 bits, the range of exponent values can be anywhere between 00000000 and 11111111 (which are reserved for 0 and infinity, respectively). However, any exponent value between 00000001 and 11111110 is valid. So, accounting for a bias of -127, you can achieve an exponent of 127.

So, assuming a mantissa of all 1's (i.e., a value very close to 2), you can achieve up to 2^127 for your encoding.

If all you need is 2^8 for your encoding, consider using overall fewer bits in your floating point number.

Read more here: http://steve.hollasch.net/cgindex/coding/ieeefloat.html


问:
Algorithm to find times when resources are available
I'm writing a semi-automatic scheduling application. Given some existing bookings and some resource requirements, it needs to find the times at which a new event can be scheduled. A human user will then evaluate the results and choose one of the options. It does not need to optimise a timetable for multiple events and hence it is not the usual NP-Hard timetabling problem.

The system has a number of resources (trainers, rooms, equipment) each of which has a type (e.g. French teacher, seminar room, projector...). Resources are booked for events each of which has a start and end time.

Now, say I need to schedule a 2 hour long French class using a projector in a seminar room, what are the times that at least one resource of each required resource type is available?

In order to limit the problem space, it's acceptable to consider only 9am-5pm, Mon-Fri at 15 minute intervals for the next 90 days. Total number of resources in of the order of 1000.

How can I do this without having to compare every resource with every other resource?

答: One presumes you have three tables - trainers, rooms, equipment.  You have a 'blocksize' of 2 hours. So the first temporary result set you generate (in this case for trainers) lists the available trainers and their block starting times, where only those that have at least two hours available are included. You create another result set for rooms, and another for equipment.  At this point you merge the available times of all three categories into one list and assign each interval an identity, therefore day 1 hour 1 is 1, day 1 hour 2.5 is 2, day 3 hour 3.25 is 3, etc.  You have one (combined) list of all times available in all categories.  These IDs get updated back into the respective intermediate sets.  Thus the first time slot available for a room might be 2, the first for a trainer might be 5, and the first for equipment might be 7.  Now you query on the set of all records where 'trainertimeid = roomtimeid and trainertimeid = equipmenttimeid'. What is returned is the set of all records where availability is found in all three categories.</p>

ContentLicense: CC BY-SA 3.0


答:
Floating point stores the exponent and mantissa in base two, not base 10. Two to the 127th power corresponds roughly to ten to the 38th power, so that's the largest decimal number that can be stored.

See https://www.google.com/#q=2+to+the+127th+power

Title: Why does IEEE 754 Single Float have 8 bits for exponent but only allow 38 base ten Max Value

Body:
Why is it that the IEEE 754 standard provide 8 bits for the exponent but puts a range maximum of 38 on the largest acceptable exponent?

Seems kind of ridiculous to have the data storage there but not allow it to actually be used.

I wanted to pack data into this exponent for some encoding I'm doing, but I can't use all the bits because I can't pack an exponent larger than 38! I was hoping to pack values up to 256 using all bits (2 ^ 8).


答:
I would try to use a one dimensional sweep-line algorithm for this. First, for each resource part of a booking, find out the points in time where its status switches from "available" to "booked", or vice versa (restricted, for example, for every point in time after now). You put each of this points in time into a data record containing

time stamp

kind of status switch (to "booked" or "available")

reference to the resource

Make one list of all of those records and sort it by time stamp. Next, you create a boolean array with a flag "available" for each of the resources, initialize it with the current availability status. Finally, the "sweep" takes place: walk through the sorted list from one record to the next, change the availability state in your boolean array of the related resource, until each of the flags have the state "available". Move one record further and get the time stamp, this will tell you how long the resources are all available within a contiguous time interval (you may take care for not crossing day boundaries here). If the time span is long enough, you found a solution in form of a time interval. You continue this until your reach the end of the list or your have enough intervals found.

As a bonus, this works fine with or without the "15 minute" and "90 days" constraints.

Title: Algorithm to find times when resources are available

Body:
I'm writing a semi-automatic scheduling application. Given some existing bookings and some resource requirements, it needs to find the times at which a new event can be scheduled. A human user will then evaluate the results and choose one of the options. It does not need to optimise a timetable for multiple events and hence it is not the usual NP-Hard timetabling problem.

The system has a number of resources (trainers, rooms, equipment) each of which has a type (e.g. French teacher, seminar room, projector...). Resources are booked for events each of which has a start and end time.

Now, say I need to schedule a 2 hour long French class using a projector in a seminar room, what are the times that at least one resource of each required resource type is available?

In order to limit the problem space, it's acceptable to consider only 9am-5pm, Mon-Fri at 15 minute intervals for the next 90 days. Total number of resources in of the order of 1000.

How can I do this without having to compare every resource with every other resource?


问:
What parts of functionality should be refactored into a directive?
I am creating an application from legacy code using AngularJS.

I wonder what parts of my code should be moved into a directive.

For example, iI had thought of moving a table which is used multiple times across the application into a directive. The tables alter from headings and size.

Is it worth the effort or even a good practice to turn such things into their own directives or should I create each table in a unique way?

答:
There are quite a few reasons for using a directive:

The classic one: it needs to access the DOM / window / document. This should be kept to a bare minimum however, as Angular can handle a lot of things via templating + 2 way data-binding.

You have a reusable component, or one that might be reused in future. This should be considered even if it doesn't need to access the DOM directly, as directive templates are still $compiled in the usual way, and support all the standard 2-way data bindings.

You have a controller or template that you would like to somehow pass options to, or call functions or update data on the parent scope, without polluting the scope chain. You can use the scope option when creating a directive for this, which can handle the 3 most used cases

Binding a variable on the directive's isolated scope to the parent scope (using =). For example, I suspect the usual use of ngModel uses this so it can modify the model object as needed.

Creating a function on the directive's isolated scope that then evaluates an expression in the parent scope (using &). For example, I suspect ngClick uses this to pass a callback to the directive.

Binds a variable on the directive's isolated scope to an interpolated string on the parent scope specified by an attribute (using @). TBH, I'm yet to use this.

If for some reason you then still need access the attributes of the element directly, you can use the argument that is often referred to as tAttrs / iAttrs in the compile and link functions. See the documentation for $compile

You would like to enforce a separation of concerns between business logic, and view logic. You could make a generic table component to show data from completely difference sources in different parts of your app. Maybe then add some sorting functionality, etc.

You would like to make smaller component controllers, and allow them to still communicate with each other, in a non-brittle (with respect to the DOM) way. The require option when creating a controller allows directive controllers to communicate with each other. For example, ngModel must require an optional parent ngForm, so it then registers itself with the form at linking time, so the ngForm can work out its validation state. If you want to customise or create your own form inputs, then you can require ngModel to communicate with its controller. Adding parsers or custom validation would be a typical use-case for this.

One that should be used very sparingly: if you want to make a variable or function accessible to all child scope/templates. For example, I recently made a responsive directive, without an isolated scope, that adds a variable to the scope, and hence all child scope, that holds the current window size + "class" (say, mobile or large screen). This changes on a debounced listener + $apply to the window resize event, so other templates only change when the window has stopped resizing.

Another use case for this, is to add routing $state to all child scopes. The example at https://github.com/angular-ui/ui-router/wiki/Quick-Reference#note-about-using-state-within-a-template uses run and $rootScope, but a slightly more flexible approach would be to add this in a directive, so theoretically you could have a section in your app without the $state variable in the scope/template.

If any of the above would hold true if you were to refactor, then definitely consider it. I think the main jist of the above is that the components should be small, and have a clearly defined purpose, and so be fairly easy to test. If things are long, consider refactoring to directive(s). The above points are all to do with the interface. If you have common business functionality, then this would typically be in services.


问:
Why isn't exponentiation hardware-implemented?
Why is there no exponentiation operation in hardware, even though many languages have builtin operators for it?

Is it because even hardware implementations would need to use the same algorithm as software (i.e. no hardware implementation could be significantly more efficient), or because it is rarely used, or another reason?

答:
For integers, the only exponentiation operations that are normally present in hardware are the shifts, << and >> (in C parlance), which multiply by exponential powers of two. For anything else with integers, you run out of bits to represent things far too quickly for it to be useful; by the time you've sorted that problem out, you might as well not have special hardware support as you've also had to deal with memory management and other such expensive things.

I don't know floating-point hardware so well, but hardware exponentiation makes more sense there as you've got the numeric range to make it reasonable. (My google-fu indicates that someone seems to be selling the hardware layout to make this possible…)


问:
Does Abstract Factory Pattern scale?
I'm still trying to understand design patterns here, after learning the Abstract factory pattern , I realised that this pattern will not scale well. Take a look at the uml diagram of the abstract factory pattern

If I have to create a new 'AbstractProductC', I will have to add an abstract method 'CreateProductC' in 'AbstractFactory' which effects the implementation of both ConcreateFactory1, ConcreateFactory2.

My question here is, does Abstract Factory pattern scale at all (or) I'm I thinking in the wrong direction here ?

thanks in advance

答:
Yes, you are right, "abstract factory" does not scale well when you need additional abstract products.

But in a lot of real-world scenarios you have a changing number of products, but only a small, fixed number of abstract products to support. For instance, take the GUI widgets example from the wikipedia article about abstract factories. The abstract GUI factory could have a method createWidget (instead of createButton), where Widget is the "abstract product", beeing the topmost base class for a family of several dozen GUI elements. Adding new GUI widgets does in no way imply a change to the interface of the abstract factory, so none of the concrete factory`s interfaces has to be changed.

Having lots of abstract products means you will have a lot of different class hierarchies in your code. And if that's the case, you may consider to create an individual factory (or abstract factory) for each of the hierarchies.

Title: Does Abstract Factory Pattern scale?


问:
Why is the copying instruction usually named MOV?
In quite many assemblers, a value copying instruction is usually named "MOV" and its description in manuals usually also contains "move" (however, other words can be used, like "load", "store", "extract", etc.) It's uncommon to find an ISA ) which doesn't follow this convention.

On the other hand, in other contexts, "move" differs from "copy" in sense that source is destroyed (for example, "mv" vs. "cp" in Unix, Move[F6] in Norton Commander and clones, etc.) Assembler's "move" really has semantic "copy", keeping the source value intact.

I've found that this has started at least since IBM 1401 (1959), but, IBM 360 used this word only for in-storage copying, but not for operations between registers and storage (which used "load" and "store"). But why it's still widely used and not replaced with "copy" or "store"?

答:
Replacing an instruction means breaking backward compatibility. An assembler with the new syntax will not be able to assemble code written with the old syntax - unless that code doesn't use that instruction(and the only place where you'll see an assembly code that doesn't use MOV is in syntax examples that show other instructions...)

Compilers usually generate assembly code and automatically pass it to the assembler, so they'll have to be modified as well to fit the new assembler. If a language allows inline assembly, old source code that uses inline assembler with MOV instructions won't work anymore.

So, we are talking about a gigantic code breakage, and for what? it won't make the language any more readable, because unlike some high level language you have no chance of telling what an assembly code does without knowing assembly, and if you know assembly you know what MOV does.

Huge cost with zero gain easily explains why the instruction hasn't been renamed.


问:
Why did the team at LMAX use Java and design the architecture to avoid GC at all cost?
Why did the team at LMAX design the LMAX Disruptor in Java but all their design points to minimizing GC use? If one does not want to have GC run then why use a garbage collected language?

Their optimizations, the level of hardware knowledge and the thought they put are just awesome but why Java?

I'm not against Java or anything, but why a GC language? Why not use something like D or any other language without GC but allows efficient code? Is it that the team is most familiar with Java or does Java possess some unique advantage that I am not seeing?

Say they develop it using D with manual memory management, what would be the difference? They would have to think low level (which they already are), but they can squeeze the best performance out of the system as it's native.

答:
It seems the reason it's written in Java is that they have Java expertise in-house and it was probably written (although it's still in active development) before C++ got its act together with C++0x/11.

Their code is really only Java by name, they use sun.misc.Unsafe quite a bit which kind of defeats the point of Java and the safety is supposedly gives. I have written a C++ port of the Disruptor and it outperforms the Java code they ship (I did not spend a lot of time tuning the JVM).

That said, the principles that the disruptor follows are not language specific, e.g. Don't expect low latency C++ code that allocs or frees from the heap.


答:
In some instruction sets, there exist distinct instructions to load a register from memory, store a register to memory, or transfer things among registers.  While some assembly language forms use the verb "load" for everything (e.g. Zilog's Z80 mnemonics use ld a,(1234h), ld (1234h),a and ld a,b) , and some use "T"ransfer (e.g. the 6502 with TXA for "transfer X to A"), some use "move" for regster-to-register operations to distinguish them from loads and stores.  If one has an instruction format like the 68000 which uses the same general instruction form for register-to-register, register-to-memory, memory-to-register, and even memory-to-memory operations, the verb "move" is probably a better general-purpose verb than any of the alternatives.

I have no idea about minicomputer or mainframe instruction sets prior to the 8080, but the 8080 used "load" and "store" for most memory-access instructions and "mov" for register-to-register instructions, but most instructions which could operate on an arbitrary 8-bit register could also operate on "M", which was the memory location addressed by HL, so a "MOV" to or from "M" would actually behave as a load or store.

As for the distinction between "copy" and "move", I suspect that has a lot to do with the fact that code can neither create nor destroy registers; they just exist.  In describing the behavior of the code sequence mov bx,ax / mov ax,1234, does it make more sense to say the first instruction copies bx to ax, and the second instruction destroys the value in ax and replaces it with the value 1234, or does it make more sense to view the first instruction as having moved the value from bx to ax (making the value in ax a "don't care"), and the second instruction loads ax (which had been don't-care) with 1234?  Sometimes the source registers is still meaningful after a register-transfer instruction, but since there's nothing in the instruction set to indicate whether it will be, and in many common situations it isn't, "move" seems reasonable.

Title: Why is the copying instruction usually named MOV?

Body:
In quite many assemblers, a value copying instruction is usually named "MOV" and its description in manuals usually also contains "move" (however, other words can be used, like "load", "store", "extract", etc.) It's uncommon to find an ISA ) which doesn't follow this convention.

On the other hand, in other contexts, "move" differs from "copy" in sense that source is destroyed (for example, "mv" vs. "cp" in Unix, Move[F6] in Norton Commander and clones, etc.) Assembler's "move" really has semantic "copy", keeping the source value intact.

I've found that this has started at least since IBM 1401 (1959), but, IBM 360 used this word only for in-storage copying, but not for operations between registers and storage (which used "load" and "store"). But why it's still widely used and not replaced with "copy" or "store"?


问:
Python - defining exit method before importing
This breaks nothing (in my experience), but lots of things "don't break anything" and are still wrong.

```<code>#! /usr/bin/env python
"""Short description of this module."""

def preferred_exit_method(*args):
    #code for exiting as desired

try:
    import foo
    import bar
    import eggs
except ImportError as e:
    #code code code
    preferred_exit_method(e)
</code>```

So, clearly defining the program's behavior on exit, then using it during the import process can't be too terrible, right? But it goes against the oft-cited PEP 8, which states that modules should be absolutely be imported before anything global.

It seems like an unrisky proposition, but then there's always something like this:

```<code>#! /usr/bin/env python
"""Description of module"""

def exit_of_choice(*args):
    #code code code
    sys.exit(0)

try:
    import sys
    import other_things
except ImportError as e:
    exit_of_choice(e)
</code>```

Apart from writing code that never needs to do this because it is perfect and never fails at anything, is there a reason besides PEP 8 and "other Python people will be cross with you" not to do this? (well, I'm less concerned with the latter - even though sys wouldn't typically fail to import, I still sort of hate that on principle)

答: While what you are doing does go against convention, it is not wrong. If your program needs to do something special upon exit, it is worth sacrificing some of the organization in it, especially if you do not mind that much if "python programmers are cross with you". There are few performance issues when modules are imported later in the program, and properly exiting seems like something that should be of higher priority. That being said, I do have a solution that will organize things to get the best of both worlds. You could have two files. One has the preferred exit method. This will run the other file, and address all of the other file's errors. That means that that file's errors will always be addressed properly.</p>


问:
Would adding an @beta doc-comment tag be useful?
When a function has reached the end of its life, we add a @deprecated tag into its doc-comment to notify other developers that they should stop using this function, and then a couple years later it's removed.

I was just thinking about an @beta tag to signify this method is brand new and hasn't been tested in a variety of use-cases yet.

You might be thinking "you can write use-cases to ensure its correctness!" Of course you can, but its the API that concerns me, and how it behaves in edge-cases. Sometimes these decisions are not obvious until you have tried out the function in a variety of situations. Sometimes new parameters need to be added to cover more use-cases. Sometimes re-ordering them makes sense if you find that an argument is actually optional and needs to be moved to the end (or vice versa).

By adding the @beta tag, you are warning other developers that the API of this method might change yet, and they should use it with extreme caution. This gives you more granular control over your API instead of making the entire project 'beta'.

To get the most use out of this, however, IDEs and documentation-generators would need to pick up on this tag.

What do you guys think? Could you see this as being useful, is it a waste of time, or do you have other ways of dealing with this?

In the past, I have made such methods 'private' where possible, or prefixed them with an underscore.

答: I actually like your suggestion. It is sort of a pre-cursor to adding something like the word 'final' in-front of a function. It makes a lot of sense, and while the above comments suggest having use and test cases is prudent, often times in the real world we can't create or even see every test case until something comes up.</p>


问:
Why didn't == operator string value comparison make it to Java?
Every competent Java programmer knows that you need to use String.equals() to compare a string, rather than == because == checks for reference equality.

When I'm dealing with strings, most of the time I'm checking for value equality rather than reference equality. It seems to me that it would be more intuitive if the language allowed string values to be compared by just using ==.

As a comparison, C#'s == operator checks for value equality for strings. And if you really needed to check for reference equality, you can use String.ReferenceEquals.

Another important point is that Strings are immutable, so there is no harm to be done by allowing this feature.

Is there any particular reason why this isn't implemented in Java?

答:
Java seems to have been designed to uphold a fundamental rule that the == operator should be legal any time one operand can be converted to the type of the other, and should compare the result of such conversion with the non-converted operand.

This rule is hardly unique to Java, but it has some far-reaching (and IMHO unfortunate) effects on the design of other type-related aspects of the language.  It would have been cleaner to specify the behaviors of == with regard to particular combinations of operand types, and forbid combinations of types X and Y where x1==y1 and x2==y1 wouldn't imply x1==x2, but languages seldom do that [under that philosophy, double1 == long1 would either have to indicate whether double1 is not an exact representation of long1, or else refuse to compile; int1==Integer1 should be forbidden, but there should be a convenient and efficient non-throwing means of testing whether an object is a boxed integer with particular value (comparison with something that isn't a boxed integer should simply return false)].

With regard to applying the == operator to strings, if Java had forbidden direct comparisons between operands of type String and Object, it could have pretty well avoided surprises in the behavior of ==, but there's no behavior it could implement for such comparisons that wouldn't be astonishing.  Having two string references kept in type Object behave differently from references kept in type String would have been far less astonishing than having either of those behaviors differ from that of a legal mixed-type comparison.  If String1==Object1 is legal, that would imply that the only way for the behaviors of String1==String2 and Object1==Object2 to match String1==Object1 would be for them to match each other.


答:
Some machines (especially microcontrollers) include hardware to accelerate extended-precision (512+ bits) multiplies, and such hardware will inherently help with exponentiation as well (useful for things like RSA ciphers).  Hardware to expedite precise exponentiation (other than by expediting multiplication) is rare because performance with or without such hardware is going to be dominated by the time required to do the constituent multiplications.

If one doesn't need precise results, one may raise floating-point numbers to any desired power by computing the log of the base, multiplying it by the exponent, and raising e to that power; many floating-point units include hardware to expedite all three of those steps.

Title: Why isn't exponentiation hardware-implemented?

Body:
Why is there no exponentiation operation in hardware, even though many languages have builtin operators for it?

Is it because even hardware implementations would need to use the same algorithm as software (i.e. no hardware implementation could be significantly more efficient), or because it is rarely used, or another reason?


问:
Purpose of NOP instruction and align statement in x86 assembly
It has been a year or so since I last took an assembly class. In that class, we were using MASM with the Irvine libraries to make it easier to program in.

After we'd gone through most of the instructions, he said that the NOP instruction essentially did nothing and not to worry about using it. Anyway, it was about midterm and he has some example code that wouldn't run properly, so he told us to add a NOP instruction and it worked fine. I asked I'm after class why and what it actually did, and he said he didn't know.

Anybody know?

答:
There is a x86 specific case still not described in other answers: interrupt handling. For some styles of it, there can be code sections when interrupts are disabled because the main code works with some data shared with interrupt handlers, but it's reasonable to allow interrupts between such sections. If one naively writes

```<code>
    STI
    CLI
</code>```

this won't process pending interrupts because, citing Intel:

After the IF flag is set, the processor begins responding to external, maskable interrupts after the next instruction is executed.

so this shall be rewritten at least as:

```<code>
    STI
    NOP
    CLI
</code>```

In the second variant, all pending interrupts will be processed just between NOP and CLI. (Of course, there can be many alternative variants, as doubling the STI instruction. But explicit NOP is more obvious, at least for me.)

Body:
There is a x86 specific case still not described in other answers: interrupt handling. For some styles of it, there can be code sections when interrupts are disabled because the main code works with some data shared with interrupt handlers, but it's reasonable to allow interrupts between such sections. If one naively writes

    STI
    CLI

this won't process pending interrupts because, citing Intel:

After the IF flag is set, the processor begins responding to external, maskable interrupts after the next instruction is executed.

so this shall be rewritten at least as:

    STI
    NOP
    CLI

In the second variant, all pending interrupts will be processed just between NOP and CLI. (Of course, there can be many alternative variants, as doubling the STI instruction. But explicit NOP is more obvious, at least for me.)


问:
Why do most programming languages only support returning a single value from a function?
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?

答:
As suggested in this answer, it is a matter of hardware support, though tradition in language design also plays a role.

when a function returns it leaves a pointer to the returning object in a specific register

Of the three first languages, Fortran, Lisp and COBOL, the first used a single return value as it was modeled on mathematics. The second returned an arbitrary number of parameters the same way it received them: as a list (it could also be argued that it only passed and returned a single parameter: the address of the list). The third return zero or one value.

These first languages influenced a lot on the design of the languages that followed them, though the only one which returned multiple values, Lisp, never gathered much popularity.

When C came, while influenced by the languages before it, it gave a great focus on efficient use of hardware resource, keeping a close association between what the C language did and the machine code that implemented it. Some of its oldest features, such as "auto" vs "register" variables, are a result of that design philosophy.

It must be also pointed out that assembly language was widely popular until the 80s, when it finally started to be phased out of mainstream development. People who wrote compilers and created languages were familiar with assembly, and, for the most part, kept to what worked best there.

Most of the languages that diverged from this norm never found much popularity, and, therefore, never played a strong role influencing the decisions of language designers (who, of course, were inspired by what they knew).

So let's go examine assembly language. Let's look first at the 6502, a 1975 microprocessor that was famously used by the Apple II and VIC-20 microcomputers. It was very weak compared to what was used in the mainframe and minicomputers of the time, though powerful compared to the first computers of 20, 30 years before, at the dawn of programming languages.

If you look at the technical description, it has 5 registers plus a few one-bit flags. The only "full" register was the Program Counter (PC) -- that register points to the next instruction to be executed. The other registers where the accumulator (A), two "index" registers (X and Y), and a stack pointer (SP).

Calling a subroutine puts the PC in the memory pointed to by the SP, and then decrements the SP. Returning from a subroutine works in reverse. One can push and pull other values on the stack, but it is difficult to refer to memory relative to the SP, so writing re-entrant subroutines was difficult. This thing we take for granted, calling a subroutine at any time we feel like, was not so common on this architecture. Often, a separate "stack" would be created so that parameters and subroutine return address would be kept separate.

If you look at the processor that inspired the 6502, the 6800, it had an additional register, the Index Register (IX), as wide as the the SP, which could receive the value from the SP.

On the machine, calling a re-entrant subroutine consisted of pushing the parameters on the stack, pushing PC, changing PC to the new address, and then the subroutine would push its local variables on the stack. Because the number of local variables and parameters is known, addressing them can be done relative to the stack. For example, a function receiving two parameters and having two local variables would look like this:

```<code>SP + 8: param 2
SP + 6: param 1
SP + 4: return address
SP + 2: local 2
SP + 0: local 1
</code>```

It can be called any number of times because all the temporary space is on the stack.

The 8080, used on TRS-80 and a host of CP/M-based microcomputers could do something similar to the 6800, by pushing SP on the stack and then popping it on its indirect register, HL.

This is a very common way of implementing things, and it got even more support on more modern processors, with the Base Pointer that makes dumping all local variables before returning easy.

The problem, the, is how do you return anything? Processor registers weren't very numerous early on, and one often needed to use some of them even to find out which piece of memory to address. Returning things on the stack would be complicated: you'd have to pop everything, save the PC, push the returning parameters (which would be stored where meanwhile?), then push the PC again and return.

So what was usually done was reserving one register for the return value. The calling code knew the return value would be in a particular register, that would have to be preserved until it could be saved or used.

Let's look at a language that does allow multiple return values: Forth. What Forth does is keeping a separate return stack (RP) and data stack (SP), so that all a function had to do was pop all its parameters and leave the return values on the stack. Since the return stack was separate, it did not get in the way.

As someone who learned assembly language and Forth in the first six month of experience with computers, multiple return values look entirely normal to me. Operators such as Forth's /mod, which return the integer division and the rest, seem obvious. On the other hand, I can easily see how someone whose early experience was C mind find that concept strange: it goes against their ingrained expectations of what a "function" is.

As for math... well, I was programming computers way before I ever got to functions in mathematics classes. There is a whole section of CS and programming languages which is influenced by mathematics, but, then again, there's a whole section which is not.

So we have a confluence of factors where math influenced early language design, where hardware constraints dictated what was easily implemented, and where the popular languages influenced how the hardware evolved (the Lisp machine and Forth machine processors were roadkills in this process).

Body:
As suggested in this answer, it is a matter of hardware support, though tradition in language design also plays a role.

when a function returns it leaves a pointer to the returning object in a specific register

Of the three first languages, Fortran, Lisp and COBOL, the first used a single return value as it was modeled on mathematics. The second returned an arbitrary number of parameters the same way it received them: as a list (it could also be argued that it only passed and returned a single parameter: the address of the list). The third return zero or one value.

These first languages influenced a lot on the design of the languages that followed them, though the only one which returned multiple values, Lisp, never gathered much popularity.

When C came, while influenced by the languages before it, it gave a great focus on efficient use of hardware resource, keeping a close association between what the C language did and the machine code that implemented it. Some of its oldest features, such as "auto" vs "register" variables, are a result of that design philosophy.

It must be also pointed out that assembly language was widely popular until the 80s, when it finally started to be phased out of mainstream development. People who wrote compilers and created languages were familiar with assembly, and, for the most part, kept to what worked best there.

Most of the languages that diverged from this norm never found much popularity, and, therefore, never played a strong role influencing the decisions of language designers (who, of course, were inspired by what they knew).

So let's go examine assembly language. Let's look first at the 6502, a 1975 microprocessor that was famously used by the Apple II and VIC-20 microcomputers. It was very weak compared to what was used in the mainframe and minicomputers of the time, though powerful compared to the first computers of 20, 30 years before, at the dawn of programming languages.

If you look at the technical description, it has 5 registers plus a few one-bit flags. The only "full" register was the Program Counter (PC) -- that register points to the next instruction to be executed. The other registers where the accumulator (A), two "index" registers (X and Y), and a stack pointer (SP).

Calling a subroutine puts the PC in the memory pointed to by the SP, and then decrements the SP. Returning from a subroutine works in reverse. One can push and pull other values on the stack, but it is difficult to refer to memory relative to the SP, so writing re-entrant subroutines was difficult. This thing we take for granted, calling a subroutine at any time we feel like, was not so common on this architecture. Often, a separate "stack" would be created so that parameters and subroutine return address would be kept separate.

If you look at the processor that inspired the 6502, the 6800, it had an additional register, the Index Register (IX), as wide as the the SP, which could receive the value from the SP.

On the machine, calling a re-entrant subroutine consisted of pushing the parameters on the stack, pushing PC, changing PC to the new address, and then the subroutine would push its local variables on the stack. Because the number of local variables and parameters is known, addressing them can be done relative to the stack. For example, a function receiving two parameters and having two local variables would look like this:

SP + 8: param 2
SP + 6: param 1
SP + 4: return address
SP + 2: local 2
SP + 0: local 1

It can be called any number of times because all the temporary space is on the stack.

The 8080, used on TRS-80 and a host of CP/M-based microcomputers could do something similar to the 6800, by pushing SP on the stack and then popping it on its indirect register, HL.

This is a very common way of implementing things, and it got even more support on more modern processors, with the Base Pointer that makes dumping all local variables before returning easy.

The problem, the, is how do you return anything? Processor registers weren't very numerous early on, and one often needed to use some of them even to find out which piece of memory to address. Returning things on the stack would be complicated: you'd have to pop everything, save the PC, push the returning parameters (which would be stored where meanwhile?), then push the PC again and return.

So what was usually done was reserving one register for the return value. The calling code knew the return value would be in a particular register, that would have to be preserved until it could be saved or used.

Let's look at a language that does allow multiple return values: Forth. What Forth does is keeping a separate return stack (RP) and data stack (SP), so that all a function had to do was pop all its parameters and leave the return values on the stack. Since the return stack was separate, it did not get in the way.

As someone who learned assembly language and Forth in the first six month of experience with computers, multiple return values look entirely normal to me. Operators such as Forth's /mod, which return the integer division and the rest, seem obvious. On the other hand, I can easily see how someone whose early experience was C mind find that concept strange: it goes against their ingrained expectations of what a "function" is.

As for math... well, I was programming computers way before I ever got to functions in mathematics classes. There is a whole section of CS and programming languages which is influenced by mathematics, but, then again, there's a whole section which is not.

So we have a confluence of factors where math influenced early language design, where hardware constraints dictated what was easily implemented, and where the popular languages influenced how the hardware evolved (the Lisp machine and Forth machine processors were roadkills in this process).


问:
What is the difference between 'code readability' and 'language conventions' used within a community?
When I'm looking at questions asked on sites like stackoverflow on how to make a particular piece of code "more pythonic" there are usually suggestions offered to use complex list comprehensions or generators or other python features that aren't available in, say, Java.

I am a casual Python programmer, and sometimes I can't follow what's going on without carefully unwrapping the logic in my head. Sometimes the list comprehensions are nested in ways that I'm thinking "you probably should just write it out using loops".

Of course, veteran Python users probably won't have an issue with this, but I'm increasingly getting the impression that "pythonic code" is preferred over writing code that would be readable for the "average programmer" that may not be very proficient in Python.

In general, what are some guidelines and heuristics to follow when choosing between the readability of the code and following the conventions used in a specific programming language community?

答:
If you can't read it, you can't debug it or maintain it. </p>

<p>'more Pythonic' code that you can't maintain is worthless, so for you, using the more complex features is a bad idea, no matter how elegant the answer is in terms of the language.</p>

Body:
If you can't read it, you can't debug it or maintain it.

'more Pythonic' code that you can't maintain is worthless, so for you, using the more complex features is a bad idea, no matter how elegant the answer is in terms of the language.


问:
Are projects using frameworks not as good as projects using pure programming?
I've been a Rails developer for a year now (originally self taught), and am at the point where I want to improve. I've been reading books on how to improve the quality of my Ruby code (I read Design Patterns and Practical Object Oriented Design in Ruby).

I'm trying to improve the quality of my code and to add to my portfolio, but I'm having trouble thinking of anything motivating to do with just Ruby since in my head it feels cooler or more usable to have a Sinatra app (I'm thinking about learning Sinatra) and a browser to interact with the app than having to run a pure ruby app through the console with $ ruby my_app.rb and have it spit out some info. I know the results are really similar, but still.

My question is, do employers think lesser of projects that use frameworks than projects (Rails, Sinatra, etc) that are built from complete scratch (just the programming language itself)?

答:
TL;DR: No

There's really two things going on here when employers look at a resume, or at least some employers.

Do you have a basic understanding of the underlying technologies? Buzzword match up - Ruby, HTML, CSS, JavaScript, PostgreSQL, MongoDB, or whatever the platforms they are using. Knowing the platforms often makes you acceptable candidate.

Do you know and understand the frameworks that we specifically use here? Rails, SASS, Mongoid, ActiveRecord, or whatever else that makes sense for that organization. Knowing these makes you a better candidate.

If you have the list of #1 covered, and you're missing one or two from #2. Normally not a big deal. You can be taught one or two frameworks. It's more important that someone is a good cultural fit and aligns correctly to our organizational values than you have every framework on the list.

Given the above, the importance of most frameworks sorta depends on what you are trying to do. If you are targeting a specific type of job or a role in a specific organization - finding out what frameworks are used and make yourself familiar with them is a huge plus. But at the end of the day, you'll want to use some frameworks. There's no value in reinventing everything you need every time.

Now, I have in the past hired someone who didn't really come close to covering nearly all of #1 but they came across as really bright and we all knew it was going to be a junior position. That turned out to be a pretty good hire. Normally, if someone can't at least speak to most of #1, then the conversation is over pretty quickly. Even if you can't speak to my list in #2, having a list you can speak about how you've used it, the benefits and failings you have discovered and why you might choose to use it again would be a huge benefit in most interviews.


答:
Yes and no.

If all you've done is wire up crud apps using some framework specifically to do that, employers will question if that's all you can do - especially if it's an older technology.

Likewise, if you spent the past 2 years doing something that would've taken a week if you'd just used Framework X, that doesn't reflect well on you either.

Employers value people who get stuff done, ideology and technology be damned.

Title: Are projects using frameworks not as good as projects using pure programming?

Body:
I've been a Rails developer for a year now (originally self taught), and am at the point where I want to improve. I've been reading books on how to improve the quality of my Ruby code (I read Design Patterns and Practical Object Oriented Design in Ruby).

I'm trying to improve the quality of my code and to add to my portfolio, but I'm having trouble thinking of anything motivating to do with just Ruby since in my head it feels cooler or more usable to have a Sinatra app (I'm thinking about learning Sinatra) and a browser to interact with the app than having to run a pure ruby app through the console with $ ruby my_app.rb and have it spit out some info. I know the results are really similar, but still.

My question is, do employers think lesser of projects that use frameworks than projects (Rails, Sinatra, etc) that are built from complete scratch (just the programming language itself)?


答:
There are two questions here. The first question, the subject line, has to do with quality of the code. The second and last question is about employers and what they look for in a candidate.

I think @Travis answers the second question adequately. Employers are certainly looking for a lot of things, including proficiency with the technologies and tools in the business space, but they're also looking for a "fit" within the company. And perhaps even more than that, what they're really looking for is problem solvers. If you lack in a certain language, technology, or framework, but you can show an employer that you have an ability to learn quickly and solve problems, then that's valuable to an employer.

I think employers understand that they're not usually going to get candidates that have every single bullet point on their wish list; but what you're hoping you get is fast learners who are capable and adaptable and can be brought up to speed quickly.

Now, as to the idea of an app being good or bad based on framework usage: here's the bottom line on that one: It depends. Some frameworks are good, and some are bad, and it's only through using them that you will realize how good or bad they are and what barriers they bring or eliminate to a software development project. By the same token, some apps built without frameworks are a mess of spaghetti, but some projects will be just fine. It depends on the people who worked on them.

The larger question, the more concerning question to me, is: Is the app something I can manage and grow and change over time, easily, and with little friction? If the answer to that question is yes, then I don't really care if it used a framework or not.

In my experience, it depends greatly on the language, but some frameworks do a really good job of making apps extensible, easily manageable, and easily changeable as the app grows and evolves. Little friction is experienced when changes need to be made, and in those apps they are a true joy to work on as the age and evolve.

Other apps... you feel as if every line of code that needs to be changed is a major hassle, and with each and every moment you spend in the code you wish for a chance to rewrite it from the ground up.

The trick is to write lots of code, learn, work with other programmers, talk, experience, and gather up a library of thoughts and lessons learned. Aim to make code that is friction-free and is easy for anyone who comes after you to adapt and change. To me, these are the noble goals of our profession.


问:
Why do some compilers generate direct machine code?
I was taking this course - CMU 18-447, Computer Architecture at Carnegie Mellon to brush my knowledge and concepts.

They say that most of the machine level details and implementations are taken care of at the Instruction Set Architecture(ISA) level and is abstracted at that level.

Some Intel processors even have hardware level translation layers that take the front level ISA that is exposed to the programmer and translate them further closer to the machine.

Given such power is provided by the ISA/Processor itself, why do compilers generate direct machine code, or is it just a black box and internally it uses assemblers to convert them into direct machine code?

I hear that JVM takes byte code and translate them directly to machine code(exe).Is this true or is my understanding wrong here?

答:
Compilers may output assembly code, linkable object code, or ready-to-run machine code; I've worked with examples of all three types.  Although compilers which output assembly code may be more adaptable to different platforms than those which output object code, outputting assembly code is often slower than outputting machine code, and running a program will require the assembly code undergo further processing steps.  It really isn't much harder for a compiler to generate machine code than to generate assembly code; in some cases it may be easier.

As for whether to generate linkable or ready-to-run code, it's often faster and easier for a compiler to produce the latter; the only advantage of producing the former is that building a program will require recompiling only the parts that have changed, and then linking everything, versus having to feed everything through the compiler.  If projects will generally be large, and the portion that changes on any given build small, then being able to selectively compile the parts of the code that have changed may be a 'win'.  If, however, one is apt to want to rebuild most of the program on each build, producing runnable machine code may be faster than going through an intermediate link stage.

An additional benefit of producing runnable machine code is that a compiler may be able to take advantage of things it knows about the locations of objects in ways that would not be possible when generating relocatable code.  For example, if foo and bar are declared in separate modules, a statement foo=bar; would require something like:

```<code>    ldr r0,[pc+(_addr_of_bar-*)]
    ldr r1,[pc+(_addr_of_foo-*)]
    ldr r2,[r0]
    str r2,[r1]
 ...somewhere within 2K of the above:
 _addr_of_bar: dw _bar
 _addr_of_foo: dw _foo
</code>```

If variables foo and bar happen to be at known addresses which are within 4K of each other [e.g. 1600 bytes apart], the code could be simplified to something like:

```<code>    ldr r0,[pc+(_addr_of_foo_bar-*)]
    ldr r1,[r0+600]
    str r1,[r0-1000]
 ...somewhere within 2K of the above:
 _addr_of_foo_bar: dw _foo+1000
</code>```

Such optimizations are only possible if the compiler knows how things are going to be placed.

Body:
Compilers may output assembly code, linkable object code, or ready-to-run machine code; I've worked with examples of all three types.  Although compilers which output assembly code may be more adaptable to different platforms than those which output object code, outputting assembly code is often slower than outputting machine code, and running a program will require the assembly code undergo further processing steps.  It really isn't much harder for a compiler to generate machine code than to generate assembly code; in some cases it may be easier.

As for whether to generate linkable or ready-to-run code, it's often faster and easier for a compiler to produce the latter; the only advantage of producing the former is that building a program will require recompiling only the parts that have changed, and then linking everything, versus having to feed everything through the compiler.  If projects will generally be large, and the portion that changes on any given build small, then being able to selectively compile the parts of the code that have changed may be a 'win'.  If, however, one is apt to want to rebuild most of the program on each build, producing runnable machine code may be faster than going through an intermediate link stage.

An additional benefit of producing runnable machine code is that a compiler may be able to take advantage of things it knows about the locations of objects in ways that would not be possible when generating relocatable code.  For example, if foo and bar are declared in separate modules, a statement foo=bar; would require something like:

    ldr r0,[pc+(_addr_of_bar-*)]
    ldr r1,[pc+(_addr_of_foo-*)]
    ldr r2,[r0]
    str r2,[r1]
 ...somewhere within 2K of the above:
 _addr_of_bar: dw _bar
 _addr_of_foo: dw _foo

If variables foo and bar happen to be at known addresses which are within 4K of each other [e.g. 1600 bytes apart], the code could be simplified to something like:

    ldr r0,[pc+(_addr_of_foo_bar-*)]
    ldr r1,[r0+600]
    str r1,[r0-1000]
 ...somewhere within 2K of the above:
 _addr_of_foo_bar: dw _foo+1000

Such optimizations are only possible if the compiler knows how things are going to be placed.


问:
Algorithm that determines relevant attributes in ordered list
Suppose I have a list of objects sorted by a person based on that person's subjective taste. Let's assume that this person is being somewhat consistent in their sorting and that there are quantifiable attributes of these objects that I can identify. For example, a person might sort cheese based on how much they enjoy the taste, and people who disliked salt would rank salty cheese lower than cheeses that were low salt. One person might not care what the color of the cheese was or whether it came from cows, goats, or sheep, while another might rank sheep's milk cheeses higher than goat's milk cheeses.

I assume there is a procedure to identify what attributes of data elements in a list are and aren't relevant to the determining the order. What is the name for this problem, and what algorithms exist for solving it?  (ideally in Python)

答:
Since the sort isn’t necessarily perfect, the first thing that comes to mind is regression analysis.

For each property, you want to determine the strength of a correlation between the indices of the items (the response variable) and the values of that property. I think you can then assume that—or ask the user if—the sorted property is the one you found to have the strongest correlation.

If multiple properties might be considered in the sort, as they very well could be, you need to use multivariate regression. I guess you would consider the 2n possible subsets of all the properties, if n is small, or else only the size-k subsets.


问:
How discrete should a RESTful API be?
I've never built a RESTful API before and I am wondering how discrete should it be?

For example lets say I have a customer which has a name, address, phone number, email address, language, etc.

Does it make sense that there is a way to update each individual field (update address, update email address, etc), or should there just be a single update for the entire customer and each field is optional?

答:
You have one update action for a resource. As a rough rule of thumb a table in your database will be a resource. So in your example there is one controller for the Customer with one update action and fields are optional as far as possible.

There can be exceptions to this (for example if you update the password you expect password & password_confirmation), but this holds true for most cases.

It is more likely that the exceptions are controllers that have limited actions for some resources, like a SessionsController that can only be created and destroyed. It is very unlikely that you would want to have actions for single fields.

In your example one thing could be handled as a resource of its own and that is the address. If you would have a table for addresses, especially if there would be more than one address per customer (billing, delivery...) this could be handled as a nested resource. But again one update action for the whole address resource.

Title: How discrete should a RESTful API be?


问:
Which is better to use? (Enum or Constant)
I have my enum like this.

```<code>enum Size{PAGE_SIZE=20,
          HEADER_SIZE=30
};
</code>```

I only use them as constants(No enum variable created) in my program.

i.e= int x = PAGE_SIZE + 20;

So what is the better way to declare the constants in this scenario? (enum or const)

答:
Perhaps due to my background in other languages where the typing of enum is more strict (*), I tend to think that if you want a type able to contain a set of constants, use an enum, if you want a bunch of constants, use a bunch of constants and don't introduce a type where there is no need of one.

There have been considerations which made the choice of an enum better at the time, but the only one I can think which survived the normalization of C++ 98 is compatibility with C and previous implementations of C++ (and some have kept as their style what was a necessity when they established it).

What has survived are the considerations which made the use of an additional type worrisome.  The fact that the constants are of another type which is normally not used can interfere with overload resolution and type deduction in templates.  Rules are such that it does usually what you want -- perhaps at the cost of an additional instantiation for the spurious enum type -- but there are time when it isn't.  For instance

```<code>template <typename T> MyClass<T> make_MyClass(T) {...}
</code>```

return a MyClass<Size> for make_MyClass(PAGE_SIZE) where you probably expect a MyClass<int> if the reason for introducing the enum wasn't to have a type but introduce some constants.

(*) note that such stricter typing of enum was deemed sufficiently desirable that a variation is now provided as enum class since C++11.

Body:
Perhaps due to my background in other languages where the typing of enum is more strict (*), I tend to think that if you want a type able to contain a set of constants, use an enum, if you want a bunch of constants, use a bunch of constants and don't introduce a type where there is no need of one.

There have been considerations which made the choice of an enum better at the time, but the only one I can think which survived the normalization of C++ 98 is compatibility with C and previous implementations of C++ (and some have kept as their style what was a necessity when they established it).

What has survived are the considerations which made the use of an additional type worrisome.  The fact that the constants are of another type which is normally not used can interfere with overload resolution and type deduction in templates.  Rules are such that it does usually what you want -- perhaps at the cost of an additional instantiation for the spurious enum type -- but there are time when it isn't.  For instance

template <typename T> MyClass<T> make_MyClass(T) {...}

return a MyClass<Size> for make_MyClass(PAGE_SIZE) where you probably expect a MyClass<int> if the reason for introducing the enum wasn't to have a type but introduce some constants.

(*) note that such stricter typing of enum was deemed sufficiently desirable that a variation is now provided as enum class since C++11.


问:
Model-View-Controller -- Where does a factory class go?
I'm working (slowly) on a small Flask project. One of my models is a class called Post, which is a lightweight namedtuple. Post objects are created by a PostFactory, because creating a Post involves hitting a database. The PostFactory holds the necessary database connection, so the Post objects can be serialized.

What part of the model/view/controller division does a factory object naturally fit in? Is it part of the models, since it's tightly coupled with Post objects? Or is it a controller, since it manipulates models?

答:
It's probably a proper part of a repository, which goes in your model.

Any machinery that helps you look up domain objects is part of the model.  The controller will most likely call a method in your repository, which in turn calls the factory to get the Post object.  Or, you can expose the factory method from your repository, and allow the controller to call it directly.

Always favor fatter models, and thinner controllers.


问:
Which way to terminate reading loop is the preferred approach?
When you have to iterate a reader where the number of items to read is unknown, and the only way to do is it to keep reading until you hit the end.

This is often the place you need an endless loop.

There is the always true that indicates there must be a break or return statement somewhere inside the block.

```<code>int offset = 0;
while(true)
{
    Record r = Read(offset);
    if(r == null)
    {
        break;
    }
    // do work
    offset++;
}
</code>```

There is the double read for loop method.

```<code>Record r = Read(0);
for(int offset = 0; r != null; offset++)
{
    r = Read(offset);
    if(r != null)
    {
        // do work
    }
}
</code>```

There is the single read while loop. Not all languages support this method.

```<code>int offset = 0;
Record r = null;
while((r = Read(++offset)) != null)
{
    // do work
}
</code>```

I'm wondering which approach is the least likely to introduce a bug, most readable and commonly used.

Every time I have to write one of these I think "there has to be a better way".

答:
You don't need an endless loop.  You should never need one in C# read scenarios.   This is my preferred approach, assuming that you really do need to maintain an offset:

```<code>Record r = Read(0);
offset=1;
while(r != null)
{
    // Do work
    r = Read(offset);
    offset++
}
</code>```

This approach acknowledges the fact that there is a setup step for the reader, so there are two read method calls.  The while condition is at the top of the loop, just in case there is no data at all in the reader.

Body:
You don't need an endless loop.  You should never need one in C# read scenarios.   This is my preferred approach, assuming that you really do need to maintain an offset:

Record r = Read(0);
offset=1;
while(r != null)
{
    // Do work
    r = Read(offset);
    offset++
}

This approach acknowledges the fact that there is a setup step for the reader, so there are two read method calls.  The while condition is at the top of the loop, just in case there is no data at all in the reader.


答: The name MVC is highly semantic. Model is your data, View is your UI/Interface, and Controller being the operations you perform on the data. In your example, your assumption is correct in that it would be considered part of the controller as it is manipulating the data.</p>

Title: Model-View-Controller -- Where does a factory class go?

Body:
I'm working (slowly) on a small Flask project. One of my models is a class called Post, which is a lightweight namedtuple. Post objects are created by a PostFactory, because creating a Post involves hitting a database. The PostFactory holds the necessary database connection, so the Post objects can be serialized.

What part of the model/view/controller division does a factory object naturally fit in? Is it part of the models, since it's tightly coupled with Post objects? Or is it a controller, since it manipulates models?


问:
What is a good use case for native XML databases?
What would be a good use case to use a native XML database such as Apache Xindice and eXist-db? I have used XML features of SQL Server in the past and they were of great value, but there it is possible to use XML for 5% and traditonal storage for 95% of the application. Which application types would benefit from a 100% XML storage?</p>

答:
The only use case that comes to mind is a small blog, but I've seen more than one of those
converted to a database when they found out that using XML for storage doesn't scale.

XML is often confused with databases by those unfamiliar with it.  XML is designed to be a data exchange format, not a storage medium.

That said, apache Xindice states the case for an XML database fairly eloquently.  They say:

The benefit of a native solution is that you don't have to worry about
  mapping your XML to some other data structure. You just insert the
  data as XML and retrieve it as XML. You also gain a lot of flexibility
  through the semi-structured nature of XML and the schema independent
  model used by Xindice. This is especially valuable when you have very
  complex XML structures that would be difficult or impossible to map to
  a more structured database.


答:
The application characteristics that make an XML format attractive (vs. RDBMS) for storage are:

Processing of individual "root" items in isolation (as opposed to processing groups of individuals in a batch)

A small number of individuals ("n=1"), or significant variability across individuals in respect to the presence or number of optional attributes (possibly extending to wide use of custom attributes).

Highly restricted "ownership" of data, such that competition for locks to update individuals does not occur.

By "individual" here I do not mean (only) people, but whatever entity is central to the business logic of the application.  E.g. an "individual" might be residential properties in a real estate sales application, or a calendar date in a day-planner application.

Title: What is a good use case for native XML databases?

Body: What would be a good use case to use a native XML database such as Apache Xindice and eXist-db? I have used XML features of SQL Server in the past and they were of great value, but there it is possible to use XML for 5% and traditonal storage for 95% of the application. Which application types would benefit from a 100% XML storage?</p>


问:
Is there any particular reason for the use of lists over queues in functional programming languages?
Most functional programming languages such as Scheme and Haskell use lists as their main data structure. Queues are identical to lists, except for the fact appending to the end - not to the begin - has constant time. Every algorithm that is written elegantly using lists with head and tail can be written elegantly using queues with init and last.

Considering appending to the end is more common than the opposite, I'd guess queues are more natural than lists. Is there any reason lists have always been preferred?

答:
Queues don't functionally compose, and are difficult to implement in a well-performing way without making them mutable.

The very nature of a queue suggests that you put things into it and take things out of it, which is at odds with the immutable nature of functional languages.  Oh, sure, you can do the same thing with lists, but generally what you are really doing is composing a new list, not adding to one, and a list doesn't have the special requirement of forcing you to put items into one end and take them out of the other, like a queue does.

All that said, have a look at Okasaki's paper on Purely Functional Data Structures, which does outline a strategy for creating a queue with adequate performance in a functional way.

ContentLicense: CC BY-SA 4.0


答:
Well it depends on your situation. But one of the more "C#-ish" solutions I can think of is to use the built-in IEnumerable interface and a foreach loop. The interface for IEnumerator only calls out MoveNext with true or false, so size can be unknown. Then your termination logic is written once - in the enumerator - and you don't have to repeat in more than one spot.

MSDN provides an example of IEnumerator< T >. You will also need to create an IEnumerable< T > to return the IEnumerator< T >.

Title: Which way to terminate reading loop is the preferred approach?

Body:
When you have to iterate a reader where the number of items to read is unknown, and the only way to do is it to keep reading until you hit the end.

This is often the place you need an endless loop.

There is the always true that indicates there must be a break or return statement somewhere inside the block.

```<code>int offset = 0;
while(true)
{
    Record r = Read(offset);
    if(r == null)
    {
        break;
    }
    // do work
    offset++;
}
</code>```

There is the double read for loop method.

```<code>Record r = Read(0);
for(int offset = 0; r != null; offset++)
{
    r = Read(offset);
    if(r != null)
    {
        // do work
    }
}
</code>```

There is the single read while loop. Not all languages support this method.

```<code>int offset = 0;
Record r = null;
while((r = Read(++offset)) != null)
{
    // do work
}
</code>```

I'm wondering which approach is the least likely to introduce a bug, most readable and commonly used.

Every time I have to write one of these I think "there has to be a better way".


问:
Why doesn't Java 8 include immutable collections?
The Java team has done a ton of great work removing barriers to functional programming in Java 8.  In particular, the changes to the java.util Collections do a great job of chaining transformations into very fast streamed operations.  Considering how good a job they have done adding first class functions and functional methods on collections, why have they completely failed to provide immutable collections or even immutable collection interfaces?

Without changing any existing code, the Java team could at any time add immutable interfaces that are the same as the mutable ones, minus the setter methods and make the existing interfaces extend from them, like this:

```<code>                  ImmutableIterable
     ____________/       |
    /                    |
Iterable        ImmutableCollection
   |    _______/    /          \   \___________
   |   /           /            \              \
 Collection  ImmutableList  ImmutableSet  ImmutableMap  ...
    \  \  \_________|______________|__________   |
     \  \___________|____________  |          \  |
      \___________  |            \ |           \ |
                  List            Set           Map ...
</code>```

Sure, operations like List.add() and Map.put() currently return a boolean or previous value for the given key to indicate whether the operation succeeded or failed.  Immutable collections would have to treat such methods as factories and return a new collection containing the added element - which is incompatible with the current signature.  But that could be worked-around by using a different method name like ImmutableList.append() or .addAt() and ImmutableMap.putEntry().  The resulting verbosity would be more than outweighed by the benefits of working with immutable collections, and the type system would prevent errors of calling the wrong method.  Over time, the old methods could be deprecated.

Wins of immutable collections:

Simplicity — reasoning about code is simpler when the underlying data does not change.

Documentation — if a method takes an immutable collection interface, you know it isn't going to modify that collection.  If a method returns an immutable collection, you know you can't modify it.

Concurrency — immutable collections can be shared safely across threads.

As someone who has tasted languages which assume immutability, it is very hard to go back to the Wild West of rampant mutation.  Clojure's collections (sequence abstraction) already have everything that Java 8 collections provide, plus immutability (though maybe using extra memory and time due to synchronized linked-lists instead of streams).  Scala has both mutable and immutable collections with a full set of operations, and though those operations are eager, calling .iterator gives a lazy view (and there are other ways of lazily evaluating them).  I don't see how Java can continue to compete without immutable collections.

Can someone point me to the history or discussion about this? Surely it's public somewhere.

答:
The Java Collections Framework does provide the ability to create a read-only version of a collection by way of six static methods in the java.util.Collections class:

unmodifiableCollection(Collection c)

unmodifiableList(List list)

unmodifiableMap(Map m)

unmodifiableSet(Set s)

unmodifiableSortedMap(SortedMap m)

unmodifiableSortedSet(SortedSet s)

As someone has pointed out in the comments to the original question, the collections returned may not be considered immutable because even though the collections cannot be modified (no members can be added or removed from such a collection), the actual objects referenced by the collection can be modified if their object type allows it.

However, this problem would remain regardless of whether code returns a single object, or an unmodifiable collection of objects. If the type allows its objects to be mutated, then that decision was made in the design of the type and I don't see how a change to the JCF could alter that. If immutability is important, then the members of a collection should be of an immutable type.


答:
Given you have a program or program system which produces output in form of XML documents, and the data in those XML documents does not fit well to, for example, a relational data model, then an XML database may be the best tool for storing the documents and make them queryable.

This is not a hypothetical use case - our team develops a product where such XML documents are produced. Until now we did not use a database, only folders with collections of XML documents, and an increasing number of tools for batch processing the documents on a per-file basis. But I think the more tools we get, the more it will make sense to switch to a database.


问:
Why it is `(cons 1 (cons 2 (cons 3 nil)))` and not `(cons 3 (cons 2 (cons 1 nil)))` for [1,2,3]?
Is there any special reason that to construct list in Scheme you use

```<code>(cons 1 (cons 2 (cons 3 nil)))
</code>```

instead of

```<code>(cons 3 (cons 2 (cons 1 nil)))
</code>```

? While the first seems more obvious because it reads in the right order, the second is the one which actually reduces in the right order. Also, it seems more natural to construct a list starting with nil and adding elements to it, not the opposite. I've also found the latter has properties such as being very curry friendly: (cons 1) nicely becomes a function that appends 1 to a list.

答:
Because appending to the end of a linked list is O(n) and appending to the front is O(1). The operation you're looking for is called snoc and can be implemented. But inefficiently.

To see why, realize that when you append to the back of a list, if you don't mutate anything, every single element must be copied, where as with appending to the front, you can just allocate a cons cell and have it point to the existing list, a relatively cheap operation.


答:
As I mentioned in a comment in your previous question, if you want immutable linked lists, a straightforward implementation using cons cells can only have either a forward (next) pointer or a backward (previous) pointer, not both. In other words, they're singly-linked lists.

That means that if you want to represent (1 2 3) using (cons 3 (cons 2 (cons 1 '()))), your variable would point to the "last" node (containing the 3), and you'd traverse "backwards" to get to the 2, then the 1. Using this system, it would be impossible to access the 2 node from the 1 node, so you cannot easily traverse the list in the (1 2 3) order.

Title: Why it is `(cons 1 (cons 2 (cons 3 nil)))` and not `(cons 3 (cons 2 (cons 1 nil)))` for [1,2,3]?

Body:
Is there any special reason that to construct list in Scheme you use

```<code>(cons 1 (cons 2 (cons 3 nil)))
</code>```

instead of

```<code>(cons 3 (cons 2 (cons 1 nil)))
</code>```

? While the first seems more obvious because it reads in the right order, the second is the one which actually reduces in the right order. Also, it seems more natural to construct a list starting with nil and adding elements to it, not the opposite. I've also found the latter has properties such as being very curry friendly: (cons 1) nicely becomes a function that appends 1 to a list.


问:
Building a distributed system on Amazon Web Services
Would simply using AWS to build an application make this application a distributed system?

For example if someone uses

RDS for the database server,

EC2 for the application itself and

S3 for hosting user uploaded media,

does that make it a distributed system?

If not, then what should it be called and what is this application lacking for it to be distributed?

Update

Here is my take on the application to clarify my approach to building the system:

The application I'm building is a social game for Facebook.

I developed the application locally on a LAMP stack using Symfony2.

For production I used an a single EC2 Micro instance for hosting the app itself, RDS for hosting my database, S3 for the user uploaded files and CloudFront for hosting static content.

I know this may sound like a naive approach, so don't be shy to express your ideas.

答:
The resources are distributed but the logic is not. Both the database and the S3 repository are controlled by the application, and there is no parallelism in the task the application runs between different machines. According to wikipedia there are two requirements for a distributed system, both of which are missing from the system you described (or not clarified):

There are several autonomous computational entities, each of which has its own local memory

The entities communicate with each other by message passing.

In that sense it is not a distributed system, and it would require different EC2 servers running this application to coordinate their actions on how to access and synchronise resources.

Edit: from the question it is not clear if only one EC2 instance is used or many. In my reply above I assume a single instance.

EDIT: updated question from the OP makes clear it's a single EC2 instance.
Academically such applications are considered multi-tiered. The client tier is at the end user's machine, the web tier is the EC2 server and the Enterprise Information System (EIS) tier is the database and the S3 repository. Again, for an application to be distributed you need to distribute the processing of the web tier at multiple servers. However, in the industry such applications can be considered distributed due to the separation of locations. So I would say that the app itself that runs in the EC2 server isn't a distributed system, but the entire setup (client's browser <-> web app <-> database/s3) can be considered as a distributed architecture/application.

Please also check this question:
https://stackoverflow.com/questions/3542204/multi-tier-vs-distibuted


答:
When I have initialization, condition and increment operations I like to use the for loops of languages like C, C++ and C#. Like this:

```<code>for (int offset = 0, Record r = Read(offset); r != null; r = Read(++offset)){
    // loop here!
}
</code>```

Or this if you think this is more readable. I personally prefer the first one.

```<code>for (int offset = 0, Record r = Read(offset); r != null; offset++, r = Read(offset)){
    // loop here!
}
</code>```

Body:
When I have initialization, condition and increment operations I like to use the for loops of languages like C, C++ and C#. Like this:

for (int offset = 0, Record r = Read(offset); r != null; r = Read(++offset)){
    // loop here!
}

Or this if you think this is more readable. I personally prefer the first one.

for (int offset = 0, Record r = Read(offset); r != null; offset++, r = Read(offset)){
    // loop here!
}


问:
Using the system tray / notification area app in Windows 7?
Many dekstop apps have this, such as dropbox (windows version). You right-click the dropbox systray icon and there are shortcuts to the features of the main app.

Right now, I want to keep it simple and just want to run a exe(?) and have a custom icon appear in the system tray notification area. How do I build this?

答:
The System Tray/Notification Area is a feature of Windows Explorer shell, and is exposed as part of the Windows Shell SDK, which can be accessed on MSDN. The Shell SDK exposes a set of C-style functions that can be called from any programming language capable of calling C-style functions. This includes C++, C#/VB.NET (through P/Invoke) and probably most other common languages, though these are the ones I'm familiar with.

Specifically, you'll be wanting to call the Shell_NotifyIcon function. You can either call it directly through the methods I mentioned above, or use one of the common wrappers you'll find in most frameworks. .NET WinForms has the NotifyIcon class which wraps the Shell SDK calls within it. A quick google-search shows that people have built similar wrappers for Python, and Java has a wrapper similar to .NET's, as of Java 6.

Shouldn't be too complicated to implement in the programming language of your choice.


问:
Is there any use for layout managers beyond Java?
I am a beginning programmer and I was recently working on some primitive GUI apps in Java.

That's where I encountered different layout managers. I browsed the web and it says that for advanced GUI creation there are NetBeans and Qt and a lot of other stuff.

My question is:

Do I really need to learn all ins and outs of layout managers and try to program without advanced layout engines to understand how they work or should I start learning NetBeans right away and skipping the whole manual layout complications? Is there any use for manual layouting beyond Java in other languages? In other words, will my road be less bumpy in the future if I go learn it in detail, or should I just forget about doing manual layouts?

答:
Netbeans' GUI builder is nice and other IDEs (Xcode and Visual Studio both come to mind) have similar features.

However, while good productivity enhancers, if you want to learn build GUIs; you should design them by hand for the time being until you understand how they work.


答:
How do you propose the head be reached in this reversed list? If not using mutable structures the reversed list would only be performant if you made the head linear time and tail constant. But now you've got the exact same structure as before except you're calling the head the tail and vice versa.

the structure is the way it is because regardless of which side you declare to be the front or the back, that particular form is the only known one with constant time readahead and constant time insert without mutation or doing amortization trickery.

you're getting hung up on the terms thinking one side could be head or tail but those terms don't matter, the part that counts is the structure.


问:
Does Open Source lead to bad coding?
I have a thought that I tried asking at SO, but didnt seem like the appropriate place. I think that source sites like Google Code, GitHub, SourceForge... have played a major role in the history of programming. However, I found that there is another bad thing to these kind of sites and that is you may just "copy" code from almost anyone, not knowing if it is good(tested) source or not.

This line of thought has taken me to believe that source code websites tend to lead many developers (most likely unexperienced) to copy/paste massive amounts of code, which I find just wrong.

I really dont know how to focus the question well, but basic thought would be:

Is this ok? Is Open Source contributing to that or I'm just seeing ghosts...

Hope people get interested because I think this is an important theme.

答: Open source tends to good coding, since you cannot hide your bad code behind a working application, you need to code well otherwise you are out of game. Understanding and copy/pasting a good code doesn't make the developer worse (do not confuse with copy/pasting instead of doing a proper design). And, as mentioned in another answer, a bad programmer will find another ways to produce bad code if there were no available source codes.</p>

ContentLicense: CC BY-SA 2.5

Title: Does Open Source lead to bad coding?


问:
What's the difference between a function and a method?
I've heard that methods are more Object-Oriented than functions.  I was wondering if someone could show me an example of a function and a method and explain the differences between methods and functions?

I have taken 3 quarters of Java programming and functions have never been mentioned, I want to know the differences, strengths and weaknesses.

答:
There are no functions per se in Java. All you've got is methods. To imitate functions, Java generally uses static methods (as in java.lang.Math).

There is a number of object-oriented languages that provide free-standing functions, though: among them Python, Ruby, JavaScript, C++, Object Pascal, and even (yuck) PHP. There's a good reason behind that.

A method is basically a function with one extra parameter (invisible in Java). You refer to it as this. That this thing allows you to access the object whose method is being called, so you can think that the entire object is always an implicit parameter to a method, additionally to parameters you normally define.

A method makes sense if it makes use of its object: calls other methods and/or accesses data members. For example, a list can have a getLength() method that knows how to calculate list's length, e.g. by scanning each member. It obviously uses the implicit this object, that is, the list. This is why it needs no explicit parameters.

Else, a function is enough. For instance, to compute a cosine of an angle you only need the angle, and no other state, so cos(float angle) could be a function, and only depend on the explicit angle parameter.

Another important thing is method overriding. (To my ming, this is a dubious practice, but Java uses it very widely.) You declare a certain class (call it Z) a subclass of another class (call it A), and change implementation of some of its methods (suppose we overrode method foo()).

The subclass works like the base class (it is said to provide the same interface) but does it by different means. According to Liskov substitution principle, you can declare a variable of type A, assign to it an instance of type Z, and invoke method foo(); what will be invoked is Z's implementation of foo(), not A's. That is, the method to call will be looked up at runtime, based on the actual type of the object. This is know as "dynamic method dispatch" or "virtual methods".

What method overriding provides automatically is not easy to directly emulate with functions. (With functions, similar things are usually done with "callbacks" or "higher-order functions").

In certain languages, such as Java and C#, you can define "static methods" that do not receive a this parameter. They work exactly like "standalone" functions and use the class as a namespace. Such namespacing may sometimes make sense, when a static method of a class is used to look up  or create new instances of that class.

I hope you now have a better picture.


问:
How to avoid binary dependency on size change
```<code>class A { public: int i; }; // A.h and defined in project libA.vcxproj (libA.dll)
</code>```

I'm using class A in multiple places at various projects as below. Apporoximately 100 projects.

```<code>include "A.h"
class UseA { public: A *a; UseA(){ a = new A(); } ~UseA() {delete a;} }
</code>```

My problem is whenever I add a member variable to class A I will have to build all the projects (~100) as the size of the class A has been changed and building 100 project is time consuming.

How to avoid building so many projects on size change of a single class? Also I have many classes like class A defined in libA.vcxproj.

答: Are you familiar with the PIMPL idiom? For certain cases, it can solve this exact problem. The short version is that you wrap all your private member variables into one opaque pointer to a type so that when you add a new private member you don't need as much recompilation...</p>


答:
First make sure you really need this - having a central library which is reused more than 100 times works better when the public interface of that library does not change too often or only at specific points in time. Check if it is possible to split up your library in smaller parts, so that changes in one part don't affect the dependent projects of the other parts. Check also if it is possible to develop any changes to that library first "in private", and publish them (visibly for the majority of dependent projects) only for new "major releases" of that library.

But let's assume your project dependencies are correct and necessary for your system, and you really need to extend the public parts of that central library (or central class "A") very often. Then, you cannot avoid that all dependent projects have to be recompiled. But since you typically don't make changes to all the 100 projects simultaneously, you don't have to recompile them all on your local workstation.

What you need in this situation is a build server - a server which automatically checks out all changes from your SCCS and runs a full build of all the 100 projects in the background. For setting up such a system, you will also need a good structured automatic build process. Hopefully your 100 projects can be split up into groups of projects which can be individually compiled and tested, otherwise you have to solve that problem first.

Also a good read, though a bit outdated: Large Scale C++ Software Design by John Lakos. This book will also explain the PIMPL idiom mentioned by Jtrana in depth, though this will only help you with the private parts of your classes, not with the public ones like in your example.

Title: How to avoid binary dependency on size change

Body:
```<code>class A { public: int i; }; // A.h and defined in project libA.vcxproj (libA.dll)
</code>```

I'm using class A in multiple places at various projects as below. Apporoximately 100 projects.

```<code>include "A.h"
class UseA { public: A *a; UseA(){ a = new A(); } ~UseA() {delete a;} }
</code>```

My problem is whenever I add a member variable to class A I will have to build all the projects (~100) as the size of the class A has been changed and building 100 project is time consuming.

How to avoid building so many projects on size change of a single class? Also I have many classes like class A defined in libA.vcxproj.


问:
what is a good stack for software as a service (SAAS) application?
We will be engaging large corporations to help them run various types of analysis, mostly code analysis of their applications.  The storage requirements will likely be modest, hundreds of MB per client.

My question is mostly aimed at finding the stack with existing frameworks, best practices and a community which will allow a rapid development process.

I am comfortable with the .Net environment and am leaning towards Azure.

Any thoughts?

答:
We've been running a SaaS for enterprise customers on .NET and our own servers. Everybody seems to be happy.

If you communicate the idea of SaaS to the customer properly, they won't care what it's running on and where.


答:
In addition to the answers by Doc Brown and J Trana.

Doc Brown's answer points out that whole-project rebuild is very much necessary in software development; therefore try to reduce the pain by using build automation, instead of avoiding it.

J Trana's answer is a form of encapsulation or information hiding. If most of the users of class A do not need to access the new member, then these steps can be taken:

Make the new member private

Put the new member inside a private sub-member of class A, and initialize it in A's constructor.

Provide accessor methods (getter and setter) for the new member.

Note that this still requires rebuilding the whole project, because in C++ any change in a header file will have required a rebuild.

My suggestion #1 (vendor specific)

Some C++ compilers have options for improving the performance of the build process.

Examples: "incremental build", "build with multiple processes" etc.

My suggestion #2:
If you really must reduce the time spent on rebuilding while you are making many small experimental changes that involves new members, consider converting data members into property bag.

A property bag is a dictionary (std::map) from string to variant values.

If the class A provides get/set methods for this dictionary, then the addition and removal of new keys will not require a rebuild.

However, the drawbacks are:

It will be a lot slower to read from and write to the values in the dictionary, compared to accessing a class member.

The whole project will be more prone to errors, because the compiler will not be able to perform name checks and type checks on the keys and values stored in a property bag.

Example:
A compiler can catch the bug where one tries to access a class member that does not exist.
 A compiler does not automatically catch the bug where one accesses a dictionary key that does not exist. The programmer must write code to handle this situation.


问:
If I fork an open source project and make improvements in the fork, will it or I offend the original authors?
I have identified a couple of open source projects on github.com that are not being kept up to date for many months. I have used them for personal use, and now want to make enhancements to them and start maintaining the code base and write sample clients that use these projects. I've sent pull requests to the authors and also followed up with emails via their personal / technical website contact page, with no responses from either 1 of them.

I know that I can fork a project on github and be on my way. What I would like to know is

If I Fork an open source project and make improvements in the fork, will it or I offend the original authors? Meaning, could the original authors get upset down the line if my version of the project becomes popular and their version (the ones they are not maintaining or accepting pull requests actively) wanes in usage and popularity. A similar situation would be how Wordpress was forked from B2 and I think initially Mat Mullenweg and original B2 author had some difference of opinion / annoyances.

Are there any licensing issues and copyright issues that I should be aware of? At present, the license.MD for both Projects says Apache License Version 2.0, January 2004 http://www.apache.org/licenses/

答:
License wise, unless you are making really major changes and have a really strong opinion on the license that you want to distribute those under, you should keep to the original license of the project you fork from. The code you copied must remain under that license anyway, so using a separate license for your changes is mostly a lot of additional hassle.

As for the possibility of the original maintainers becoming offended, unless you are making changes that could easily be seen as morally wrong, you should not worry about it. If they become offended, it is likely to have one of two causes, none of which you can do anything about: 1. They regret they made a wrong choice in not working with you, or 2. You took the project in a direction that went against one of their principles.

Legally, you have the right to fork the projects, so the original maintainers can't do anything about that. At most, they can make you change the name under which you provide your version.