问:
Java developing server-client solutions
I am trying to get a job as Java developer.

I have been developing web pages with Java for a while, but now trying to go to another path and develop server-client solutions.

In this specific company they are using these technologies for web developing: Spring, Hibernate, Ant, Velocity etc. All of the hot techs for Java.

Now before applying for job as server-client developer, which technologies should I get familiar with. Which would be adequate technologies?

答:
Quote from Wikipedia:

Middleware makes it easier for software developers to perform communication and input/output, so they can focus on the specific purpose of their application.

And this is exactly where Spring Framework comes handy.

It provides a lot of pre-built ( out-of-the-box or whatever you call it ) APIs and well working default Implementations to handle all kinds of operations so a developer could focus on the business logic rather than the frameworks.

Its hard to tell in details before you tell what exactly you're talking about, but I'll try to cover a few.

Spring MVC - provides a good front-to-back-end data model mapping to UI and back to services, invoking actions & etc.

Spring Web Flow gives you a flow transition describing framework and binding flow actions to UI. Also a "scope" to where you can create your backing beans and Spring will take care of destroying them.

Spring Persistence gives an easy way to get access to database connection and transactions over JPA so you don't have to worry of creating connections and start transaction, commit and rollback operations.

And so far and so on as there are many sub-projects under Spring framework every one does it's job well.

Hope this helps :)

Title: Java developing server-client solutions


问:
Spring - Confusion over configuration?
Somewhere I read Spring offers convenience over configuration. But Spring folks are bringing in so much changes over the configuration , that I am now really getting confused to use the xml configuration or the annotation.

I would like anyone to suggest a surefire methodology or rule of thumb in using xml and annotations.

Examples at SO to show that many beginners like me are getting confused over the configuration.

link-1

I don't seem to grasp the functionality behind <context:annotation-config> and <context:component-scan>.

From what I've read they seem to handle different annotations (@Required, @Autowired etc vs @Component, @Repository, @Service etc) but also from what I've read they register the same bean post processor classes.

To confuse me even more, there is an annotation-config attribute on <context:component-scan>...

link 2

I still have  the component scan tag:

```<code><context:component-scan base-package="com.mycompany.maventestwebapp" />
</code>```

but I have also another tag (that look like have similar task), this one:

```<code><annotation-driven />
</code>```

What is the difference between these two tags?
  An other "strange" thing is that the previous example (that don't use the annotation-driven tag) is very similar to the project create by STS using the Spring MVC Template project but if I delete the annotation-driven tag from its configuration file the project don't run and give me the following error: HTTP Status 404 -...

Spring 3.2 no longer need cglib for proxying , but lower versions uses cglib. A quote from the springsource blog

In order to generate such proxies, Spring uses a third party library
  called cglib. Unfortunately, this project is not active anymore. In
  Spring 3.2, it is very likely that Spring will be using Javassist
  instead by default.

Are these enough to suggest that Spring is Confusion over configuration ?

答:
```<code><annotation-driven />
</code>```

You have to specify XML schema where this comes from.

Most likely its in the context of JPA Transaction handling strategy when defining the Transaction Manager ( see 9.5.6. Using @Transactional in Spring's docs )

When you define annotation-driven transaction handling - Spring AOP automagically creates aspects for your method to start ( or check for existing ) transaction before the invokation of a method and then commit ( or rollback in case of exception ) after the method ivokation has ended.

ContentLicense: CC BY-SA 3.0

Title: Spring - Confusion over configuration?

Body:
<annotation-driven />

You have to specify XML schema where this comes from.

Most likely its in the context of JPA Transaction handling strategy when defining the Transaction Manager ( see 9.5.6. Using @Transactional in Spring's docs )

When you define annotation-driven transaction handling - Spring AOP automagically creates aspects for your method to start ( or check for existing ) transaction before the invokation of a method and then commit ( or rollback in case of exception ) after the method ivokation has ended.


答:
Spring is what you should really concentrate on.

Hibernate is pretty straightforward if you are already familiar with databases and SQL. Ant scripts are usually set up early and the project and not touched until deployment, Velocity you may use occasionally.

But Spring is what you will be using all day every day as a developer. Its a pretty massive collection of frameworks and utility classes. Start by getting to grips with Spring MVC.

Title: Java developing server-client solutions

Body:
I am trying to get a job as Java developer.

I have been developing web pages with Java for a while, but now trying to go to another path and develop server-client solutions.

In this specific company they are using these technologies for web developing: Spring, Hibernate, Ant, Velocity etc. All of the hot techs for Java.

Now before applying for job as server-client developer, which technologies should I get familiar with. Which would be adequate technologies?


问:
Execute a Managed bean from a JSF view in WEB-INF folder
We are initiating a Spring + Primefaces project and the first problem we have encountered concerns storing the XHTML pages into the WEB-INF folder.

When we use a faces form in a view located inside the WEB-INF folder, then the commandButton does not execute the managed bean method.

```<code> <h:form id="loginForm">
    <p:commandButton action="#{LoginMgr.doLogin()}" value="Login"/>
 </h:form>
</code>```

Our bean:

```<code><bean id="LoginMgr" name="LoginMgr" class="com.tesipro.channelmanager.business.implemented.CMLoginManager">
</bean>
</code>```

In fact we think the problem is that with JSF, the pages are rendered using a link to the same page as the action of the form, so if the page is located in WEB-INF it is not publicly accessible.

We know that having all our XHTML views in the web folder instead of WEB-INF actually solves the issue, but we would like to store that pages into WEB-INF.

答: Does storing it in "app/WEB-INF/view" folder help? We do have several actions defined in XHTMLs in "app/WEB-INF/view" folder. Not invoking a spring bean from there, though, but calling a web-flow action.</p>


问:
MVP Pattern - Ways to restrict the user action based on security privilleges
In an MVP application, what should be the most appropriate way to implement restriction to some UI actions based on the current user's privileges?

For example, in a role-based security, different roles will have different access to some UI interactions on the same view. If, for instance, we have an online store, on the products list page the customers can only view the details and add items to their cart, but an administrator must be also presented with Add Product buttons and Delete button on each item.

Similar question has been asked here already, but the OP is asking for the UI making the permission checks. I am certain the UI (view) should not be responsible for permission validation, but still it has to know whether to visualize or not certain UI components. So, is there any well-defined or widely adopted pattern for telling the view which UI interactions it should disallow? I can think of a few solutions, but if there is a standard and proven one, I'd prefer to stick with that, rather than reinventing the wheel.

Update

To clarify a bit further, as suggested in answers below, I am considering the approach of having the view accept the privileges information from the presenter. It is the form of that information that bothers me - if using flags as bit masks or some too-generic representation I will:

(+) Gain consistency in passing the permissions to the view

(-) Couple the view with logic for resolving the flags.

The other thing I have in mind is having the View expose all the flags it needs as settable properties for the presenter (like view.IsDeleteItemAllowed). So I will:

(+) Not have additional logic for the permissions in the view

(-) Add additional complexity to presenter to adapt permission flags to the view's properties.

So, I am thinking of using the later approach, because that way I can reuse the presenter with different view implementations; and will not rely on the view for understanding the permissions system (which may be a subject of changes). Is there anything I should worry about with that?

答:
I don't think there is a specific pattern for this. There are two obvious solutions to this:

The Presenter provides flags/a value to the View telling it the privilege level of the current user.

The View requests the CurrentUser Model object for its privilege level/if it has privilege X.

Which of those two gets used should mostly depend on how much interaction you allow between the View and the Model (i.e. can the View ask information from the Model, or should it all be provided by the Presenter).

Whether to use flags or a single value should depend on the design of your privilege system. For a set of privileges that can be independently granted or denied, a set of flags would be most useful. For increasing levels, where level X+1 can do everything of level X plus some more, I would go for a single value.

Update

If your permission system is subject to change, the best way to keep those changes out of the View is to give the View its own permission system based on fine-grained flags (isInsertionAllowed, isDeletionAllowed, etc.) and let the Presenter map between the two permission systems.

What you should watch out for with using individual properties is that, if a View needs an additional property after a modification, the Presenter for that View also needs to be updated.

Also note that when I talk about flags, this can be implemented either as bit-flags, or as boolean properties/arguments. That does not really make a difference for the design.


问:
Applications of heapsort
Heapsort is a sorting algorithm that has a time complexity of O(nlogn), and performs sorting using O(1) space complexity. However, I know that because it's unstable, it doesn't find many applications (f.e. compared to other sorting algorithms).

I know it's used for interval scheduling.

What are some practical applications of heapsort?

EDIT: As @AProgrammer pointed out, quick sort isn't stable either.

答:
Quicksort does not behave well on small inputs, because there is a big chance that the pivot will be chosen badly (not a median of all sorted elements). Hence, Heapsort or even Insertion sort is usually used for sized arrays.

From here stems another application of heapsort - Intosort. Introsort is a sorting algorithm, which combines strengths of both quicksort and heapsort. Large arrays are sorted using quicksort, but when expected limit of depth is reached - log2n - the algorithm swaps to heapsort.

I would say that if the complexity O(nlog2n) is not needed to be guaranteed, than quicksort is (almost) always used, bacause it is on average faster and is a widely used library algorithm. If you want to improve the behaviour of Quicksort, than you use it in conjuction with Heapsort. And only when the O(nlog2n) is to be guaranteed, than the implementations use plain heapsort.

Title: Applications of heapsort


问:
Storing a re-orderable list in a database
I'm working on a wishlist system, where users can add items to their various wishlists, and I plan to allow users to re-order the items later on. I am not really sure about the best way to go about storing this in a database while remaining fast and not turning in to a mess (this app will be used by a fairly large user base, so I don't want it to go down to clean up stuff).

I initially tried a position column, but it seems like that would be quite inefficient having to change every other item's position value when you move them around.

I have seen people using a self-reference to refer to the previous (or next) value, but again, it seems like you would have to update a whole lot of other items in the list.

Another solution I've seen is using decimal numbers and just sticking items in the gaps between them, which seems like the best solution so far, but I'm sure there has to be a better way.

I would say a typical list would contain up to about 20 or so items, and I will probably limit it to 50. The re-ordering would be using drag and drop and will probably be done in batches to prevent race conditions and such from the ajax requests. I'm using postgres (on heroku) if it matters.

Does anyone have any ideas?

Cheers for any help!

答:
First, don't try to do anything clever with decimal numbers, because they'll spite you.  REAL and DOUBLE PRECISION are inexact and may not properly represent what you put into them.  NUMERIC is exact, but the right sequence of moves will run you out of precision and your implementation will break badly.

Limiting moves to single ups and downs makes the whole operation very easy.  For a list of sequentially-numbered items, you can move an item up by decrementing its position and incrementing the position number of whatever the previous decrement came up with.  (In other words, item 5 would become 4 and what was item 4 becomes 5, effectively a swap as Morons described in his answer.)  Moving it down would be the opposite.  Index your table by whatever uniquely identifies a list and position and you can do it with two UPDATEs inside a transaction that will run very quickly.  Unless your users are rearranging their lists at superhuman speeds, this isn't going to cause much of a load.

Drag-and-drop moves (e.g., move item 6 to sit between items 9 and 10) are a little trickier and have to be done differently depending on whether the new position is above or below the old one.  In the example above, you have to open up a hole by incrementing all positions greater than 9, updating item 6's position to be the new 10 and then decrementing the position of everything greater than 6 to fill in the vacated spot.  With the same indexing I described before, this will be quick.  You can actually make this go a bit faster than I described by minimizing the number of rows the transaction touches, but that's a microoptimization you don't need until you can prove there's a bottleneck.

Either way, trying to outdo the database with a home-brewed, too-clever-by-half solution doesn't usually lead to success.  Databases worth their salt have been carefully written to do these operations very, very quickly by people who are very, very good at it.


问:
Most MVC-strict php framework
I have been trying to wrap my head around MVC pattern for about 6 months.I've read tons of articles, Q&A, and blog posts about MVC and HMVC patterns, but I just simply don't get it 100%.

I tried learning MVC by exercising one of widely used PHP MVC framework, CodeIgniter. I've implemented few internal websites for my company with it. And STILL, I don't 100% get it. I believe one of the best ways to learn something is to follow strictly defined rules.

So my question is: What is the most strict PHP framework in terms of how MVC pattern is implemented? One that defines how I use models, controllers, and views so that I can completely get what MVC is?

答:
It seems like you are just having trouble "putting it all together" because many tutorials are poor at explaining MVC in a clear way. I recommend that you get your hands "dirty" and build a simple application with about 3 to 5 different frameworks to see how they typically approach the problem. Some have documentation on how to setup the basic MVC architecture for an application and if they don't you can always google for a couple mvc tutorials for that particular framework.

FWIW I liked Zend's project/directory layout recommendation: http://framework.zend.com/manual/1.12/en/project-structure.project.html

Also take a look at Rasmus' "The no-framework PHP MVC framework". It shows you don't really need a framework, you can just build your own to suit your specific needs. Plus you'll get a kick out of the comments!
http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html

Title: Most MVC-strict php framework


问:
I'd like to write an "ultimate shuffle" algorithm to sort my mp3 collection
I'm looking for pseudocode suggestions for sorting my mp3 files in a way that avoids title and artist repetition. I listen to crooners - Frank Sinatra, Tony Bennett,  Ella Fitzgerald etc. singing old standards. Each artist records many of the same songs - Fly Me To The Moon, The Way You Look Tonight, Stardust etc. My goal is to arrange the songs (or order the playlist) with the maximum space between artists and song titles. So if I have 2000 songs and 20 are by Ella I'd like to hear her only once in every 100 songs. If 10 artists sing Fly Me To The Moon I'd like to hear it once in every 200 songs. Of course I want to combine these two requirements to create my "ultimate shuffle".

I know this is a fairly wide open question. I haven't started programming it yet so I'm just looking for suggestions of a good approach to take. I actually have some other requirements regarding evenly spacing other song attributes but I won't get into that here.

As a starting point I'm modifying code I found here to manipulate mp3 files and read ID3 tags.

I wrote a small app that satisfies my need using parsifal's answer below. I also wrote a follow up question here. Thanks for all the great responses!

答:
Do you want to run your program once and generate a playlist, or pick the next song live?

If the latter, then the answer is simple:

Create an array that contains all of your songs, with artist and title

Create a list (linked list preferable) to hold recently-played song titles. This list starts out empty, and each time you play a song you add it to the list. When the list hits your desired "no song repeat" size, drop the oldest (first) entry.

Ditto for a list of artists.

Picking a song then becomes the following sequence of steps:

Randomly pick a song from the "all songs" array. This is just a random number between 0 and the size of the array.

See if that song is already in the played songs list. If it is, go back to step #1.

See if the artist is already in the played artist list. If it is, go back to step #1.

Add the song artist/title to the appropriate lists, dropping old entries if needed.

Play the song.

There are a couple of possible issues, but they should only matter if you're doing this as homework and not a real project.

As @Dukeling said in a comment, if your collection is dramatically unbalanced in favor of a single artist or song title, you may get into a loop where you constantly reject songs. In practice, this is not going to be an issue. The solution is that you need to reduce the size of the "already seen" lists. And adding counters at steps #2 and #3 can tell you if it's a problem (if you see 10 failures in a row, raise a warning and/or reduce the size of the list).

If you're trying to produce a playlist that contains all of your songs played only once, you'll need to remove songs from the source array. This will also change how you deal with too many "recently played" failures (because eventually you might end up with only one artist in your source array).

If your ID3 tags are anything like mine, they contain plenty of misspellings. Does "Duke Ellington" need to be different from "Duke Elingten"? If yes, then look into using a Levenstein matcher when scanning the "recently played" lists.


问:
Impact of ending contract with know-ins-and-outs lead developer of a project
I have a long time running project. Its been running for about 6 months. The project is very big. The lead developer/team leader  designed the project and the whole project is in his brain. He knows all ins and outs. I also know almost everything. But I am not confident like him.

Problem is recently he is charging quite high for simple bug fix and small change request. I am worried if I end the contract what will be the future of the project. I had 2-3 public demos. I must launch soon. The project is still in development alpha.

What happens to the project if I end the contract?

Are the high charges is because he knows I can not end the contract now?

答:
What happens to the project if I end the contract?

You will have more work, you will gain more confidence, the project will be yours.

Are the high charges is because he knows I can not end the contract now?

This is a possibility. If you want a confirmation, suggest him that you can't afford such high charges and therefore that you will do the work yourself. He may end the contract or lower his charges.


问:
Good Data Structure book to improve programming logic for children
My cousin (Age 10) who studies in Standard 5. He wants to learn programming and programming logic.

Which book or resources should I refer? Is there any Good Data Structure book to improve programming logic specially for children?

答:
Check out Scratch.  My kids learned about programming from it and one of them even made a science fair project from it.

From their About page:

Scratch is a programming language that makes it easy to create your own interactive stories, animations, games, music, and art -- and share your creations on the web.
  As young people create and share Scratch projects, they learn important mathematical and computational ideas, while also learning to think creatively, reason systematically, and work collaboratively.


问:
Is $.proxy a code smell?
I've been writing most of my javascript applications in an OO style close to what I would use for most other languages. However, this means that most callbacks need to have a reference to an object, and I generally handle that by using $.proxy (or dojo.hitch, or whatever the framework's tool for this is) to be sure that the callbacks are operating in the context of my object, rather than the tag they were attached to.

Very quickly, this seems to lead to using proxied calls for almost everything, and can look like I'm fighting against the tool, particularly if the tool is jQuery.

Do you have a policy on how to handle javascript function binding in your work? Do you try fit your design to how the tool binds it's functions, or do you force the bindings to work according to your design?

答:
Well the alternatives to function binding are a lot worse, instead of a simple $.proxy call, the
popular alternative is to type this every time

```<code>var self = this;
$().click( function(e) {
    self.doit(e);
});
</code>```

Compared to

```<code>$().click($.proxy(this.doit, this));
</code>```

I have an active feature request for jQuery where this would be possible:

```<code>$().click(this);
</code>```

This is what the standard event listener api supports:

```<code>elem.addEventListener("click", this);
</code>```

The method .handleEvent is then called on this when the event occurs, with proper context. The element
as this is just useless because it can be always attained from event.currentTarget.

So it's not a code smell in that you could replace it with something simpler or better.

Title: Is $.proxy a code smell?

Body:
Well the alternatives to function binding are a lot worse, instead of a simple $.proxy call, the
popular alternative is to type this every time

var self = this;
$().click( function(e) {
    self.doit(e);
});

Compared to

$().click($.proxy(this.doit, this));

I have an active feature request for jQuery where this would be possible:

$().click(this);

This is what the standard event listener api supports:

elem.addEventListener("click", this);

The method .handleEvent is then called on this when the event occurs, with proper context. The element
as this is just useless because it can be always attained from event.currentTarget.

So it's not a code smell in that you could replace it with something simpler or better.


答:
This is an optimization job, and a pretty complex one if you are looking for the optimal solution. Fortunately I believe it to be one of those cases where good enough will do.

First thing to do is to establish a mathematical quality criterion, that is a formula that given a permutation of the list will return a single number describing how good or bad that permutation is.

A simple formula suggestion, each criteria that you would like taken into account should be given a weight, give a high weight to important criteria, and a low weight to criteria where a lot of songs share the same property, so that those do not dominate:

```<code>For each song on the list
    For each other song on the list
        For each criteria
            If the two songs share that criteria
                Add to the quality value: square root( [criteria weight]/[distance between the two songs] )
</code>```

The lower a value this procedure produce, the better the list permutation is.

Making the permutation

Now you could take this formula to math.stackexchange and have them tell you how insanely difficult and possibly practically impossible it is to find the optimum solution for anything but a trivial number of songs, or you could just throw clock cycles at it and get a good solution.

There are many ways of doing this, here is one:

```<code>Start with a random permutation of the list.
Several million times do the following:
    Select two entries at random
    For each of those two entries calculate their contribution to the quality value
    Swap the positions of the two entries
    Calculate the contribution to the quality value of the two entries at their new position
    If the sum of the calculations in the new positions is greater than the sum in the old positions
        Swap back
</code>```

This is a somewhat wasteful algorithm, but it is easy to implement and can deal with as many criteria as one desire.

Optimizations

Loads of different tweaks and optimizations can be applied, here are a few:

In quality value calculation, don't bother checking a song against every other song on the list, instead just check it against the 100 or so closest songs. For common values this speed optimization has practically no influence on the quality of the result.

For a rare value of a given property it may be more efficient to track the existing instances of that value than to search for them.

If you feel that it is important that values that have few instances get spaced close to even, rather than just far apart it is probably necessary to increase the weight for those specific values, but not for other values of that criterion.

A pseudo-random function that pick all possible pairs from the list in equal distribution may have a slightly better efficiency per pick than a normal random pick.

Title: I'd like to write an "ultimate shuffle" algorithm to sort my mp3 collection

Body:
I'm looking for pseudocode suggestions for sorting my mp3 files in a way that avoids title and artist repetition. I listen to crooners - Frank Sinatra, Tony Bennett,  Ella Fitzgerald etc. singing old standards. Each artist records many of the same songs - Fly Me To The Moon, The Way You Look Tonight, Stardust etc. My goal is to arrange the songs (or order the playlist) with the maximum space between artists and song titles. So if I have 2000 songs and 20 are by Ella I'd like to hear her only once in every 100 songs. If 10 artists sing Fly Me To The Moon I'd like to hear it once in every 200 songs. Of course I want to combine these two requirements to create my "ultimate shuffle".

I know this is a fairly wide open question. I haven't started programming it yet so I'm just looking for suggestions of a good approach to take. I actually have some other requirements regarding evenly spacing other song attributes but I won't get into that here.

As a starting point I'm modifying code I found here to manipulate mp3 files and read ID3 tags.

I wrote a small app that satisfies my need using parsifal's answer below. I also wrote a follow up question here. Thanks for all the great responses!

Body:
This is an optimization job, and a pretty complex one if you are looking for the optimal solution. Fortunately I believe it to be one of those cases where good enough will do.

First thing to do is to establish a mathematical quality criterion, that is a formula that given a permutation of the list will return a single number describing how good or bad that permutation is.

A simple formula suggestion, each criteria that you would like taken into account should be given a weight, give a high weight to important criteria, and a low weight to criteria where a lot of songs share the same property, so that those do not dominate:

For each song on the list
    For each other song on the list
        For each criteria
            If the two songs share that criteria
                Add to the quality value: square root( [criteria weight]/[distance between the two songs] )

The lower a value this procedure produce, the better the list permutation is.

Making the permutation

Now you could take this formula to math.stackexchange and have them tell you how insanely difficult and possibly practically impossible it is to find the optimum solution for anything but a trivial number of songs, or you could just throw clock cycles at it and get a good solution.

There are many ways of doing this, here is one:

Start with a random permutation of the list.
Several million times do the following:
    Select two entries at random
    For each of those two entries calculate their contribution to the quality value
    Swap the positions of the two entries
    Calculate the contribution to the quality value of the two entries at their new position
    If the sum of the calculations in the new positions is greater than the sum in the old positions
        Swap back

This is a somewhat wasteful algorithm, but it is easy to implement and can deal with as many criteria as one desire.

Optimizations

Loads of different tweaks and optimizations can be applied, here are a few:

In quality value calculation, don't bother checking a song against every other song on the list, instead just check it against the 100 or so closest songs. For common values this speed optimization has practically no influence on the quality of the result.

For a rare value of a given property it may be more efficient to track the existing instances of that value than to search for them.

If you feel that it is important that values that have few instances get spaced close to even, rather than just far apart it is probably necessary to increase the weight for those specific values, but not for other values of that criterion.

A pseudo-random function that pick all possible pairs from the list in equal distribution may have a slightly better efficiency per pick than a normal random pick.


问:
Why is sizeof called a compile-time operator?
Originally, this is a part of another question.

Why is sizeof called a compile-time operator? Isn't it actually a run-time operator? And if it is indeed a compile-time operator, how does it help in producing portable code which runs the same in different computers ? Please explain in detail.

答:
sizeof() gives you the size of the data type, not the size of a particular instance of that type in memory.

For example, if you had a string data object that allocated a variable size character array at runtime, sizeof() could not be used to determine the size of that character array.  It would only give you the size of the pointer.

The size of a data type is always known at compile time.


答:
Heap sort is always O(nlogn) without the Quicksort worst case of O(n2).  This is important in order to put an upper bound on the maximum processing time.

Heapsort is also useful in some applications because processing can begin before all the data is available.  Data could be received in packets with time delays.  Rather than wait for all the data to arrive before starting to sort, Heapsort can begin with the first element to arrive and proceed incrementally so that its nearly complete when the last element is available.

Title: Applications of heapsort

Body:
Heapsort is a sorting algorithm that has a time complexity of O(nlogn), and performs sorting using O(1) space complexity. However, I know that because it's unstable, it doesn't find many applications (f.e. compared to other sorting algorithms).

I know it's used for interval scheduling.

What are some practical applications of heapsort?

EDIT: As @AProgrammer pointed out, quick sort isn't stable either.


问:
Understanding stack frame of function call in C/C++?
I am trying to understand how stack frames are built and which variables (params) are pushed to stack in what order? Some search results showed that the C/C++ compiler decides based on operations performed within a function.  For example, if the function was supposed to just increment a passed-in int value by 1 (similar to ++ operator) and return it, it would put all the parameters of the function and local variables into registers.

I'm wondering which registers are used for returned or pass by value parameters.  How are references returned? How does the compiler choose between eax, ebx,ecx and edx?

What do I need to know to understand how registers, stack and heap references are used, built and destroyed during function calls?

答:
This depends on the calling convention being used. Whoever defines the calling convention can make this decision however they want.

In the most common calling convention on x86, registers aren't used for passing parameters; the parameters are pushed on to the stack starting with the rightmost parameter. The return value is placed in eax and can use edx if it needs the extra space. References and pointers are both returned in the form of an address in eax.


答:
C++ doesn't actually store the metadata for objects at runtime so size checking must be compile time.  For an example of how C++ doesn't validate size, declare an array of int of some arbitrary size and read past the end of it.  If you're lucky you'll get a segfault but more likely you'll simply read gibberish, because C++ doesn't track the size of your array.

See Can a C/C++ program seg-fault from reading past the end of an array (UNIX)? for an example from SO.

Body:
Originally, this is a part of another question.

Why is sizeof called a compile-time operator? Isn't it actually a run-time operator? And if it is indeed a compile-time operator, how does it help in producing portable code which runs the same in different computers ? Please explain in detail.


答:
because the entire sizeof "call" is calculated at compile time and whatever is between the parenthesis is discarded and not run at runtime,

the result is purely based on static type info available to the compiler

Title: Why is sizeof called a compile-time operator?


问:
Saving Multiple Sizes of Images
We have lots of user-generated images on our site.  When users upload their images, we only store the original.  However, depending on the page, we show different sizes of those images (small, medium, large, original).  Is it necessary to store all sizes of these images or is there a better way?  Currently, we are resizing them with CSS but this is really slow.  </p>

答:
Storing multiple copies of the image at the required sizes is probably your best bet, for a few reasons:

Disk space is relatively cheap,

As @Jalayn commented, downsizing images doesn't require much processing power,

As @Dan Pichelman commented, serving smaller images when possible will save on bandwidth costs.

Once a file is uploaded, kick off an async process to generate the various copies so the user doesn't have to wait.

Title: Saving Multiple Sizes of Images


答:
There's a lot of way you can handle this, and I think the "right way" depends.

However I think we can all agree that storing the different sizes is the best way.

Your site might not be setup in a way that 3 sizes work for you though (such as small, medium, large) and of course storing every possible combination is unpractical. So with that being said I would store a few different sizes based on the most common sizes you serve.

If you happen to store a 100px x 100px image most of the time and need a  90px x 90px image just serve the 100x100 and scale it down with css, that's not as big of a deal as having to serve the 900x900px image and scaling it down. It's a good compromise.

Title: Saving Multiple Sizes of Images

Body: We have lots of user-generated images on our site.  When users upload their images, we only store the original.  However, depending on the page, we show different sizes of those images (small, medium, large, original).  Is it necessary to store all sizes of these images or is there a better way?  Currently, we are resizing them with CSS but this is really slow.  </p>


问:
What problems can happen if an XML file is not backed by a schema?
What is a XML schema in plain simple terms? What will be the problem if an XML doesn't have a schema defined? An example can be very helpful.</p>

答:
The main problem I see is that it cannot be validated either against a DTD, or against an XML Schema. As such, you don't have any guarantee that what you received is what you expected.

For example, if you are sending this XML file to someone:

```<code><x id="2">
    <yyy>
        <zzz>fdslgskfmlsdk</zzz>
        <zzz>sdmflsdmfl</zzz>
    </yyy>
    <yyy>thingy</yyy>
</x>
</code>```

How can he be certain that:

is "id" always a number ?

is "id" mandatory or optional ?

is "id" the only attribute of the "x" element ?

how many "yyy" elements can be contained in a "x" element ?

is "yyy" the only element that can be inside "x" ?

how many "zzz" elements in a "yyy" element ?

etc.

There is an unlimited list of questions that person can ask to you. The goal of an XML Schema is to hopefully answer all these questions and also to provide a way to validate a document before or during the parsing phase.

Not fond of w3schools, but here is a list of short and interesting reads on XML Schema:

Why use XML Schema ?

Tutorial on XML Schema

Also, why XML Schema beats DTD, old but good read.

Body:
The main problem I see is that it cannot be validated either against a DTD, or against an XML Schema. As such, you don't have any guarantee that what you received is what you expected.

For example, if you are sending this XML file to someone:

<x id="2">
    <yyy>
        <zzz>fdslgskfmlsdk</zzz>
        <zzz>sdmflsdmfl</zzz>
    </yyy>
    <yyy>thingy</yyy>
</x>

How can he be certain that:

is "id" always a number ?

is "id" mandatory or optional ?

is "id" the only attribute of the "x" element ?

how many "yyy" elements can be contained in a "x" element ?

is "yyy" the only element that can be inside "x" ?

how many "zzz" elements in a "yyy" element ?

etc.

There is an unlimited list of questions that person can ask to you. The goal of an XML Schema is to hopefully answer all these questions and also to provide a way to validate a document before or during the parsing phase.

Not fond of w3schools, but here is a list of short and interesting reads on XML Schema:

Why use XML Schema ?

Tutorial on XML Schema

Also, why XML Schema beats DTD, old but good read.


问:
Send stdout or stderr to a new thread
For performance issue I want the logging send to a new thread.

While the main program can work, the new thread can write the error or other messages to a file without effect to the main program. How could I send all stdout to the new thread?

Work to be done:

create a new thread, ok

open a file, ok

create a pipe inside the thread, ok

send stdout to the new thread, with freopen or dup?

Every time the buffer gets full, or every 5 seconds the log file gets new data.

Because it is an MPI program, I can't fork the whole program. It has to be a Posix thread.

答:
create an internal producer/consumer

your log call will produce a message that will be consumed by the other thread and written out to the log file

you will need to change the log call to push to the queue instead of writing to stdout but if you used a macro from the start that shouldn't be an issue ;)

edit what I mean by using a macro for logging is

```<code>#define LOG(s,...) printf(s,_VA_ARGS_)
</code>```

this would then change to

```<code>#define LOG(s,...) do{char[] buff = new char[512]; \
          snprintf(buff,512,s,_VA_ARGS_); \
          pushToLogger(buff);}while(0)
</code>```

pushToLogger(char*) is the function that does the pushing (and becomes responsible for freeing buff)

Title: Send stdout or stderr to a new thread

Body:
create an internal producer/consumer

your log call will produce a message that will be consumed by the other thread and written out to the log file

you will need to change the log call to push to the queue instead of writing to stdout but if you used a macro from the start that shouldn't be an issue ;)

edit what I mean by using a macro for logging is

#define LOG(s,...) printf(s,_VA_ARGS_)

this would then change to

#define LOG(s,...) do{char[] buff = new char[512]; \
          snprintf(buff,512,s,_VA_ARGS_); \
          pushToLogger(buff);}while(0)

pushToLogger(char*) is the function that does the pushing (and becomes responsible for freeing buff)


问:
How can a Right-Brainer Deal with Massive Left-Brainer Code?
I'm an artist, mostly, though I describe myself as a artist/physicist.  While I can do math, deal with  words, and the "logical" stuff considered left-brain, it's an effort and I make mistakes, whereas I do well with and most of the time think in terms of those things associated with right-brain thinking - spatial relations, holistic big-picture context, etc.  Of course all that is fuzzy, as the right-left brain theory is oversimplified and no mental activity is so simple.   Yet I do sense that I fit in fine with artists, video directors, chefs, and other non-verbal thinking, creative types, while most people in "IT" or hardcore software engineers have minds that work differently, with attention to detail, holding many details in mind at one time, and strong rational and verbal capabilities.

So here I am in a job being paid to fix fussy and obscure bugs in a massive swarm of C++ software, very heavy on OO, and any one line of code makes no sense unless I hold in mind about twenty other class and method names, relations between them, the flow of execution (very spaghetti-like) and other detail.

Besides that,  I'm also rather strongly against much of contemporary C++ and OO styles.  Those who wrote this code really drank the deep OO and Modern C++ kool-ade.  I find it actually makes code much harder to follow, much harder to decide where to fix or change something.   I don't know if this is part of the left/right differnce (or whatever you want to call it) or not.

But work on the C++ I must - people depend on me for my income.  What are tips and techniques to deal with this situation, to be as effective as possible for my employer?

答:
I think visually also and the details of typography bedevil me.

Google terms: British dyslexia site also Learning styles: visual spatial thinking, whole to part learning.

Concepts First, Tips After

Right brained people imagine everything in their 'mind's eye'.

When your visualization corresponds well to reality, the work is easy

Right brained thinkers who do not do Left brained thinking well must rely on visualization

Right brained learners learn the whole thing at once 'aha!' then fit details into the mental construct. They need the overview FIRST, then details.

Without an overview for context, the details float in a vacuum, unconnected in the mind's eye - so brute force memorization has to be used. Very hard for the right -brained.

TIPS that helped me:

1 Use Color to distinguish syntax parts

write  pseudocode of the code you are debugging: this does this, then go here and label code sections to match

if the objects were, say, real animals, they would have habits, and expected behaviors.This is a more easily visualized way of
thinking about codeing.

I imagine the code as a story with pseudicode as my notes and then follow the process around.

What section to fix next?

My workflow

Who lives there? (process, connections, data,etc.)

what do they need to do?
(function)  OK

OK

code it somewhere it can be syntax /spell checked  OK
copy and paste

Test

Result -->it Works? Yes, keep going

No? The characters must be acting out Hamlet where everyone dies.

Return to environment-

left something out?, sysntax errors

needs a connection

needs data

error code has meaning?

it works in another part of code?

Version trouble?

its supposed to work

ContentLicense: CC BY-SA 2.5


答:
If you need the context for multiple functions, I agree with Esailija's solution.  It's common and simple.

If you only need it once, this is also available:

```<code>$().click( function(e) {
    this.do_something();
}.bind(this) );
</code>```

If do_something takes no arguments (so it'll discard the e) and the anonymous function would only call it, I believe this also works:

```<code>$().click( this.do_something.bind(this) );
</code>```

Title: Is $.proxy a code smell?

Body:
I've been writing most of my javascript applications in an OO style close to what I would use for most other languages. However, this means that most callbacks need to have a reference to an object, and I generally handle that by using $.proxy (or dojo.hitch, or whatever the framework's tool for this is) to be sure that the callbacks are operating in the context of my object, rather than the tag they were attached to.

Very quickly, this seems to lead to using proxied calls for almost everything, and can look like I'm fighting against the tool, particularly if the tool is jQuery.

Do you have a policy on how to handle javascript function binding in your work? Do you try fit your design to how the tool binds it's functions, or do you force the bindings to work according to your design?

Body:
If you need the context for multiple functions, I agree with Esailija's solution.  It's common and simple.

If you only need it once, this is also available:

$().click( function(e) {
    this.do_something();
}.bind(this) );

If do_something takes no arguments (so it'll discard the e) and the anonymous function would only call it, I believe this also works:

$().click( this.do_something.bind(this) );


答: It's the same question as using a static or dynamically-typed language. Schema is a declarative check on the correctness of your data. If you have a field that has to be an integer, you can mark as such in your schema and then invalid data won't get past the validator. Without a schema, you would have to check in your code which is more error-prone. Sometimes, you might have a preference for flexibility in which case a schema is a hindrance. Notably there is no standard schema language for JSON, yet it is growing in popularity.</p>

Title: What problems can happen if an XML file is not backed by a schema?

Body: What is a XML schema in plain simple terms? What will be the problem if an XML doesn't have a schema defined? An example can be very helpful.</p>


答:
In addition to what Dirk said, an important use of stack frames is to save previous values of registers so that they can be restored after a function call. So, even on processors where registers are used for passing parameters, returning a value, and saving the return address, the values of those registers are saved on the stack before a function call so that they can be restored after the call. This allows one function to call another without overwriting its own parameters or forgetting its own return address.

So, calling a function B from function A on a typical "generic" system might involve the following steps:

function A:

push space for the return value

push parameters

push the return address

jump to the function B

function B:

push the address of the previous stack frame

push values of registers that this function uses (so they can be restored)

push space for local variables

do the necessary computation

restore the registers

restore the previous stack frame

store the function result

jump to the return address

function A:

pop the parameters

pop the return value

This is by no means the only way function calls can work (and I may have a step or two out of order), but it should give you an idea of how the stack is used to let the processor handle nested function calls.

Title: Understanding stack frame of function call in C/C++?

Body:
I am trying to understand how stack frames are built and which variables (params) are pushed to stack in what order? Some search results showed that the C/C++ compiler decides based on operations performed within a function.  For example, if the function was supposed to just increment a passed-in int value by 1 (similar to ++ operator) and return it, it would put all the parameters of the function and local variables into registers.

I'm wondering which registers are used for returned or pass by value parameters.  How are references returned? How does the compiler choose between eax, ebx,ecx and edx?

What do I need to know to understand how registers, stack and heap references are used, built and destroyed during function calls?


问:
Can we create a program that writes out its source code?
Can we create a program that print out its source code what if we (or the program itself) compile than the new program would have the same exact functionality what the original program has? So somehow it would reproduce himself in perfect clones that can reproduce too.

The program shouldn't use any external files othervise it would be realy easy to implement: we just need to create a program that reads a file than writes it out, than copy and paste the source code to the external file.

My first attempt was to write a program that has a print function than copy-paste the source code to this print function, but this program can reproduce himeself for only once, and doesn't have the same functionality because the second program cant print out the source code.

答:
That's called a quine. It's a frequent subject of programming challenges.

This page lists a large number of quines written in various languages. You can look at how it's implemented in those examples to get the general idea of how to write your own.


答:
Yes, as p.s.w.g said this is called a quine.

A quine is a computer program which takes no input and produces a copy
  of its own source code as its only output. The standard terms for
  these programs in the computability theory and computer science
  literature are self-replicating programs, self-reproducing programs,
  and self-copying programs.

From: http://en.wikipedia.org/wiki/Quine_%28computing%29

And, that can be achieved in any programming language that is turing-complete

see here for more info: https://stackoverflow.com/questions/2568020/is-it-possible-to-create-a-quine-in-every-turing-complete-language

Also, on a related note, here you can find examples of quines and other programming puzzles:
https://codegolf.stackexchange.com/search?q=quine

Title: Can we create a program that writes out its source code?

Body:
Can we create a program that print out its source code what if we (or the program itself) compile than the new program would have the same exact functionality what the original program has? So somehow it would reproduce himself in perfect clones that can reproduce too.

The program shouldn't use any external files othervise it would be realy easy to implement: we just need to create a program that reads a file than writes it out, than copy and paste the source code to the external file.

My first attempt was to write a program that has a print function than copy-paste the source code to this print function, but this program can reproduce himeself for only once, and doesn't have the same functionality because the second program cant print out the source code.


问:
When people work in different countries and need to work together how to keep code in correct language
I'm a member of a small new team and with one of our latest builds I noted that,  VS2010 code files don't contain language formatting.

So for example when I write down a Euro symbol in my code or use a "."  or "," in numbers or use Pounds, Euro  or Dollar symbols, those look ok in my code, but for a coder in Russia they don't. I wonder how other people tackle these kind of problems?

答:
One solution is to have a document that outlines the coding style that all in the team will be using.

This could bring more light on the issue:

It's important for a team to have a single coding standard for each
  language to avoid several problems:

A lack of standards can make your code unreadable.

Disagreement over standards can cause check-in wars between developers.

Seeing different standards in the same class can be extremely irritating.

Does your company have a coding standard?


问:
Estimated errors in implementation comparison
I've been working on improving an existing library to be more maintainable after trying to implement a feature I wanted and found the code to be hard to alter.

The library is a node.js grunt plugin called grunt-contrib-jshint and my implementation is in a repo called grunt-jshint-bfs.

I've run a code analysis tool called plato that generates a source analysis report that includes metrics line total/average lines of code, maintainability and estimated errors in an effort to compare the code bases for code quality purposes.

The trouble I'm having is comparing the estimated errors between the two projects, since one has 2 files and the other has many more files it would seem that the exposure to errors would increase, or am I reading that wrong?

Here is a link to my repo's report and the grunt-contrib-jshint report for comparison.

答:
I think you're reading that wrong. Based on reading the two reports, it appears that Plato infers an estimated error value from the length and complexity of the code. Longer, more complex functions tend to have higher estimated error values. Unfortunately, Plato does not provide any documentation (that I could find) for its algorithms and approaches, short of the source code itself, and a couple mentions of the complexity and lint libraries it uses. This tells me it is not a serious tool, though its reports look great.

Distributing functions across multiple files (without changing the functions themselves) should make no difference to the total error estimation. Plato does, however, seem to favor shorter source files, so you'll make the tool happier by moving functions to more files. That's not a big justification for doing so, IMO. It is also unfortunate that Plato provides so few project-wide totals for the various metrics it generates. Division of source into files is arbitrary, but the totals across all files are what matters.

As a comparison, here's Plato's report on jquery. It shows estimated error values well above 1 for many files. Does this mean that jquery (which is used on a significant fraction of the web pages in existence these days) has that many errors? I doubt it. Jquery, due to its heavy use, is also heavily tested, and probably nearly bug-free.

I think you should take Plato's results with a grain of salt. It uses some static analysis tools (and not particularly sophisticated ones, IMO) and bulk measurements that are not good metrics for coding style and engineering quality. Instead I recommend you trust your intuition about code quality and develop your sense of code smells [Wikipedia, Jeff Atwood].

And lastly, remember that while reducing complexity is a worthy goal, some code simply needs to be complex. Artificially diluting natural complexity (perhaps by many layers of subroutines) can render it unreadable by other programmers. Write a good comment and trust your colleagues to handle something a little hard.


问:
Why do we still use a programming language instead of using just SQL?
In database managements systems lecture, my professor said that we can use Oracle etc. ui designing tools instead of using Visual C# or etc. He added that SQL is as strong as a programming language. So I wonder why do we still use these programming languages for desktop applications which mostly adds/deletes/updates records? Is there any performance difference? What's the main reason? And if the business world applies it like that why we still try to learn a programming language instead of focusing on SQL?</p>

答:
SQL is difficult to use for certain tasks. Most notably, user interfaces as it cannot do infinite loops in its base form and would have trouble specifying where coordinates should be. It's very difficult to program at a low level in SQL as well since you cannot specify machine level operations in a declarative fashion with any real level of efficiency.

There are instances where SQL does not scale well, particularly in web-based distributed architectures. It is has issues dealing with binary data files, something that C or Perl has little trouble with. For more real-time applications like Games or Space Probes, SQL imposes too much overhead in terms of memory usage at that level of abstraction.


问:
What is the current status of software support for JPEG-2000?
The general recommendation to record original scanned images used to be "use TIFF". But programmers need evolution of format for "evolution of software", and I need to evolve my system to change from TIFF to JP2.

I have a big image storage (terabytes) for legal and scientific scanned materials, they need original recording. I use some caching rules, but the system need to show (via web download) or to manipulate (ImageMagick and others) original data.

I've read an article about migrating image storages from TIFF-lossless to JPEG-2000-lossless and the conclusion is to stay with TIFF. However the article is from 2009 and at the time they found support for the JPEG-2000 format by available software was very poor. The conversions to JPEG-2000 were lossy in the software they tested, and the available software for consuming images did not support the format well.

Is now the time to change from TIFF to JP2, or not? Is the software support still as flawed as it was in 2009?

答:
Based on Wikipedia's list of applications, support these days looks pretty good. It is also gaining traction in archive-oriented organizations worldwide:

Here's a page discussing its adoption by NATO, among others.

This paper mentions that the Harvard University Library is moving to JPEG-2000 as well.

This paper goes into detail on the British Museum and Harvard efforts, and adds the Wellcome Digital Library.

On my MacBook Pro running 10.7.5, here are some browser results (source 1, source 2):

Safari: no trouble

Chrome: sometimes needed to load QuickTime

Firefox: no trouble

I didn't test IE, but from those three, and the Wikipedia list, I think JPEG-2000 support is now widespread.

Regarding the issue of whether you should switch, since JPEG-2000 appears to have sufficient platform support now, I would switch only if there are strong technical reasons for doing so:

smaller image sizes

faster performance

more secure

TIFF is starting to be unsupported.

If you choose to switch, please post back with your experiences in doing so!


问:
Opinions on distribution of software via virtual appliance
I've created a distribution of my open source application framework in a working virtual appliance.  It includes everything to get started with the tutorial.  The distribution is Fedora 14 running Tomcat 5.5 and Oracle 10g Express Edition, plus my framework.  It is completely preconfigured and boots into a working running copy.

Would this be something you might try?

What assurances might you need to get you to try it?

Edit: The VM is just over a 2Gb download.  Alternatively it is also available via 23Mb download for the source and a PDF detailing how to configure the Tomcat and Oracle dependencies.

答:
Would this be something you might try?

No.  For a couple reasons.

Frankly, I wouldnt want to have to download a 2gig file just to try out an unknown, undocumented open-source project.  Not everybody has 100MB bandwidth.  Plus, you dont say what VM system this 'virtual appliance' uses, but 'virtual appliance' typically refers to VMWare.  That is not a no-impact install on a machine.

Also, imo, if this is the easiest way for you to distribute the project, I'm left with the impression then that the project must be such a pain to install that it needs a virtual appliance like this to realistically test.  Why would a user want to jump into that?

Also, your site has practically zero information about the project.  So now you are asking people to download a 2 gig appliance, and let VMWare do whatever its going to do to your system, without any assurances your project would actually do anything useful.

I think you'd be better suited to spend your time fleshing out the site so people can read a thorough description of the project's features, as well as streamlining the installation process to the point where an appliance isnt needed.


答:
What you are looking for is called Application Binary Interface - ABI.

There is a specification for each compiler that spells out the ABI.

Each platform will usually specify and ABI on order to support interoperability between compilers. For example, x86 Calling Conventions spells out the typical calling conventions for x86 and x86-64. I would expect a more official document than wikipedia however.


问:
Why does Java use so many middlemen?
For example to read data from a website we do:

```<code>HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
</code>```

The method that executes the HTTP request, returns a response, then we turn the response into an entity, then we turn the entity into a input stream, then you got to use two more objects, a buffer reader and a string builder,to turn that is into a string. It just seems like a lot of repetitive code. Why can't HttpResponse have a method that returns an InputStream, or better yet a String?

P.S. I'm not necessarily saying that Java is wrong, I want to find out what the reason behind it is, if any.

答:
Yes, you're right - in general Java requires a lot of ceremony for surprisingly simple situations*. The obvious advantage is that you see each step of the way to your goal, so you have more control. Network communications are done by wrapping messages inside envelopes, so you are exposed to this layering -- your library already hides many layers for you, but keeps the HTTP layers (the header and the entity) visible.

If you can make simplifying assumptions about the sequence of operations you must perform (for example, you don't want to inspect HttpResponse's status code), then you should just abstract it away into a helper method that does what you want, and call that instead.

In fact, there is an Apache HTTP client library that does just this. Take a look at this Stackoverflow question for a two-line example of going from URL to the text stream. (I suspect you may already be using this library, but I'm not sure.)

* Coming from Python and Perl, building a HashMap in Java is really verbose. Luckily Google Guava simplifies the notation.

Title: Why does Java use so many middlemen?


问:
Is there a name for being able to quickly find the relevant code?
I notice that a property of codebases that I like hacking on is that it's quick to find the relevant code for some feature, without knowing much about the code base at all. For example, searching for a label in the GUI, and immediately hitting the code that implements that feature.

This seems to be in direct tension with abstraction layers, where the label is probably buried behind an I18N module, and the business logic is probably further removed in an MVC framework. (It can be mitigated by including GUI labels in comments though, for example.)

It's obviously part of maintainability, but is there a name for this specific, desirable, property?

答:
Although I do not believe that there is a word specifically for this concept, the ease of use of these codebases can often be attributed to several causes, all of which have terms:

Well-documented - Which includes comments, external documentation, internal parsable documentation (like JavaDocs), and indicative variable names.

Well-organized - Shows design and planning

Readable - Besides resulting from the other two, this can be an intentional design choice of certain programming languages, such as Python, who make it a core "pillar" of their design ideology.


问:
How to encapsulate 'global' variables in C#? /best practice
In C# what is the best practice for encapsulating variables I need to use in multiple methods? Is it OK to simply declare them at the top of my class above the two methods?

Also if I am using app settings from my config file should I use a getter? like this...

```<code>private string mySetting{ get { return WebConfigurationManager.AppSettings["mySetting"]; } }
</code>```

What best practice is?

答:
It's not just OK. According to the book Clean Code it's actually a very good practice, and Uncle Bob really encourages it. A variable used by many methods could show a high degree of cohesion between the methods . Moreover, a high degree of object variables could also hint that said class should be split in two so declaring them as object variables could help you find out hidden class candidates. </p>

<p>Object level variables aren't global variables, so don't be afraid to use them if they should be shared by various methods. </p>

Body:
It's not just OK. According to the book Clean Code it's actually a very good practice, and Uncle Bob really encourages it. A variable used by many methods could show a high degree of cohesion between the methods . Moreover, a high degree of object variables could also hint that said class should be split in two so declaring them as object variables could help you find out hidden class candidates.

Object level variables aren't global variables, so don't be afraid to use them if they should be shared by various methods.


问:
How does one generate challenging different puzzles like the one in AirLock android game
here's the link of the app:

https://play.google.com/store/apps/details?id=com.iatll.airlock

I had studied AI in the final year of b.tech cs programme,   and i do remember some algorithm of generating and solving the 8 puzzle game; we had to implement it in Prolog (tough times)

But I'm not sure if the above mentioned app uses that same algorithm. Where do I need to look to create a puzzle game like that? They seriously couldn't have designed each level by hand right?  Had to be computer generated. How can I so that?

pardon me for not formatting,  I'm on a mobile device.

答:
It is likely that the levels of this game really were designed by hand, using the old but still very relevant art of Level Design.  In fact, generating these levels programmatically would have been too risky, as they would not necessarily produce the player experience that the developers wanted.

In general, though, the answer to these kind of questions of where to find such types of algorithms is generally to invent them yourself.  Though they might draw inspiration and pieces from other common algorithms, the end result is custom.  In the event that someone did produce a level generator for this game, it is likely that they manually determined the patterns and mechanics of how to do so - thus, either way, manual understanding of the generation of the levels is necessary.


问:
Static variable - Usage and Implications on Threading
I have some confusion regarding the use of static variables/references in a class. It feels like I may not have entirely figured out the implications of keeping something static.

When I say a variable is public static, is it one instance of the variable per class or one instance per assembly?

For example, I have a user control (say, for a WPF app). This user control has a public static variable that coordinates various things within the control. If there is a form in a client application that uses this user control, with multiple instances of this control per form, how many instances of the public static variable are created? (My guess is only one,  and it is modified by every control).

Now, I actually need each instance of the control to have one such variable, not one variable across all the instances of the control in that single form.

Does using a singleton pattern, with a "lock" keyword solve this issue i.e will it create one variable per instance of the user control?
If not, what issue does the singleton pattern solve?
What are the options in solving this design problem?

(Note: I have resorted to creating an internal non static global variable and passing it around carefully, instead of going the static route and its working fine. I am looking to see if there is another option.)

(Please bear with me if the question sounds very naive or unresearched, I did read a bit before posting, but seem stuck on finding an answer that explains it very clearly to me.)

答:
Completely ignoring any temptation to guess at the specifics of what you're trying to accomplish with your controls, or why, let me take a quick stab at answering your basic questions.

Up front; from your description, I think it sounds like your best option is just to have an instance field, not a static one, and not a singleton.  You said "I actually need each instance of the control to have one such variable, not one variable across all the instances of the control in that single form."  That is kind of a loose definition of an instance variable.  Does it even really need to be public?

Actually, I would make it an instance property, because chances are pretty good that sooner or later you'll want to raise some event when the thing changes, or do something else that will end up making a public field feel like an unfortunate decision in retrospect.  Hindsight is always 20/20.  Or at least 20/30 or so.  But in this case, a little foresight says that using a simple automatic property is cheap insurance:

public SomeDataType WidgetSettings{ get; set; }

So; there is only one instance of a static field/variable for the entire assembly.  Every instance of the class containing that public static variable has a reference to the very same object in memory.  So yes, all of your control instances are accessing the very same object/memory.

Any time you see "static" and "public" together in the same variable declaration line, it should be reason to pause and think.  The thing is, if the variable is something like a string, or a numeric type, or a simple collection, you will have to use synchronization code everyplace that you access that field from.  On the other hand, if it's a reference to a class with static getters and setters for various attributes, then you can put that synchronization code in the getters and setters, and you can test that class and its attributes in isolation (as a unit) and know that it works properly.  I don't know if I expressed that as well as I meant to...  But honestly, if you can what you need to do using instance variables and avoiding the whole thread-safety issue altogether, then do that instead.

If you have a static variable, it is absolutely for certain not thread-safe. At all. Maybe you're thinking that you're doing a Winforms app and all of the UI stuff executes on a single thread (because Winforms is not thread-safe), which is true enough if you follow the rules, except that we're all creative about using timers and background workers and such to loosen things up.  So it is still possible for strange things to happen. So in the worst case, not only are all of your control instances accessing and updating the same variable, they might be trampling all over each other in the process.

If you're messing with WPF, then the UI library is thread-safe and the potential pitfalls of multithreading combined with static fields apply.

If the data that the variable points at is a type that requires more than one instruction to write completely, then it is only a matter of time before one control instance writes only half of a new value before the next control instance reads that field and gets a value composed of half of one write and half of a different write.  I think the proper technical term for that situation is something along the lines of "fubar."  Of course the thread that reads that mangled variable may well try to write back to it before it gets swapped out by the thread scheduler and the original thread gets another go, replacing the first thread's half-value with its own half-value before the first thread even gets a chance to write the second half of its value.  This is likely to end in tears, or baldness, or more likely both tears and baldness.

Finally, the singleton has all the same potential thread-safety issues as the static field, because the whole notion of a singleton is that you grab your instance from a factory method, which serves the same single instance up to everybody who asks.  So everybody who asks is, by definition, accessing the very same object.

In this case, my gut tells me that "singleton" is a code word for "fancy static field, which requires a lot more code and a lot more testing, and still isn't thread-safe unless you write error-prone and performance-robbing synchronization code to go with it."

When a code word has a definition that long, it's worth seriously looking at a different approach.

For what it's worth.  :-)  Without more detail it would be awfully difficult to provide any answers that relate directly to your question.  What type of object is this static field pointing at?  Is it a collection?  Is it some kind of settings or configuration class with multiple properties? Is it an object that communicates with other parts of the system (events) in response to different signals you send it?  Etc.


答:
Java was created in a world where you wanted to see all of the steps, often you needed that fine gained control over your networking (or any other aspect of dealing with I/O).

I personally think it's not at all bad that developers are at least aware that such complexity exists, I find too many devs blindly accept that "Magic happens" and then can't debug/investigate a problem.  Yeah, yeah, get off my lawn I know.

Clearly the world has moved on, and simpler abstractions can and should be used as by default. Apache's HttpClient is the defacto lib to use for this in Java and you can also use languages such as JRuby, Jython, Groovy, Scala, Clojure all on the JVM to do this sort of work more concisely.

Title: Why does Java use so many middlemen?

Body:
For example to read data from a website we do:

```<code>HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
</code>```

The method that executes the HTTP request, returns a response, then we turn the response into an entity, then we turn the entity into a input stream, then you got to use two more objects, a buffer reader and a string builder,to turn that is into a string. It just seems like a lot of repetitive code. Why can't HttpResponse have a method that returns an InputStream, or better yet a String?

P.S. I'm not necessarily saying that Java is wrong, I want to find out what the reason behind it is, if any.


答:
Non-ascii characters are pain in Visual Studio. While our team does not consist of people using different locales, we have occasional need for characters from different locales and we use several other compilers that behave differently. So here is what we found works:

Visual Studio recognizes UTF-8 byte order mark. You can change the encoding in "File/Advanced Save Options" for individual file and default somewhere in Options. If you choose Unicode (UTF-8 with signature) - Codepage 65001, it is going to always display the same to all team members.

Unicode characters in wide literals (L"...") are properly encoded in UTF-8 sources.

Unicode characters in narrow literals ("...") are recoded to local charset. Without ability to select which one you want to recode to. So it will be recoded differently when different people compile it. Utterly useless; though I am not sure it is still not possible in VS2010, we use VS2008 and there it is not possible.

Escape sequences are never recoded.

So use the UTF-8 to make files display correctly for everybody, but in narrow strings you have to always use escapes anyway. You may use the characters directly in wide literals, but if you ever need to port the code, using escape sequences there is preferred anyway. It's not readable, yes. You can have the actual text in comment, it will display fine if it is UTF-8.

Hm, that was in particular for encoding, which I know is can of worms in Visual Studio. For the other things, in comments you just use one common language, usually English. And in user output you have to use std::locale.

As for actual localization, the resources system by default provided by Microsoft toolchain is notoriously difficult to maintain. I strongly recommend using system, that has English literals directly in code and translation catalogues from English to the other language. This ensures that you don't forget to update the translations when the source changes.

Either use Gettext, which can now be read by Boost.Locale or similar framework (e.g. Qt has similar system built in (and KDE replaces it with Gettext anyway)).

Boost.Locale also provides some function that make use of std::locale more convenient. Mainly extended typesafe printf-like function extended to support calling the std::locale number/currency/date... formatters internally.

Title: When people work in different countries and need to work together how to keep code in correct language

Body:
I'm a member of a small new team and with one of our latest builds I noted that,  VS2010 code files don't contain language formatting.

So for example when I write down a Euro symbol in my code or use a "."  or "," in numbers or use Pounds, Euro  or Dollar symbols, those look ok in my code, but for a coder in Russia they don't. I wonder how other people tackle these kind of problems?


答: Discoverability or learnability could be applied to this concept. But note that making something discoverable might be optimizing it for first time users. Look here for a related discussion.

Title: Is there a name for being able to quickly find the relevant code?

Body:
I notice that a property of codebases that I like hacking on is that it's quick to find the relevant code for some feature, without knowing much about the code base at all. For example, searching for a label in the GUI, and immediately hitting the code that implements that feature.

This seems to be in direct tension with abstraction layers, where the label is probably buried behind an I18N module, and the business logic is probably further removed in an MVC framework. (It can be mitigated by including GUI labels in comments though, for example.)

It's obviously part of maintainability, but is there a name for this specific, desirable, property?


问:
Efficient way to find highest value from predicates
I have predicate, that enumerates through backtracking list of values. I want to find highest value from this list.

For example:

```<code>ranked_move(X,Y,R) :- between(0,10,Y), between(0,10,X), rank_move(X,Y,R).
top_move(X,Y) :- % X, Y for highest R
</code>```

Right now, I have it solved by using findall and custom predicate that goes through the list and remembers highest value it comes across. But I would like to know if there is way to do it without first turning the moves into a list. Eg. do the picking predicate directly on ranked_move.

I know about https://stackoverflow.com/questions/1701693/max-out-of-values-defined-by-prolog-clauses . I haven't tried it, but I assume Prolog is not going to go through the predicates efficiently.

答:
As long as you don't have any way of judging your moves except calling ranked_move/3, no, there is no more efficient way than calling it on everything and finding the maximum of the resulting list.

It would be possible to avoid the findall by writing your own predicates that generate the values systematically and remember the maximum so far, and so avoid the overhead of creating a list. But that overhead is very likely insignificant next to the cost of judging the moves (no heuristic worth implementing could possibly be cheaper than a cons operation).

So the only really useful improvement would be to have a different, cheaper, weaker heuristic that influences the order in which the moves are generated, and iterate over them in an order more likely to have the maximum first. (Even then, of course, you would still not terminate any quicker unless you set a cutoff value that is "good enough" rather than "optimal".)


问:
Why is sizeof called a compile-time operator?
Originally, this is a part of another question.

Why is sizeof called a compile-time operator? Isn't it actually a run-time operator? And if it is indeed a compile-time operator, how does it help in producing portable code which runs the same in different computers ? Please explain in detail.

答:
Why is sizeof called a compile-time operator?

Because, at compile time, the compiler calculates the sizeof the expression and substitutes that compile-time constant value.

Isn't it actually a run-time operator?

No.
You can even use sizeof to evaluate the size of expressions you can't legally execute (ie, that would incur Undefined Behaviour), so long as the compiler can figure out what the type of the expression is.

Also, even before C++11 constexpr, you can use sizeof expressions in ways you can't use run-time expressions.

And if it is indeed a compile-time operator, how does it help in producing portable code ...

Types may vary in size on different platforms. Using sizeof expressions instead of hard-coded assumptions means your code won't break when you compile on a different platform and your types change size.


答:
Its simply good OO design, having separate objects at a fairly fine grained level.

HttpResponse encapsulates the entire response. It is composed of a status, headers and entity objects. These objects further encapsulate more fine grained details, for example the entity consists of information about the encoding type, length, encoding and a stream of the content itself.

This design avoids having a HttpResponse god object which does everything, end up being huge and loses its reusability.

Title: Why does Java use so many middlemen?


问:
Keeping git repositories on different hosts in sync
I am thinking about starting a small project and I want to make its versioning with git.

Bitbucket seems a good option for me with their free plan. I want to use it as the main tool for working with git since they have nice tools  like a web-interface, Mac OS client, and so on. But, in order to have higher protection from any accidental damages that can be caused by using a third-party service, I want also to install git on my NAS as a second back-up copy of the repository.

Now my question is, whether it is possible to create a repository on two different hosts and then keep them in sync? For example, suppose once per week I update the repository on my NAS to match the one on Bitbucket.  Then, in case something happens with Bitbucket, I will still have the full repository with full history of development on my local NAS storage.

And is there a way to import an existing repository with full history to another git-service?

I think that mirroring is what I need.
This article seems to describe exactly what I need.
And this one as well.

I believe that it will make full copy with full history and even automatically commit new versions to the repositories on both hosts automatically.

Am I right?

答:
Yes, that's exactly the beauty of DVCS such as git. You can use any number of different repos with the same state as the one on bitbucket or github.

Even you local copy (the repository on your computer) is usually a full clone of the remote repo.

The only thing you have to do to keep multiple repos in sync is pulling for one (usually called origin or upstream) and pushing to the backup copies.

ContentLicense: CC BY-SA 4.0


答:
I think it's a combination of a few things.

to be able to unit test properly you have to be able to inject your dependencies into the unit under test

Java does not have first class functions so objects are the only way to inject dependencies

Java's philosophy is for code to be mostly plain boring java that everyone can understand

Title: Why does Java use so many middlemen?


问:
Approach to use for user email address change in application?
As the title says, if the user wants change their email address in the application, in terms of programming, what approach (process) to use? Where do you store the new email address until the user will confirms it?</p>

答:
is the email id the login id? is it used as a reference anywhere else? does the user row have a different primary key?

If designed well then the table has a Db / separate primary key (and the email id it self is not a foreign key elsewhere). Then you could keep new email addresses in a different table till its verified along with the key to who it belongs. also as validation make sure same email id is not used by other user nor is it under validation by someone other user.

once validated, update to the main table, remove from the temp table and if you can keep the old email in an audit table


答:
The level of control offered does no harm, you can always build abstraction on top of it that fits your requirements. It would be bad if no control or not enough control was offered at all.

If you just wanted the response as a string directly, you could do this:

```<code>String result = httpClient.execute(httpPost, new BasicResponseHandler());
</code>```

This isn't example specific, you can usually either find a library or search documentation to do something in a relatively simple way if you find the defaults and lack of control acceptable.

Title: Why does Java use so many middlemen?

Body:
The level of control offered does no harm, you can always build abstraction on top of it that fits your requirements. It would be bad if no control or not enough control was offered at all.

If you just wanted the response as a string directly, you could do this:

String result = httpClient.execute(httpPost, new BasicResponseHandler());

This isn't example specific, you can usually either find a library or search documentation to do something in a relatively simple way if you find the defaults and lack of control acceptable.


问:
SOA - The four tenets
I'm reading about SOA and the four tenets required to make a SOA application. I have tried different sources, but the explanations are twisting. I'm searching for something that is a bit less abstract. Is my interpretation correct?

The four tenets is:

Services have explicit boundaries

Services are autonomous

Services share schema and contract, not class

Services interoperate based on policy

My interpretation is:

The methods that a client may use shall be easy to use and well
defined.

Services shall not be dependent on others. Change of one service
shall not affect another in any way.

A scheme represent the data that will be sent, contract contains the
defined methods for a service. To make a system loosely coupled, you
share scheme and contract instead of classes and objects.

A policy to use a service may be that a particular type of binding
is required so it may be used. Anyone that wants to use this service
must connect to it with this type of binding.

答:
You're pretty close with your abstractions, yes.

Yes.  Well encapsulated is another way of looking at this.

Yes, but...  Service can rely on other services for functionality, especially if that avoids duplication of code.  The nuance here is in the definition of dependent, I guess.

Yes.  Services perform a contract for a scheme.  User provides XYZ data and the Service will provide ABC action per the contract.

I view services as operating against a business policy.  Business policy shouldn't get to the level of specifying binding.  From the implementing business policy point of view, you can see where some services would be dependent upon other services in order to fulfill their contract without duplicating code.

At a broader level, business policy is just a bunch of rules.  Rules that hopefully interoperate nicely with each.  But just like human resources, business rules have a nasty habit of not getting along with each other as well.  Services are the instantiation of those business rules.

From a lower level point of view, if the caller doesn't use the advertised binding(s) then the caller will (obviously) be unable to utilize the service.  So while your statement is correct, it's a bit of a tautology which doesn't enhance your understanding as much.

Title: SOA - The four tenets


问:
How to keep my Activity code readable and maintainable?
I have written a rather small App with only one activity. From my understanding an activity has to be seen as kind of a view and controller in one class.

But even for a little app, with 3 dialogs (made with AlertDialogBuilder and all those anonymous inner classes that come with it) my activity has 500+ LOC and became very hard to maintain. The activity houses mainly android lifecycle handlers and view handling. Business logic is very little.

How to handle activity classes to keep them readable and maintainable?

答:
When I develop for Android, I always think of my Activities as my controllers and my layouts (XML) as my views. The layouts interact with each other and the business logic through my Activities (controllers). Here are some mistakes I learned a lot from:

Keep your component Listeners as separate classes. I used to keep them as inner classes to my components (mainly Buttons). This made my Activity code a pure mess and editing it was like hell.

Try and have separate Activities for every action you have. This will make your code easier to get back to if you need to change stuff (and thus more maintainable)


问:
Is there any difference between interfaces and abstract classes that have abstract methods only?
Let's say we have an abstract class and let this class has only abstract methods. Is this abstract class different from an interface that has same methods only?

What I am looking to know is if there are any differences both philosophically, objectively and in the underlying programming language implementation between an Abstract Class with only abstract members and an equivalent Interface?

答: In most OOP languages, an implementing class can derive only from one abstract class, but implement multiple interfaces.</p>


答:
If you don't want to make a change to your user data storage (e.g. add another field to your database table.), you can include the new email address in the confirmation reply link as a parameter. For security purposes, you could also send a notice to the current address, "Hey, you're changing your email address to "whatever" so a confirmation was sent there...".

Your application will have to treat an email address change confirmatation a little different than your new account confirmation process by updating the email address. Maybe the old one is logged?

If the user chooses not to confirm your app doesn't have to do anything.

I don't know how critical an email address is to the application (relies heavily on notices or is just for your marketing purposes), but you may want to consider maintaining more than one. There can always be a default/main address. Old addresses are just disabled in case of a mix up.

Title: Approach to use for user email address change in application?

Body: As the title says, if the user wants change their email address in the application, in terms of programming, what approach (process) to use? Where do you store the new email address until the user will confirms it?</p>


答:
Abstract classes may feature abstract protected methods (in the languages I'm working with), in interfaces methods are usually always public. Whether this difference allows useful exploitations I don't know.

Edit I first thought that a private abstract method is of no use, but now I recalled that it may be used to ensure that that method is never called. This way you can prevent that a copy constructor of an object is called.

Title: Is there any difference between interfaces and abstract classes that have abstract methods only?

Body:
Let's say we have an abstract class and let this class has only abstract methods. Is this abstract class different from an interface that has same methods only?

What I am looking to know is if there are any differences both philosophically, objectively and in the underlying programming language implementation between an Abstract Class with only abstract members and an equivalent Interface?


答:
Technically, the differences aren't really significant but, conceptually, they are entirely different things and that leads to the technical differences others have mentioned.

An abstract superclass is exactly what it sounds like, it's a common type that is shared by many other types, like Cats and Dogs are Animals.

An interface is also exactly what it sounds like, it's an interface through which other classes can communicate with the object. If you want to make a Cat Walk, you're ok, cause Cat implements a CanWalk interface. Same for a Lizard, though they walk very differently. A Snake, on the other hand, does not implement CanWalk, so you can't tell it to Walk. Meanwhile, Lizard and Snake (or possibly more explicit subclasses -- I'm not an expert) might both shed their skin, and thus implement CanShed, while a Cat couldn't do that.

But they're all still Animals and have some common properties, like whether they're alive or dead.

This is why all methods on an interface must be implemented as public (or explicitly, in C#). Cause what's the point in an interface that's hidden from the class interfacing with the object? It's also why you can have multiple interfaces to an object, even when a language doesn't support multiple inheritance.

To go back to your question, when you look at it this way, there's very rarely a reason to have an entirely abstract superclass.


答:
I think the main difference is that : In an abstract class - even if all the methods are all abstract they can still provide data members (instance variables) and some code to the classes that implement it (in form of private methods or constructors), static blocks;  doing part of the work for the sub classes and helping them with the implementation.

One positive side effect : code is in one place so one place to make corrections. sub classes can just call super class method and then do something else or nothing if super class actions are enough for their case. Super class wants each sub class to make this decision so has marked all its implementation as abstract (some could be empty too)

Not relevant to question: but having interfaces means one class can implement two different contracts. So that is an advantage of a interface over a abstract super class


问:
CSS3 shorthand properties
Working on my own I tought I need to learn that css3 shorthand properties, because - as I know now, it affects website's loading time, so I need to optimize it a little bit.
I was thinking - is there any order how to write property values, when using shorthand prop's?
For example: font: 1em/1.5em bold italic serif

答:
With such shorthands, there's no order. On shorthands where you provide all numeric values (margin, padding, ...), the order is important :

4 values : applied in that order : top right bottom left

3 values : top right+left bottom

2 values : top+bottom left+right

1 value : top+bottom+left+right

Title: CSS3 shorthand properties


答:
In a language like C++ that allows multiple inheritance, and has no interfaces, abstract classes in which all methods are abstract can serve as interfaces. I haven't worked with C++ that much, but I guess multiple inheritance can cause problems when there are methods with the same name in base classes.

In languages like PHP and C#, interfaces provide a means of achieving similar polymorphism, although I dislike calling it "inheritance" since there's a conceptual difference between inheriting an abstract class and implementing an interface. Interfaces remove the conflict problem, because they themselves provide no implementation.

An interface serves as a contract to the outside world, while an abstract class can provide an implementation, although if used to "fake" an interface, it most likely won't.

The main conceptual difference is that when a class inherits another class (abstract or not), there's a relationship of "is", so a Car is a Vehicle and Dog is an Animal. With an interface, it's what the object does that matters. So both Car and Dog can Move() and the consumer knows it because they implement Movable, but a Car is definitely not a Dog, or an Animal. And the move implementation will be different (wheels vs legs) but the consuming code doesn't and shouldn't care. Interfaces are all about the consuming code, rather than the implementation.

The main point is if you have interfaces in you language of choice, use them for things that they're there for. If not (like in C++), you can fake them by using pure abstract classes.