问:
Is this a race condition?
I have a friend arguing this is a race condition, but I'm struggling to understand how.

This is for a web application using PHP and MySQL where users can login and create tickets, these tickets have tasks which users can add. Each task has a time spend variable.

When the user submits a task, it adds a row with the task data to a table. After the entry has been added, it calculates the total time spent for all tasks for this particular ticket, and updates a field in a different table with that value.

The argument my friend puts forth is that with many users, there will be race condition issues as users are simultaneously adding tasks for tickets.

But my defence is that as long as the update for total time spent is run after the insert query, it will still update the field correctly regardless of how many users are adding tasks at the same time.

答:
If you don't use transactions, then yes, there is a minor race condition that can result in having the incorrect value for the total time spent for a brief while. Consider for example the following timing of events:

```<code>[task 1 added]
[total selected]
                [task 2 added]
[total updated]
                [total selected]
                [total updated]
</code>```

Now the client 1 selects the total amount, but a new task is added after this and for a brief while, the total contains an incorrect value. However, soon after the client 2 will update the total to the correct value.

Can the tasks be deleted in addition to adding them? If so, the situation might become more complex and requires further analysis.

You should really use transactions in this use case. This ensures that the updating of the total and the addition of the task happen simultaneously when viewed from outside of the transaction. Using a transaction with a proper isolation level eliminates the minor race condition.

You should note, however, that while transactions help in this use case there are various transaction isolation levels and all potential race conditions in don't disappear unless your database truly supports the SERIALIZABLE isolation level and you are actually using it. Many databases have the default isolation level set to something else than SERIALIZABLE and do not actually support the true SERIALIZABLE isolation level while they silently accept it and offer something worse. To read about transaction isolation levels, see e.g. http://www.postgresql.org/docs/9.1/static/transaction-iso.html (this is for PostgreSQL, not MySQL)

For an example of the case when the race condition can occur despite using transactions, see this timing:

```<code>[transaction 1 begins]
                       [transaction 2 begins]
[task 1 added]
                       [task 2 added]
[total selected]
                       [total selected, doesn't yet see transaction 1]
[total updated]
                       [total updated, waits for lock of transaction 1]
[transaction 1 commits]
                       [transaction 2 commits]
</code>```

Now transaction 2 updates the total but doesn't yet see the row added by transaction 1, and thus the total ends up containing only the value of task 2 but not the value of task 1. This happens if you're not using the SERIALIZABLE isolation level. If, on the other hand, you are using the SERIALIZABLE isolation level on recent PostgreSQL, one of the transactions would fail due to serialization failure and you would need to be prepared to retry.

To fix this without using SERIALIZABLE, you need to select a locking row for update (the SQL command SELECT ... FOR UPDATE):

```<code>[transaction 1 begins]
                       [transaction 2 begins]
[select for update]
                       [select for update, waits for transaction 1]
[task 1 added]
[total selected]
[total updated]
[transaction 1 commits]
                       [select for update wait done]
                       [task 2 added]
                       [total selected, doesn't yet see transaction 1]
                       [total updated, waits for lock of transaction 1]
                       [transaction 2 commits]
</code>```

I'm not sure if MySQL supports the true SERIALIZABLE isolation level or if it's just snapshot isolation. There was at least some work put into it by Michael Cahill, but I'm not sure if that work got ever merged to the MySQL distribution.

Do note that for transactions to work properly, you need to use a transactional database engine. I.e. InnoDB instead of MyISAM.

Title: Is this a race condition?

Body:
If you don't use transactions, then yes, there is a minor race condition that can result in having the incorrect value for the total time spent for a brief while. Consider for example the following timing of events:

[task 1 added]
[total selected]
                [task 2 added]
[total updated]
                [total selected]
                [total updated]

Now the client 1 selects the total amount, but a new task is added after this and for a brief while, the total contains an incorrect value. However, soon after the client 2 will update the total to the correct value.

Can the tasks be deleted in addition to adding them? If so, the situation might become more complex and requires further analysis.

You should really use transactions in this use case. This ensures that the updating of the total and the addition of the task happen simultaneously when viewed from outside of the transaction. Using a transaction with a proper isolation level eliminates the minor race condition.

You should note, however, that while transactions help in this use case there are various transaction isolation levels and all potential race conditions in don't disappear unless your database truly supports the SERIALIZABLE isolation level and you are actually using it. Many databases have the default isolation level set to something else than SERIALIZABLE and do not actually support the true SERIALIZABLE isolation level while they silently accept it and offer something worse. To read about transaction isolation levels, see e.g. http://www.postgresql.org/docs/9.1/static/transaction-iso.html (this is for PostgreSQL, not MySQL)

For an example of the case when the race condition can occur despite using transactions, see this timing:

[transaction 1 begins]
                       [transaction 2 begins]
[task 1 added]
                       [task 2 added]
[total selected]
                       [total selected, doesn't yet see transaction 1]
[total updated]
                       [total updated, waits for lock of transaction 1]
[transaction 1 commits]
                       [transaction 2 commits]

Now transaction 2 updates the total but doesn't yet see the row added by transaction 1, and thus the total ends up containing only the value of task 2 but not the value of task 1. This happens if you're not using the SERIALIZABLE isolation level. If, on the other hand, you are using the SERIALIZABLE isolation level on recent PostgreSQL, one of the transactions would fail due to serialization failure and you would need to be prepared to retry.

To fix this without using SERIALIZABLE, you need to select a locking row for update (the SQL command SELECT ... FOR UPDATE):

[transaction 1 begins]
                       [transaction 2 begins]
[select for update]
                       [select for update, waits for transaction 1]
[task 1 added]
[total selected]
[total updated]
[transaction 1 commits]
                       [select for update wait done]
                       [task 2 added]
                       [total selected, doesn't yet see transaction 1]
                       [total updated, waits for lock of transaction 1]
                       [transaction 2 commits]

I'm not sure if MySQL supports the true SERIALIZABLE isolation level or if it's just snapshot isolation. There was at least some work put into it by Michael Cahill, but I'm not sure if that work got ever merged to the MySQL distribution.

Do note that for transactions to work properly, you need to use a transactional database engine. I.e. InnoDB instead of MyISAM.


问:
When and why to use Page.ResolveUrl
So, i had a discussion with a colleague on why and where should we use Page.ResolveUrl("~/PageUrl.aspx") instead of ./PageUrl.aspx.

For example, are there any differences between:

 ' runat="server"> Home

and

 Home  ?

Here is what i found on msdn but the only benefit i see from there is that Page.ResolveUrl is good at resolving urls  for content ( images & stuff like that)

Here you can find a good example on why to use Page.ResolveUrl but Babu Naresh Narra does not say anything about the ./ usage.

Are there any other benefits that Page.ResolveUrl gives over the basic ./ approach?

答:
Suppose you had made a User Control that you were going to use on many different pages. Part of the User Control is a link to the Home page.

If you use the User Control on a page that is more than one level deep:
i.e http://website/folder1/APageWithUserControlOn.aspx

then this :

 Home

will resolve to http://website/folder1/Home.aspx

Where as this:

```<code> <a href="<%= Page.ResolveUrl("~/Home.aspx")%>" runat="server">
</code>```

Will resolve to http://website/home.aspx which is much more likely to be what you wanted as the link will be correct on any page. The server side Page.Resolve resolved the url from the root when using '~'. You might thing you could use '/Home.aspx' in the first example, but this doesn't work as expected when using Virtual Directories.

ContentLicense: CC BY-SA 3.0

Title: When and why to use Page.ResolveUrl

Body:
Suppose you had made a User Control that you were going to use on many different pages. Part of the User Control is a link to the Home page.

If you use the User Control on a page that is more than one level deep:
i.e http://website/folder1/APageWithUserControlOn.aspx

then this :

<a href="./Home.aspx" runat="server"> Home </a>

will resolve to http://website/folder1/Home.aspx

Where as this:

 <a href="<%= Page.ResolveUrl("~/Home.aspx")%>" runat="server">

Will resolve to http://website/home.aspx which is much more likely to be what you wanted as the link will be correct on any page. The server side Page.Resolve resolved the url from the root when using '~'. You might thing you could use '/Home.aspx' in the first example, but this doesn't work as expected when using Virtual Directories.


问:
Can I use in a non-free script a code example that doesn't mention license but which is used by its author in a GPL'ed script?
After seeing the following question one of my problems came in mind: I want to couple two different scripts in two different languages.

I found a solution for that, and I copied that solution. Unfortunately the same author uses this code for a script which he put under the GPL, but he did not mention the GPL in his example.

Can I use the connection (pipe-construction) in a non-free script, even if the script he uses this code is under the GPL?

I want to combine python and ruby, and I used the code from this page. Later I found out that he wrote a script licensed under the GPL using the same technique.

答:
Most likely, no you cannot use the other person's script without licensing your code under the GPL.

For you to legally use someone else's work, they need to provide a license to you for that code.  Some licenses, such as MIT and BSD, are permissive, and are the equivalent of giving the code away.  Other licenses, such as the GPL, impose restrictions upon end-users of their code.

You stated that the script you want to use is GPL'd, then you must release your code as GPL if you wish to use their script.

The fact that an example was provided without explicitly stating the license is mot.  That example was effectively unlicensed code to which you did not have permission to use.


问:
proper exception handling (throwing/message) dll libary
I just wrote a dll library  using vb.net. while testing, i got an error which i did not initially use a try-catch block. The code is

```<code> Try
            'The first four bytes are for the Command
            _Command = DirectCast(BitConverter.ToInt32(data, 0), Commands)

            'The next four store the length of the name
            Dim nameLen As Integer = BitConverter.ToInt32(Data, 4)

            'The next four store the length of the message
            Dim msgLen As Integer = BitConverter.ToInt32(Data, 8)

            'This check makes sure that ClientName has been passed in the array of bytes
            If nameLen > 0 Then
                _ClientName = Encoding.UTF8.GetString(Data, 12, nameLen)
            Else
                _ClientName = Nothing
            End If

            'This checks for a null message field
            If msgLen > 0 Then
                _Message = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen) <-- this is the error line
            Else
                _Message = Nothing
            End If
        Catch ex As Exception
            Throw
        End Try
</code>```

The error is

Index and count must refer to a location within the buffer. Parameter
  name: bytes

My question now is would it be considered good practice to throw errors from dll  or return an error message to the client.

My client is expecting an array if bytes as response and i need a way to send back valid error message

答:
Exceptions denote exceptional cases, which I think is in your case. Assuming I am understanding your question correctly, returning an empty/null result could also imply that the input was [4][4][4][0], so there was nothing to return, rather than an empty or malformed input array.

I would suggest that wrap that exception with an exception of your own, something which will make more sense to your client but without providing extra information on what is going on underneath. If your client does not care, and would like to treat situations like the above and situations where the input is invalid the same, then, it will be up to them.


问:
How can QA staff test caching logic that they can't see?
I just implemented a caching layer in my web application, and now I'm wondering how QA is supposed to test it, since caching is transparent to the user.

One idea I have is to put logging in the methods that invoke the code that populate the cache, and record when an object is pulled from cache and when it requires recreation from the database, and then the testers could view the logs to see if, for example, a certain object is reloaded from the db every 10 minutes, instead of every page view.

But can anyone suggest some better practices for this situation?

答:
One question is whether the cache itself is really a requirement that should be tested by QA. Caching improves performance, so they could test the difference in performance to ensure it meets some requirement.

But good idea to have some testing around caching, whoever is responsible for it. We used performance counters. If your cache system takes advantage of these, they are straightforward. If there is any way to get a count from the cache itself, that is another option.

Using your approach is nice too. If any of these are wrapped in automated tests that check the results, then no one has to look through logs to find answers.


问:
What is the correct approach for creating an application around a library?
I have a library that defines messages. In my particular instance, it's autogenerated code from an XSD using JAXB (Java). The messages can be very complex, with some members as objects and those objects containing other objects. The objects are both classes and enumerations. The library is a single JAR file with no dependencies, billed as a reusable component for Java applications. The idea is that any Java application that needs to send or receive these messages would use this library to do so. At present, there are 10 messages that are defined, but there are a large number of data types (classes and enumerations) that are also defined in the library that are contained within the messages.

The immediate need is for a graphical application that lets the user construct the messages in the specified format and then publish them appropriately over a network connection. This means that the user would be able to create the 10 messages and populate the various fields that go into them. The result is an XML string that conforms to the schema that can be published to a listening application. The listening application is also generating messages that are also defined in the XSD and the library in accordance with the schema and those must be received.

It is desirable to also be able to create a command-line version of this application that can be scripted. This command-line version is not well-defined, but it could be interactive (with prompts) or simply command-line argument driven to publish the messages.

What would the best approach to building my application around this library?

Two approaches come to mind:

The first approach is a a wrapper around the library that is part of the application build. This wrapper would be almost a duplication of the JAXB library, but it wouldn't invoke the generated data objects until requested. It would be a builder that would also provide validation and perhaps a simplified interface for some of the components of the messages. This could be useful, since the JAXB library doesn't have a concept of validation until the elements are marshalled. Although you can marshall to a default handler as opposed to your output format like a file or stream, but that seems not very useful since the messages you get from validation errors aren't exactly user-friendly. In this approach, the GUI, the text user interface, and the command-line interface would all interact with this application data model.

The second approach would be to organize my user interfaces into different packages. The GUI packages would provide user interface elements that correspond to the fields of each message. The validation rules from the XSD would be applied as validation rules to each field, using things like InputVerifiers, combo boxes, check boxes, and other things that prevent invalid data before it's even passed off to the data model. The text user interface would essentially provide the same thing, but by reading from and writing to the standard input, output, and error streams. I suspect in these implementations, the input classes would correspond to the data model classes 1-to-1 - each input class would be responsible for gathering and validating the user inputs needed to construct a single data element (one class in the data model provided by the JAXB library). I suspect that the textual UI and GUI can share base classes or interfaces that each of the UI classes can inherit from to allow them to be passed into the same controller to read from and produce the appropriate object from the data model. A command-line interface would likely use a command-line argument parser to gather the input, ensure everything is there, validate all of the fields, and then carry out the transmissions or receptions. It would be implemented very differently than the interactive user interfaces.

I'm personally leaning toward the second approach, but I suspect that there may be another, better strategy out there.

答:
The interface to build these messages is the same in both the GUI application and the command line interface. For example, both applications can:

Add elements

Update elements drilled down in the message

Delete elements

Validate messages

I would design this part first. Design the behaviors that you want to be able to do which would then call the appropriate API calls in your messaging class. You've discussed data validation at length - the validation code would all go within the data model. Don't worry about how the user will be informed of invalid messages yet; you can throw ValidationExceptions that get caught later on in the design.

Once this data model works the way you want it, you can then attach any sort of interface you want that can call these data model methods.

This is essentially option 2, but the distinguishing feature is the order in which you do the work. By designing the data model first, you will discover the various user operations that make the most sense, before you worry about drawing screens or picking command line flags (or whether you want the command line tool to be interactive).

When it is time to design the "View" (MVC definition of the word), start by writing interfaces that will work for both the command line and GUI version. Then you can use JLine or Commons CLI (depending on what you mean by command line) or something else for the former, and Swing or JavaFX or whatever in the latter.


问:
Is creating the objects you think you will need ok in a first test in TDD
I'm fairly new to TDD and I have trouble when creating my first test when it comes before any of the implementation code. Without any framework to the implementation code I am free to write my first test however I want but it always seems to come out tainted by my Java / OO way of thinking about the problem.

For example in my Github ConwaysGameOfLifeExample the first test I wrote (rule1_zeroNeighbours) I started out by creating a GameOfLife object that hadn't been implemented yet; called a set method that didn't exists, a step method that didn't exist, a get method that didn't exist, and then used an assert.

The tests evolved as I wrote more tests and refactored, but originally it looked something like this:

```<code>@Test
public void rule1_zeroNeighbours()
{
    GameOfLife gameOfLife = new GameOfLife();
    gameOfLife.set(1, 1, true);
    gameOfLife.step();
    assertEquals(false, gameOfLife.get(1, 1));
}
</code>```

This felt odd as I was forcing the design of the implementation based on how I had decided at this early stage to write this first test.

In the way that you understand TDD is this ok? I seem to be following the TDD / XP principles in that my tests and implementation evolved over time with refactoring, and so if this initial design had proved useless it would have been open to change, but it feels like I am forcing a direction on the solution by starting this way.

How else do people use TDD? I could have gone through more iteration of refactoring by starting out with no GameOfLife object, only primitives and static methods but that seems too contrived.

答:
I do not like system level tests written in java or C# for that reason.   Look at SpecFlow for c# or one of the Cucumber based test framework for java (maybe JBehave).   Then your tests can look more like this.

And you can change your object design without having to change all your system tests.

(“normal” unit tests are great when testing single classes.)

What are the differences between BDD frameworks for Java?


答:
You implemented a cache (I assume) because the system wasn't performing well enough. That is something that is relevant for the user. Here are things that QA can check:

That the system, after the cache was introduced, is still correct. This means they should attempt to trick the cache into providing stale data, which is something QA can verify, and make sure nothing else was broken.

That the system now meets performance threshholds that it was not meeting when you decided to improve performance. They can compare the old measurements and compare them to the new ones.

Remember, users (and, by extension, QA) don't care about how you solved a problem. They only care that the problem was solved and didn't create new problems. This is true whether you implemented caching, improved String parsing, did a hardware upgrade, or sprinkled magic fairy dust on the server.

Title: How can QA staff test caching logic that they can't see?

Body:
I just implemented a caching layer in my web application, and now I'm wondering how QA is supposed to test it, since caching is transparent to the user.

One idea I have is to put logging in the methods that invoke the code that populate the cache, and record when an object is pulled from cache and when it requires recreation from the database, and then the testers could view the logs to see if, for example, a certain object is reloaded from the db every 10 minutes, instead of every page view.

But can anyone suggest some better practices for this situation?


问:
Java System class implementation
The Java System class contains various data members and methods that make perfect sense being there. For instance:

```<code>System.in (variable)
System.err (variable)
System.out (variable)
System.exit(int)
System.gc()
System.getSecurityManager()
</code>```

etc. However, there is one method that I don't understand being there:

System.arraycopy(Object, int, Object, int int)

Copying one array to another feels to me like it belongs in the Arrays class; following from the documentation:

This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

Methods for manipulating arrays is what points me to this conclusion, as copying one array to another is surely array manipulation, right?

So my question: why is arraycopy() in System?

Is it a relic of an early Java System class implementation? The method isn't marked as deprecated, so I'm a little bit lost. Furthermore, it doesn't follow the Java camelCase standard, which brings me back to my thinking that it's a relic of the early library design.

答:
System.arraycopy is implemented natively by each JVM. Here is the method declaration:

public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);
```

This means that it does array copying in the fastest way possible in native assembly instructions. The idea is that this is such a commonly needed, potentially slow functionality that Java should provide this behavior at a low level.

Other ways of copying arrays either wrap System.arraycopy, or use interpreted loops, which would not be as performant.

Title: Java System class implementation

Body:
System.arraycopy is implemented natively by each JVM. Here is the method declaration:

public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);

This means that it does array copying in the fastest way possible in native assembly instructions. The idea is that this is such a commonly needed, potentially slow functionality that Java should provide this behavior at a low level.

Other ways of copying arrays either wrap System.arraycopy, or use interpreted loops, which would not be as performant.


问:
Do designer tools degrade the programming experience?
I've been looking around lately, specifically at some of the MS tools that are available, and I'm noticing a big focus on designer tools and wizards. Not just for UI development but for everything.

Entity Framework has the modeller

RIA Services has the DomainService wizard(s)

Workflow has the whole workflow designer thingy... (I don't know, haven't really used it)

There's more, but I think you get the idea. There's lots of designer tools. Using some of these I find that:

They complicate matters beyond the prescribed use cases

(ie all of the tech demo videos)

I have been evaluating some of these technologies recently, and trying to work with them I end up having to dissect exactly what the designers, modellers and wizards are doing for me... otherwise I'm lost when I actually have to try to do something with whatever was created.

This ends up being a case where I have to fight the tool, or fight its output enough such that I could have just done the whole thing myself without it - and had a much stronger understanding of what's going on. I find this particularly infuriating with the silverlight designer and RIA services domain service wizard.

I find myself asking "What good is this tool if I have to figure out its inner workings or re-write half of its output in order to use it?"

They're not as fast

The selling point of these tools is to increase productivity and this point may change over time using the tool, and doesn't necessarily apply to UI designers (though, in some cases it still does -> I'm looking at you silverlight designer). I find that I can hack some code much faster than I can drag-and-drop, resize, move, whatever in a designer.

The UI gets in the way of the model

Maybe this is just me, but when I am using anything reminiscent of a UML design tool I end up spending more time laying everything out so that my lines don't cross and so that I can see it all on the screen than modelling what I'm trying to achieve.

They're no fun

Half of the reason that I code for a living is that I enjoy it. Clicking checkboxes and selecting comboboxes and then fixing everything that comes out isn't fun.

I don't appear to be alone

The community seems to not want these tools either. The best example I can think of at the moment is Entity Framework Code-First.

So I ask:

Do designer tools actually improve productivity?

Are they fun-killers?

Is 'the community' actually asking for more designer tools, or are vendors just thinking we are?

答:
Do designer tools actually improve productivity?

They may as long as your project is simple and not too complex for them. My experience you hit the wall as soon you try to implement/solve a real world problem.

Are they fun-killers?

WF (Workflow) & WPF where fun but also killer when the VS 2008 crashed every 30min.

Is 'the community' actually asking for more designer tools, or are vendors just thinking we are?

Many of tools released by MS lately seem to be desperate attempts to keep the developers. The battle is now going on in smart phone market. Who will win the hart of developers, MS, Google or Apple?

ContentLicense: CC BY-SA 2.5


问:
How to define complex business rules using User Stories?
A quick and dirty definition of User Story:

```<code>"As a <role>, I want <goal/desire> so that <benefit>"
</code>```

In this commonly accepted definition there is little space for defining business rules, constraints or user input.

Trivial example just to illustrate:

```<code>"As a <librarian>, I want to <register new books> so that
<students can find their availability online>"
</code>```

In this silly example, where would one define the fields needed when registering a book? Should it be written anywhere? Or should the required business rules be passed as word of mouth by the Product Owner?

答:
The previous answers provide valid points, specially regarding a user story being a reminder to have a conversation. Other things to consider:

If the story is too complex, it's probably an epic. You can split epics into smaller stories now or once they get prioritized on the product backlog

Details that imply test cases are separated from the story itself. [Mike Cohn]

You can add on the back of the story card, make small notes if they are really important or put them into the acceptance tests document.

As a guideline to evaluate if your user stories are good, you may follow Bill Wake's suggestion:

Independent (of others stories)

Negotiable

Valuable (to the user or customer)

Estimable (to a good approximation)

Small (enough to be estimable)

Testable

You may want to read te Chapter 2 "Writing Stories" of the book User Stories Applied, by Mike Cohn.

ContentLicense: CC BY-SA 4.0


问:
What algorithm can be used to determine order given incomplete information?
Given a series of statements such as:

```<code>a<c
a<b
b<c
(Read as "a is before b", "a is before c", etc.)
</code>```

What is the order of the elements?  In this example, the answer is a<b<c.

A less trivial question would be:

```<code>a<c<d
b<d
c<e
a<b
</code>```

This one has four answers: a<b<c<d<e, a<c<b<d<e, a<b<c<e<d, a<c<b<e<d.

Edit: To be clear, an algorithm need only return 1 of the possible answers for the logical statements.  There will also never be a case where the statements have a contradiction.  E.g. below is an impossible input:

```<code>a<b
b<a
</code>```

答:
A topological sort algorithm can sort a collection of data according to some set of rules as you have specified, where not all pairs have a pre-defined ordering.

Typically the rules only define a partial ordering, so there are multiple possible orderings and topological sorting chooses an arbitrary one. If there's a contradiction in the rules you have specified, there will be no possible ordering.

If you can give a true/false/don't-know answer for any pair of elements in constant time, IIRC there are sequential algorithms that topologically sort in linear time - O(Vertices + Edges), as mentioned in comments below.

A contradiction in the constraints arises if, and only if, there is a cycle in the constraints. It may therefore by useful to identify the "greatest strongly connected components" in the digraph of constraints.

It may also be useful to grow your initial seed set of constraints to include all possible constraints that can be proven directly or indirectly from that seed set. In general, the resulting set is considered "closed" with respect to the function used to find new members, so algorithms that grow sets like this are "closure algorithms" - not to be confused with a lexical-scope closure. Particular set closures often mentioned WRT abstract algebra include symmetric closures (if a?b is in your set, also add b?a), reflexive closures (if a?b is in your set, also add a?a and b?b) and transitive closures (if a?b and b?c are in your set, also add a?c).

Ordering relations are transitive - if a<b and b<c then a<c - so the transitive closure of your set of constraints may be useful.

You might also want to identify clusters of elements that are ordered with respect to each other (assuming no contradiction) without caring initially about the order. This defines a partitioning of the elements into equivalence classes, given an in-the-same-cluster sense of equivalence. For that, you could use a disjoint set / union-find data structure - the equivalence classes are disjoint from each other, so each equivalence class is a set that's disjoint from the others. The union operation from union find basically says "whatever classes these two elements are in, combine those classes into a single class if necessary". The "find" determines which class a particular element is in, usually by choosing one element to represent that class.

A common theme in all this is the theory of graphs, although aspects come from abstract algebra and elsewhere. Basically, the relation a<b can be modelled as an edge on a graph between vertices representing the elements a and b. If you care about the ordering, that's a directed graph.

For example a relation x<y will appear in the transitive closure of your initial set of constraints if both x and y are in the same strongly connected component of the digraph.

Sorry, I got confused above - the relation x<y will appear in the transitive closure if there's any path between x and y in the digraph, but that doesn't imply a strongly connected component. A strongly connected component requires a cycle, not just a path.


答:
Is it a relic of an early Java System class implementation?

System.arraycopy is one of the oldest parts of the library, while java.util.Arrays was added in 1.2. I wouldn't quite call arraycopy a relic as there isn't anything that directly replaces it, and the various copy methods in Arrays are implemented in terms of it.

There's nothing special about System or Arrays that requires native methods to be in one or prevents them from being in the other.

Title: Java System class implementation

Body:
The Java System class contains various data members and methods that make perfect sense being there. For instance:

```<code>System.in (variable)
System.err (variable)
System.out (variable)
System.exit(int)
System.gc()
System.getSecurityManager()
</code>```

etc. However, there is one method that I don't understand being there:

System.arraycopy(Object, int, Object, int int)

Copying one array to another feels to me like it belongs in the Arrays class; following from the documentation:

This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

Methods for manipulating arrays is what points me to this conclusion, as copying one array to another is surely array manipulation, right?

So my question: why is arraycopy() in System?

Is it a relic of an early Java System class implementation? The method isn't marked as deprecated, so I'm a little bit lost. Furthermore, it doesn't follow the Java camelCase standard, which brings me back to my thinking that it's a relic of the early library design.


答:
Test performance, as indicated in Andy's answer.

I have found that the biggest obstacle to implementing caching (and performance) at many organizations is actually having an environment where you can do good performance testing and run tests for various real world load and performance tests.

To have this you should set up a performance testing environment that, as closely as possible, and allowing for costs, mirrors production.  This will probably NOT be your current development environment which should be be smaller and more self-contained to allow for rapid application development.  Development environments also tend to use caching less and so don't represent production well for performance testing.

In the performance testing environment the app should be running in production 'mode'.  You should more than one server if production does, database connection pool and caching should be set for a production environment, etc.

You'll also want to consider a tool to help with load testing.

jmeter is very popular though I find it quite unfriendly and primitive to use.

Another route I've used is to just url curl's with a ruby script.

To be clear

base line performance testing is for testing the time ONE request makes.

load testing is similar to performance testing but looks at response when the system is also under load from other requests.

You may also find the following links helpful:

Best practices for unit testing methods that use cache heavily?

Load Test Methodology for a cache

Is there any way to test how will the site perform under load

http://www.procata.com/cachetest/


答:
Burying important business logic or system state deep in a black box makes verifying correct system behavior difficult.  It's easier to exhaustively test the behavior of a single component in the system than the entire system.  I favor exposing such things explicitly through some mechanism so it can be unit / regression / integration / QA tested in some meaningful fashion.

One option with a cache would be to expose a special page that gives some details on the cache (contents, state, etc).  This can assist with debugging in development and potentially in production.  QA can also use this page to create test cases for the cache if they are given details on what the expected behavior of the cache is.  Using performance counters and/or log files to explicitly document the cache behavior is another less visible but viable approach.

Note that this approach is not a substitute for end-to-end performance testing.  This is a mechanism to ensure the cache itself behaves correctly.  Performance testing should be used to determine if caching has the intended aeffect on performance.

Also note that swapping out components of the system with new ones implementing the same interface like introducing a cache can be a destabilizing and deceptively complex change.  With the cache example, you are introducing state in what was previously stateless, which can create bugs that are harder to find or reproduce.  Such a change should always be accompanied with full regression testing to verify expected system behavior.


问:
Sanity check SQL
Is there any tools/processes to check SQL does not contain any possible issues.

For example we had an SQL ran that forgot to put a where clause on an update and mistakenly updated the entire table.

Is there a tool that can check your SQL and provides warnings for SQL updates which may be problematic. Or what is best practice to prevent these kinds of errors. We already have a peer review process but still have things like this slip through the cracks.

答:
Yes, there are tools like that and the best thing about them is that:

You can have your own custom standards and analysis rules

This is what you are pretty much looking for here.

So if you guys have a standard procedure through which you go through when code reviewing the SQL code just make your own custom standards and/or analysis rules and you should be able to catch everything you need in real time.

They also have their own predefined analysis rules and standards that you can use or modify if needed.

Most of the tools out there should have these functionalists baked in + more, depending on which one you choose specifically.

Myself I have had experience with SQL Enlight and it was definitely helpful when trying to keep things consistent across all teams.

One other reason I like SQL Enlight actually is because it is a great refactoring tool for when you come in front of a nasty, legacy SQL code.

Title: Sanity check SQL


问:
When is it a good idea to force garbage collection?
So I was reading a question about forcing the C# garbage collector to run where almost every single answer is the same: you can do it, but you shouldn't - except for some very rare cases. Sadly, nobody there elaborates on what are such cases.

Can you tell me in what sort of scenario it is actually a good or reasonable idea to force garbage collection?

I'm not asking for C# specific cases but rather, all programing languages that have a garbage collector. I know that you can't force GC on all languages, like Java, but let's suppose you can.

答:
As a general principle, a garbage collector will collect when it runs into "memory pressure", and it's considered a good idea to not have it collect at other times because you could cause performance problems or even noticeable pauses in your program's execution.  And in fact, the first point is dependent on the second: for a generational garbage collector, at least, it runs more efficiently the higher the ratio of garbage to good objects becomes, so in order to minimize the amount of time spent pausing the program, it has to procrastinate and let the garbage pile up as much as possible.

The appropriate time to manually invoke the garbage collector, then, is when you've finished doing something that 1) is likely to have created a lot of garbage, and 2) is expected by the user to take some time and leave the system unresponsive anyway.  A classic example is at the end of loading something large (a document, a model, a new level, etc.)


问:
Personal Digital Signatures in Web Applications
In order to sign data with personal digital signature in a web application, server side languages like PHP can do the whole job, but that would require that the user uploads his private key, lets say stored in PFX file, which would also require that he submit the (personal) password to unlock the PFX. Other alternative is to upload the already unlocked information in PEM format, which doesn't require the password, but the private key is much or more exposed as in the previous case.

What remains is to sign the data in the client machine, and submit the signed data together with the public key to the server.

As it is a web application i assume that would be done with JavaScript.

What would be the  the most global (crossbrowser/"official") JavaScript solution?

If you think this is misleading I appreciate correction and guidance.

Thank you

答:
Yes, you are correct, you can either treat the server as trusted and put an unencrypted (or encrypted with the password next to it) private key in the server to let the server do the signing itself or you treat the server as untrusted medium and do the signing on the local machine. The latter can't be done with JavaScript solution though, as the JavaScript itself needs to be delivered by the server, and a malicious attacker can replace that JavaScript with something of their own making. The application that signs should be disconnected from the server for best security.

Those are really the two major tradeoffs. There is no single "correct" solution, what you should choose depends on your security and availability requirements.

If you really need both high security, high auditability, and high availability, then one option is to use a hardware token on the server. The hardware token is a special purpose hardware dedicated just for signing, and it is designed so the private key cannot be extracted from the token; at least not through a remote connection. An attacker has to be present at the machine to have a chance to extract the key. A hardware token wouldn't prevent the attacker that managed to gain remote access to the server from tricking the token to sign their content, but it will provide auditability, as the token can keep records of things it signs, that are stored in such way that cannot be tampered easily by the attacker.


答:
You really can't make blanket statements about appropriate way to use all GC implementations. They vary wildly. So I'll speak to the .NET one which you originally referred to.

You must know the behaviour of the GC pretty intimately to do this with any logic or reason.

The only advice on collection I can give is: Never do it.

If you truly know the intricate details of the GC, you'll not need my advice so it won't matter. If you don't already know with 100% confidence it will help, and have to look online and find an answer like this: You should not be calling GC.Collect, or alternatively: You should go learn the details of how the GC works inside and out, and only then will you know the answer.

There is one safe place it makes some sense to use GC.Collect:

GC.Collect is an API available that you can use for profiling timings of things. You could profile one algorithm, collect, and profile another algorithm immediately afterwards knowing GC of the first algo wasn't occurring during your second one skewing the results.

This sort of profiling is the single time I would ever suggest manually collecting to anyone.

Contrived Example Anyway

One possible use case is if you load really large things, they'll end up in the Large Object Heap which will go straight to Gen 2, though again Gen 2 is for long lived objects because it collects less frequently. If you know that you are loading short lived objects into Gen 2 for any reason, you could clear them out more quickly to keep your Gen 2 smaller and it's collections faster.

This is the best example I could come up with, and it's not good - the LOH pressure you're building here would cause more frequent collections, and collections are so frequent as it is - chances are it would be clearing out the LOH just as fast as you were blowing it out with temporary objects. I simply don't trust myself to presume a better collection frequency than the GC itself - tuned by people far far smarter than I.

So let's talk about some of the semantics and mechanisms in the .NET GC... or..

Everything I think I know about the .NET GC

Please, anyone who finds errors here - do correct me. Much of the GC is well known to be black magic and while I tried to leave out details I was uncertain of, I probably still got some things wrong.

Below is purposely missing numerous details I'm not certain about, as well as a far larger body of information I'm simply unaware of. Use this information at your own risk.

GC Concepts

The .NET GC occurs at inconsistent times, which is why it's called "non-deterministic", this means you can't rely on it to occur at specific times. It's also a generational garbage collector, which means it partitions your objects into how many GC passes they've lived through.

Objects in Gen 0 heap have lived through 0 collections, these have been newly made so recently no collection has occurred since their instantiation. Objects in your Gen 1 heap have lived through one collection pass, and likewise objects in your Gen 2 heap have lived through 2 collection passes.

Now it's worth noting the reason it qualifies these specific generations and partitions accordingly. The .NET GC only recognizes these three generations, because the collection passes that go over these three heaps are all slightly different. Some objects may survive collection passes thousands of times. The GC merely leaves these on the other side of the Gen 2 heap partition, there's no point in partitioning them anywhere further because they're actually Gen 44; the collection pass on them is the same as everything in Gen 2 heap.

There are semantic purposes to these specific generations, as well as implemented mechanisms that honor these, and I'll get to those in a moment.

What's in a collection

The basic concept of a GC collection pass is that it checks each object in a heap space to see if there are still live references (GC roots) to these objects. If a GC root is found for an object, it means currently executing code can still possible reach and use that object, so it cannot be deleted. However if a GC root is not found for an object, it means the running process no longer needs the object, so it can remove it to free up memory for new objects.

Now after it's finished cleaning up a bunch of objects and leaving some alone, there will be an unfortunate side effect: Free space gaps between live objects where the dead ones were removed. This memory fragmentation if left alone would simply waste memory, so collections will typically do what's called "compaction" where they take all the live objects left and squeeze them together in the heap so the free memory is contiguous on one side of the heap for Gen 0.

Now given the idea of 3 heaps of memory, all partitioned by the number of collection passes they've lived through, let's talk about why these partitions exist.

Gen 0 Collection

Gen 0 being the absolute newest objects, tends to be very small - so you can safely collect it very frequently. The frequency ensures the heap stays small and the collections are very fast because they are collecting over such a small heap. This is based more or less on a heuristic that claims: A large majority of temporary objects which you create, are very temporary, so temporary they'll no longer be used or referenced almost immediately after use, and thus can be collected.

Gen 1 Collection

Gen 1 being objects that didn't fall into this very temporary category of objects, may still be rather short lived, because still- a vast portion of the objects created are not used for long. Therefore Gen 1 collects rather frequently as well, again keeping it's heap small so it's collections are fast. However the assumption is less of it's objects are temporary than Gen 0, so it collects less frequently than Gen 0

I will say I frankly don't know the technical mechanisms that differ between Gen 0's collection pass and Gen 1's, if there are any at all other than the frequency they collect.

Gen 2 Collection

Gen 2 now must be the mother of all heaps right? Well, yes, that's more or less right. It's where all your permanent objects live - the object your Main() lives in for instance, and everything that Main() references because those will be rooted until your Main() returns at the end of your process.

Given that Gen 2 is a bucket for basically everything the other generations couldn't collect, it's objects are largely permanent, or long lived at the least. So recognizing very little of what's in Gen 2 will actually be something that can be collected, it doesn't have need to collect frequently. This allows it's collection to also be slower, since it executes so much less frequent. So this is basically where they've tacked on all the extra behaviours for odd scenarios, because they have the time to execute them.

Large Object Heap

One example of the extra behaviours of Gen 2 is that it also does the collection on the Large Object Heap. Up until now I've been talking entirely about the Small Object Heap, but the .NET runtime allocates things of certain sizes to a separate heap because of what I referred to as compaction above. Compaction requires moving objects around when collections finish on the Small Object Heap. If there's a living 10mb object in Gen 1, it's going to take far longer for it to complete the compaction after collection, thus slowing down Gen 1's collection. So that 10mb object is allocated to the Large Object Heap, and collected during Gen 2 which runs so infrequently.

Finalization

Another example is objects with finalizers. You put a finalizer on an object that references resources beyond the scope of .NETs GC (unmanaged resources). The finalizer is the only way the GC gets to demand an unmanaged resource is collected - you implement your finalizer to do the manual collection/removal/release of the unmanaged resource to ensure it doesn't leak from your process. When the GC gets to executing your objects finalizer, then your implementation will clear the unmanaged resource, making the GC capable of removing your object without risking a resource leak.

The mechanism with which finalizers do this is by being referenced directly in a finalization queue. When the runtime allocates an object with a finalizer, it adds a pointer to that object to the finalization queue, and locks your object in place (called pinning) so compaction won't move it which would break the finalization queue reference. As collection passes occur, eventually your object will be found to no longer have a GC root, but the finalization must be executed before it can be collected. So when the object is dead, the collection will move it's reference from the finalization queue and place a reference to it on what's known as the "FReachable" queue. Then the collection continues on. At another "non-deterministic" time in the future, a separate thread known as the Finalizer thread will go through the FReachable queue, executing the finalizers for each of the objects referenced. After it's finished, the FReachable queue is empty, and it has flipped a bit on the header of each object that says they don't need finalization (This bit can also be flipped manually with GC.SuppressFinalize which is common in Dispose() methods), I also suspect it has unpinned the objects, but don't quote me on that. The next collection that comes around on whatever heap this object is in, will finally collect it. Gen 0 collections don't even pay attention to objects with that finalization-needed bit on, it automatically promotes them, without even checking for their root. An unrooted object needing finalization in Gen 1, will get tossed on the FReachable queue, but the collection doesn't do anything else with it, so it lives into Gen 2. In this way, all objects which have a finalizer, and don't GC.SuppressFinalize will be collected in Gen 2.

Title: When is it a good idea to force garbage collection?

Body:
So I was reading a question about forcing the C# garbage collector to run where almost every single answer is the same: you can do it, but you shouldn't - except for some very rare cases. Sadly, nobody there elaborates on what are such cases.

Can you tell me in what sort of scenario it is actually a good or reasonable idea to force garbage collection?

I'm not asking for C# specific cases but rather, all programing languages that have a garbage collector. I know that you can't force GC on all languages, like Java, but let's suppose you can.


问:
How do freelance web developers manage client hosting?
Looking for a side hobby/project of freelance web development as i am currently in university trying to make some extra cash.

So my question is:

When a client comes to me for a website should i set up an individual cheap hosting for 1 website only or purchase a more expensive hosting package and host multiple client sites on the same hosting package.

Would using a reseller account such as Hostgator's alumiunium/copper package with unlimited domains support this requirement or are there more suitable packages to support/host several websites on a single account?

I am confused as to how most people manage this or whether they just ask their client to set up their own hosting if they are technically skilled enough to do so.

答:
First thing first I would not recommend Hostgator as their service has become horrendous - they used to be good. Not anymore. Just my personal opinion from my experience.

As for managing your clients I would say that hosting their websites is not really a good idea because:

1) You automatically take on more responsibility: If one of your clients installs a vulnerable plugin and it gets hacked then all of your other client's websites are in danger as well since it is all shared. Just one example and there are many more.

2) Maintenance becomes a lot harder as the number of clients grows.

3) Most of the time you will have to use your resources sparingly hence you will only be able to provide them with less resources than if they got their own account.

The only good part about this is that as a reseller you can have the subscriptions go to you and if you collect enough clients it can pay off your subscription fee + bring in more money (this being a side business).

I have done this myself and found out that it was a lot of headache especially if you don't have as many clients to get at least a reasonable amount of money back.

As to how to approach them about getting their account set up I would say meet up with them face to face and help them go through the registration process.

If you cannot meet them then do a Skype session and share screens then walk them through.

But the bottom line is that I definitely recommend decoupling your clients from each other and letting them have their own hosting providers.


问:
How to write tests for function that depends on a config file?
I have a function that uses information from a config file. How do I test the function? Ideally, I'd want to inject my own version of the config file and test from there, but I'm not using dependency injection.</p>

答:
You have to write a test that works independent of the config file, so you can test that depending on the "simulated configuration" the output of the function or behavior of that function is correct.

You would need to inject the configuration file, or the value that you are trying to simulate on your function under test. This is the only way to guarantee that whenever you have that value, your function behavior is the indicated by the configuration file.

Ideally, you would also isolate the class that contains and dictates the behavior of the configuration file to the class/function that reads this file. When writing testing one of the goals should be isolation of the code under test.


问:
Whiteboard "testing" during an interview: legitimate way to back up your (whiteboard) code?
As I get it, having an error (even a typo like or missing ";") in your whiteboard code will often cost you some interview points. Avoiding that will inevitably make one proof-reading code again and again (losing time and possibly neural energy / concentration) or even using a simpler (and thus less effective) algorithm -- and both these ways are "costly" again!

So, why not just fast write code as elegant and effective as you would having a (unit) testing framework at your disposal and then just normally test it it (just on the whiteboard)?

Has anyone tried / seen this approach? Is the whole idea worthy?

[this also applies to the pen-and-paper case of course]

答: Asking a candidate to code on a whiteboard is silly. There are modern tools like snippits, jsfiddle and intellisense. In addition no engineer should be required to memorize syntax. Syntax is looked up and referenced. If you are memorizing code, you probably didn't spend any time in your career learning how to code in a mult-tenant environment, optimizing syntax or even a hosted environment. </p>


问:
How important are code formatting guidelines?
Coding standards are common in any software development organization, but how important are they to follow?  I can understand the need for some consistency, but when dealing with simple things like the position of braces, line length, etc., I'm not sure excessively strict standards contribute much to software development.

Isn't it more important that your code is readable, not that it conforms to a predefined standard?  It seems they're more like... guidelines anyway.

答:
At my current job, one of my first tasks was to come up with a coding standard for our development group.

My first effort was about sixty pages long (it incorporated much of the Framework Guidelines from Microsoft).  I was asked to pare it down, and my next effort was ten pages long, utilizing ideas from a variety of good sources.  I was asked to pare it down again, and finally got it down to three or four pages, I think.

It was never adopted.

Why?  Because I work with a lot of really smart people, who already follow a sensible coding standard instinctively.

For my part, I follow generally-accepted guidelines from Microsoft, and emulate the commonly-used styles of others (Javascript and jQuery are formatted differently from C#, even though they are both curly-brace languages).  I also break the rules from time to time, when doing so will make the code more readable.


答:
There are several cases where you might want to call gc() yourself.

[Some people say that this is not good because it may promote objects to older generation space which I agree is not a good thing. However, it is NOT always true that there will always be objects which can be promoted. It is certainly possible that after this gc() call, very few objects remain let alone be moved into older generation space] When you are going to create a big collection of objects and use lot of memory. You simply want to clear out as much space as preparation as possible. This is just common sense. By calling gc() manually, there will not be redundant reference graph check on part of that big collection of objects that you are loading into memory. In short, if you run gc() before you load a lot into memory, the gc() induced during the load happens less by at least one time when loading start creating memory pressure.

When you have done loading a big collection of big objects and you will unlikely load more objects into memory. In short, you move from creating phase into using phase. By calling gc() depending on implementation, the memory in used will be compacted which massively improves cache locality. This will result in massive improve in performance that you will not get from profiling.

Similar to the first one, but from the view that if you do gc() and the memory management implementation supports, you will create much better continuity for your physical memory. This again makes new big collection of objects more continuous and compact which in turn improves performance


问:
Make functions that imply other functions
I'm developing a game that often has repetitious code that I can't simplify.

Example of what I do normally:

```<code>Square object;
GL11.glPushMatrix();   // Pushes a matrix stack down by one. This allows us to rotate our object freely
GL11.glTranslated(object.x, object.y, 0); // Move object to its position
object.drawToScreen(); // Draws the object
GL11.glPopMatrix();    // Pushes a matrix stack up by one, prevents the translation from affecting other objects in the scene
</code>```

The above code gets bulky and needs to be repeated often.

What I want to do:

```<code>Square object;
bumpMatrix()
{ // implies GL11.glPushMatrix();
GL11.glTranslated(object.x, object.y, 0); // Move object to its position
object.drawToScreen();  // Draws the object
} // implies GL11.glPopMatrix();
</code>```

Is there a way to make this happen? I swear I've seen something like it somewhere before in Java. It would allow me to make a single function and not have to Copy/Paste the same group of code several times, just call that function.

答:
It's similar to the RAII idiom in C++, where you put resource management code in the constructor & destructor of a class. Since Java doesn't have destructors, if you're targeting Java 7 or later you could instead (ab)use try-with-resources and an AutoCloseable (untested):

```<code>class GLCoordGuard implements AutoCloseable {
    protected GL _gl;

    public Manager(GL gl) {
        _gl = gl;
        gl.glPushMatrix();
    }

    public void close() {
        _gl.glPopMatrix();
    }
}

...
    Square object;
    try (GLCoordGuard guard = new GLCoordGuard(GL11)) {
        GL11.glTranslated(object.x, object.y, 0); // Move object to its position
        object.drawToScreen(); // Draws the object
    }
</code>```

The syntax in the question resembles Ruby's blocks, which get packaged in a Proc object and passed to a function, which can invoke it whenever it likes. You can do something similar in Java by passing a lambda (which require Java 8) to another function (untested):

```<code>public void bumpMatrix(Function<Void,Void> glOps) {
    GL11.glPushMatrix();
    glOps.apply(null);
    GL11.glPopMatrix();
}
...
    Square object;
    bumpMatrix((Void unused) -> {
        GL11.glTranslated(object.x, object.y, 0); // Move object to its position
        object.drawToScreen(); // Draws the object
    });
</code>```

Body:
It's similar to the RAII idiom in C++, where you put resource management code in the constructor & destructor of a class. Since Java doesn't have destructors, if you're targeting Java 7 or later you could instead (ab)use try-with-resources and an AutoCloseable (untested):

class GLCoordGuard implements AutoCloseable {
    protected GL _gl;

    public Manager(GL gl) {
        _gl = gl;
        gl.glPushMatrix();
    }

    public void close() {
        _gl.glPopMatrix();
    }
}

...
    Square object;
    try (GLCoordGuard guard = new GLCoordGuard(GL11)) {
        GL11.glTranslated(object.x, object.y, 0); // Move object to its position
        object.drawToScreen(); // Draws the object
    }

The syntax in the question resembles Ruby's blocks, which get packaged in a Proc object and passed to a function, which can invoke it whenever it likes. You can do something similar in Java by passing a lambda (which require Java 8) to another function (untested):

public void bumpMatrix(Function<Void,Void> glOps) {
    GL11.glPushMatrix();
    glOps.apply(null);
    GL11.glPopMatrix();
}
...
    Square object;
    bumpMatrix((Void unused) -> {
        GL11.glTranslated(object.x, object.y, 0); // Move object to its position
        object.drawToScreen(); // Draws the object
    });


问:
Passing Parameters to pthread_create
I have a structure named graph.

graph *G;

Now I create memory of size of structure using malloc and the start pointer is stored in pointer G.

G = (graph*)malloc(sizeof(graph));

My question is how do I pass this as a argument to pthread_create?

pthread_create(&th,NULL,function_call, ? );

答:
the prototype of pthread_create is

```<code> int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
</code>```

As the arg parameter is a void* you can simply write

```<code>pthread_create(&th,NULL,function_call, G);
</code>```

However, it the function_call(), you will need to cast you arg parameter to the real type.
either:

```<code>function_call(void *arg)
{
    graph *tmp_G;

    tmp_G = arg;
    //  then I use tmp_G as G
}
</code>```

or

```<code>((graph *)arg)->the_field_of_G;
</code>```

Then you will be able to use you parameter as you need.

If you want to give more then one parameter to you function, you simply have to create a new structure that will contain all your parameters, then cast it as above to use them in your function_call().

here is an example :

```<code>typedef struct s_my_function_call_arg
{
    graph *G;
    int   arg2;
    char  *arg3;
}              t_my_function_call_arg;
</code>```

Title: Passing Parameters to pthread_create

Body:
the prototype of pthread_create is

 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

As the arg parameter is a void* you can simply write

pthread_create(&th,NULL,function_call, G);

However, it the function_call(), you will need to cast you arg parameter to the real type.
either:

function_call(void *arg)
{
    graph *tmp_G;

    tmp_G = arg;
    //  then I use tmp_G as G
}

or

((graph *)arg)->the_field_of_G;

Then you will be able to use you parameter as you need.

If you want to give more then one parameter to you function, you simply have to create a new structure that will contain all your parameters, then cast it as above to use them in your function_call().

here is an example :

typedef struct s_my_function_call_arg
{
    graph *G;
    int   arg2;
    char  *arg3;
}              t_my_function_call_arg;


答:
I can give you a rather generic answer that I feel is only suited to more complex use cases due to the excessive boiler plate required. You can perfectly simulate a functional paradigms in Java (they've done so in Scala) and use for example the decorator pattern to solve your problem. The general approach is to define an abstract class or an interface with a single method that then can be overwritten by an anonymous inner class.

Simple example for your use case:

```<code>public class SimpleDecorator {
    public static void main(String[] args) {
        new PrintingDecorator() {
            protected void execute() {
                System.out.println("Calling my first function");
            }
        }.apply();
        new PrintingDecorator() {
            protected void execute() {
                System.out.println("Calling my second function");
            }
        }.apply();
    }
}

abstract class PrintingDecorator {
    public void apply(){
        System.out.println("Doing this action before");
        execute();
        System.out.println("Doing this action after");
    }
    protected abstract void execute();
}
</code>```

Running this prints:

```<code>Doing this action before
Calling my first function
Doing this action after
Doing this action before
Calling my second function
Doing this action after
</code>```

Now you could go significantly farther and actually just define functions and such and base your decorator on that. So for the unnecessarily complex example:

```<code>public class FunctionalDecorator {
    public static void main(String[] args) {
        Function1<Function0<Void>, Function0<Void>> printDecorator = new Function1<Function0<Void>, Function0<Void>>() {
            public Function0<Void> apply(final Function0<Void> arg1) {
                Function0<Void> resultFunc = new Function0<Void>() {
                    public Void apply() {
                        System.out.println("Doing this action before");
                        arg1.apply();
                        System.out.println("Doing this action after");
                        return null;
                    }
                };
                return resultFunc;
            }
        };

        printDecorator.apply(
            new Function0<Void>() {
                public Void apply() {
                    System.out.println("Calling my first function");
                    return null;
                }
            }
        ).apply();

        //Slightly more complex example (with taking arguments and returning values)
        Function1<Function1<String, String>, Function1<String, String>> addTextDecorator = new Function1<Function1<String,String>, Function1<String,String>>() {
            public Function1<String, String> apply(final Function1<String, String> funcArg) {
                Function1<String, String> resultFunc = new Function1<String, String>() {
                    public String apply(String arg1) {
                        return "Before string\t" + funcArg.apply(arg1) + "\tAfter string";
                    }

                };
                return resultFunc;
            }
        };

        Function1<String, String> echo = new Function1<String, String>() {
            public String apply(String arg1) {
                return arg1;
            }
        };

        Function1<String, String> decoratedEcho = addTextDecorator.apply(echo);

        System.out.println(decoratedEcho.apply("Echo!"));
    }

}

interface Function0<ReturnType> {
    public ReturnType apply();
}

interface Function1<ArgType1, ReturnType>{
    public ReturnType apply(ArgType1 arg1);
}

abstract class Decorator implements Function0<Void>{
    private Function0<Void> func;
    public Decorator(Function0<Void> func){
        this.func = func;
    }
    public Void apply() {
        beforeAction();
        Void result = func.apply();
        afterAction();
        return result;
    }
    protected abstract void beforeAction();
    protected abstract void afterAction();
}

class PrintDecorator extends Decorator {
    public PrintDecorator(Function0<Void> func) {
        super(func);
    }
    protected void beforeAction() {
        System.out.println("Doing this action before");
    }
    protected void afterAction() {
        System.out.println("Doing this action after");
    }
}
</code>```

Running this prints:

```<code>Doing this action before
Calling my first function
Doing this action after
Before string Echo!   After string
</code>```

Title: Make functions that imply other functions

Body:
I'm developing a game that often has repetitious code that I can't simplify.

Example of what I do normally:

```<code>Square object;
GL11.glPushMatrix();   // Pushes a matrix stack down by one. This allows us to rotate our object freely
GL11.glTranslated(object.x, object.y, 0); // Move object to its position
object.drawToScreen(); // Draws the object
GL11.glPopMatrix();    // Pushes a matrix stack up by one, prevents the translation from affecting other objects in the scene
</code>```

The above code gets bulky and needs to be repeated often.

What I want to do:

```<code>Square object;
bumpMatrix()
{ // implies GL11.glPushMatrix();
GL11.glTranslated(object.x, object.y, 0); // Move object to its position
object.drawToScreen();  // Draws the object
} // implies GL11.glPopMatrix();
</code>```

Is there a way to make this happen? I swear I've seen something like it somewhere before in Java. It would allow me to make a single function and not have to Copy/Paste the same group of code several times, just call that function.

Body:
I can give you a rather generic answer that I feel is only suited to more complex use cases due to the excessive boiler plate required. You can perfectly simulate a functional paradigms in Java (they've done so in Scala) and use for example the decorator pattern to solve your problem. The general approach is to define an abstract class or an interface with a single method that then can be overwritten by an anonymous inner class.

Simple example for your use case:

public class SimpleDecorator {
    public static void main(String[] args) {
        new PrintingDecorator() {
            protected void execute() {
                System.out.println("Calling my first function");
            }
        }.apply();
        new PrintingDecorator() {
            protected void execute() {
                System.out.println("Calling my second function");
            }
        }.apply();
    }
}

abstract class PrintingDecorator {
    public void apply(){
        System.out.println("Doing this action before");
        execute();
        System.out.println("Doing this action after");
    }
    protected abstract void execute();
}

Running this prints:

Doing this action before
Calling my first function
Doing this action after
Doing this action before
Calling my second function
Doing this action after

Now you could go significantly farther and actually just define functions and such and base your decorator on that. So for the unnecessarily complex example:

public class FunctionalDecorator {
    public static void main(String[] args) {
        Function1<Function0<Void>, Function0<Void>> printDecorator = new Function1<Function0<Void>, Function0<Void>>() {
            public Function0<Void> apply(final Function0<Void> arg1) {
                Function0<Void> resultFunc = new Function0<Void>() {
                    public Void apply() {
                        System.out.println("Doing this action before");
                        arg1.apply();
                        System.out.println("Doing this action after");
                        return null;
                    }
                };
                return resultFunc;
            }
        };

        printDecorator.apply(
            new Function0<Void>() {
                public Void apply() {
                    System.out.println("Calling my first function");
                    return null;
                }
            }
        ).apply();

        //Slightly more complex example (with taking arguments and returning values)
        Function1<Function1<String, String>, Function1<String, String>> addTextDecorator = new Function1<Function1<String,String>, Function1<String,String>>() {
            public Function1<String, String> apply(final Function1<String, String> funcArg) {
                Function1<String, String> resultFunc = new Function1<String, String>() {
                    public String apply(String arg1) {
                        return "Before string\t" + funcArg.apply(arg1) + "\tAfter string";
                    }

                };
                return resultFunc;
            }
        };

        Function1<String, String> echo = new Function1<String, String>() {
            public String apply(String arg1) {
                return arg1;
            }
        };

        Function1<String, String> decoratedEcho = addTextDecorator.apply(echo);

        System.out.println(decoratedEcho.apply("Echo!"));
    }

}

interface Function0<ReturnType> {
    public ReturnType apply();
}

interface Function1<ArgType1, ReturnType>{
    public ReturnType apply(ArgType1 arg1);
}

abstract class Decorator implements Function0<Void>{
    private Function0<Void> func;
    public Decorator(Function0<Void> func){
        this.func = func;
    }
    public Void apply() {
        beforeAction();
        Void result = func.apply();
        afterAction();
        return result;
    }
    protected abstract void beforeAction();
    protected abstract void afterAction();
}

class PrintDecorator extends Decorator {
    public PrintDecorator(Function0<Void> func) {
        super(func);
    }
    protected void beforeAction() {
        System.out.println("Doing this action before");
    }
    protected void afterAction() {
        System.out.println("Doing this action after");
    }
}

Running this prints:

Doing this action before
Calling my first function
Doing this action after
Before string Echo!   After string


答:
Depends on how you load data from your config file.

Ideally, write your program to be easily testable and reduce unnecessary dependencies. So make sure that if you change the location or format of your config file, that this affects as little code as possible. Then make sure that code can also deal with the testing.

If you have a single object or class or file or set of functions that deal(s) with the loading from the config file, change that so it can take a different config file or even just stub variables programmatically without needing a config file.

If you load the config file in multiple places and its path is hardcoded, it's a bit more difficult (you're also in a not so ideal situation). You could try to:

Before the test, save your actual config file to a different location (config.back or something)

Create a new config file with the values you want

After the test, delete your newly created config file and restore the old one. Make sure to take exceptions into account!

If you just define a bunch of values in a python file and that is your config, refactor: adapt your config file so that you can change which values it returns. For example, you could create a bunch of functions to return your config values that default to your hardcoded config, but could be edited for a test program.

Title: How to write tests for function that depends on a config file?

Body: I have a function that uses information from a config file. How do I test the function? Ideally, I'd want to inject my own version of the config file and test from there, but I'm not using dependency injection.</p>


问:
Front end first or Back end first. Of the two which is a Good system design pratice?
I have a client right now requiring me to develop a school enrollment system. Now this is the first time im having this kind of challenge. Most of the past software that i created are not that complex.

I know most all of you have created complex softwares, i just want your advise on this. Should i design first the front end or back end?

thanks!

Here's a conclusion of an article I found in the internet a while ago. Just whant to share

http://www.skitoy.com/p/front-end-vs-back-end-developers-my-take/157

Front-end vs. back-end developers (my take)

My personal take

Again it’s a matter of training, some broad stroke generalizations:

Front end developers

Typically don’t have a CS degree, or
have a CS degree from a 3rd tier
school.

Work in languages that similar to
basic (see PHP is Basic)

Have a visual skill in converting
photoshop documents to CSS/HTML/etc.

Have a high tolerance for iterative
programming, due to type free
languages

Back end developers

Have a CS degree or lots of
experience

Tend to me more systematic in their
problem solving approach

Don’t mind spending days finding the
one object that is leaking

Try and build tools to solve problems

答:
Expanding on my comment:

First gather requirements, then turn them into Use Cases & design.

First comes a detailed database definition. I don't care if the client doesn't fully grok it, I force them to sit down & look at it - and sign off on it (possibly then forcing then to realize that once of their more tech savvy guys ought to do so), before proceeding.

How can you start with FE, without BE? FE for what??? Define your database!! That’s what the FE manipulates.

Ok, there will be problems & later tweaks, and I do agree that it is good to get a simple, sample, GUI in front of the client ASAP, since that particular tip of the iceberg is what most most understand.

However, I 1) stress that this is only a rough mock up, for discussion porpoises, and 2) deliberately make it ugly, but functional, so that those who don't understand can nitpick & tell me to make that input box exactly 400px wide & the background light-blue.

I fell that most answers here (and I have followed them) tend to focus too much on the customer, but, from a purely s/w point of view, I contend that you can't design a FE to manipulate a BE without first designing that BE.


答:
Sadly, nobody there elaborates on what are such cases.

I'll give some examples. All in all it is rare that forcing a GC is a good idea but it can be totally worth it. This answer is from my experience with .NET and GC literature. It should generalize well to other platforms (at least those that have a significant GC).

Benchmarks of various kinds. You want a known managed heap state when a benchmark begins so that the GC does not randomly trigger during benchmarks. When you repeat a benchmark you want the same number and amount of GC work in each repetition.

Sudden release of resources. For example closing a significant GUI Window or refreshing a cache (and thereby releasing the old potentially big cache contents). The GC cannot detect this because all you are doing is setting a reference to null. The fact that this orphans an entire object graph is not easily detectable.

Release of unmanaged resources that have leaked. This should never happen, of course, but I have seen cases where a 3rd party library leaked stuff (such as COM objects). The developer was forced to sometimes induce a collection.

Interactive applications such as games. During play games have very strict time budgets per frame (60Hz => 16ms per frame). In order to avoid hickups you need a strategy to deal with GCs. One such strategy is to delay G2 GCs as much as possible and force them at an opportune time such as a loading screen or a cut scene. The GC cannot know when the best such moment is.

Latency control in general. Some web applications disable GCs and periodically run a G2 collection while being switched out of load balancer rotation. That way the G2 latency is never surfaced to the user.

If your goal is throughput then the rarer the GC the better. In those cases forcing a collection cannot have a positive impact (except for rather contrived issues such as increasing CPU cache utilization by removing dead objects interspersed in the live ones). Batch collection is more efficient for all collectors I know of. For production app in steady-state memory consumption inducing a GC does not help.

The examples given above target consistency and boundedness of memory usage. In those cases induced GCs can make sense.

There seems to be a wide-spread idea that the GC is a divine entity that induces a collection whenever it is indeed optimal to do so. No GC I know of is that sophisticated and indeed it is very hard to be optimal for the GC. The GC knows less than the developer does. It's heuristics are based on memory counters and things like collection rate and so on. The heuristics are usually good but they do not capture sudden changes in application behavior such as release of big amounts of managed memory. It also is blind to unmanaged resources and to latency requirements.

Note, that GC costs vary with heap size and number of references on the heap. On a small heap the cost can be very small. I have seen G2 collection rates with .NET 4.5 of 1-2GB/sec on a production app with 1GB heap size.


答:
API first

Engineers from both teams should work together on the API between the front-end and the back-end. Then both teams can start working based on the designed API. This has the advantage that another front-end team can also start the work (maybe mobile, after web client) besides the obvious advantage that teams can start working in parallel.

Combine with an iterative approach and should look like this:

Design a simple API

Both teams develop and test based on the API

Integration test

Show to client and receive feedback.

Enhance API and repeat.

Title: Front end first or Back end first. Of the two which is a Good system design pratice?

Body:
I have a client right now requiring me to develop a school enrollment system. Now this is the first time im having this kind of challenge. Most of the past software that i created are not that complex.

I know most all of you have created complex softwares, i just want your advise on this. Should i design first the front end or back end?

thanks!

Here's a conclusion of an article I found in the internet a while ago. Just whant to share

http://www.skitoy.com/p/front-end-vs-back-end-developers-my-take/157

Front-end vs. back-end developers (my take)

My personal take

Again it’s a matter of training, some broad stroke generalizations:

Front end developers

Typically don’t have a CS degree, or
have a CS degree from a 3rd tier
school.

Work in languages that similar to
basic (see PHP is Basic)

Have a visual skill in converting
photoshop documents to CSS/HTML/etc.

Have a high tolerance for iterative
programming, due to type free
languages

Back end developers

Have a CS degree or lots of
experience

Tend to me more systematic in their
problem solving approach

Don’t mind spending days finding the
one object that is leaking

Try and build tools to solve problems


问:
Methods of ordering function definitions in code
When I work on some programming project (usually command line application in Python with many switches), I'm usually creating about 30 and more functions. Most of the functions are in one file (except some helpers that I utilize in more projects).

Some of the functions are called on particular switch (like -p or --print) but many functions do some helper computations, print operations or database operations because I don't want to main functions be too large.

When I have an idea for a new functionality I often put new functions randomly to the file. Should I think more about it and place it to some particular place? Are there some methods for this?

答:
I prefer the iterative refactoring approach. While we are developing the application usually our focus would be on the functionalities. Once, there is a code we could look at it and refactor it to make it more readable.

To answer your question on approach (methods for deciding where to place a code) - Ask the questions that you will ask while refactoring for the new functionality or method that you are adding to the code.


问:
Range or Row and Column Indices in VBA
I would like to know what the pros and cons are for storing a range variable instead of four integers or long variables (representing the first and last row and column) to define that range.  One could also use a single-cell range variable in combination with two integers to define the row and column to define a larger range.

Obviously, there are situations where you would need to use one method over the other.  But there are also situations where you need both the indices and the range at some point, and there are situations where either method will work (for example if you need to reference each cell in the range one by one).

So I don't need trivial pros and cons like "When you need to change the format of the entire range, reference the range.". Also, I'm only asking about which variable you would use in situations where either ranges or indices will work, or where both are needed at some point.

EDIT: I'm aware that for each will beat nested for loops at code golf in this situation, no need to mention this one or other situational code golf answers because anyone who knows how to use either method should be able to figure that out on their own.

答:
In simple VBA, it is really just a style choice since either will do the job and any performance difference will be negligible.  I can only see this question mattering in more complex scenarios.

A few things to consider:

You may need more than four integers to specify a range.  A full reference to a single cell would require a file name, a worksheet name, a row, and a column.

If you change the layout of a worksheet, it may be simpler to redefine the range once at the beginning of your function rather than to change integer values in several places.

A range can contain multiple areas. For example, you could have four cells over here and a four non-contiguous cells over there defined by one range object.

If you are doing several things to each cell (say retrieving a value, setting color, setting border, setting number format), it could be better to use a range variable (telling Excel "this spot, do this") rather than repeatedly telling Excel to "go find this sheet/row/column, do this".

If you were calling Excel from the outside using COM Automation, there may be an advantage to making your interface clearer by returning a range object (already defined in a type library) rather than an array or other user-defined data structure (that you have to define an interface for, publish a type library, or apply a custom marshaling attribute).

Title: Range or Row and Column Indices in VBA


问:
What's so bad about creative coding?
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.

答:
I think it worth completing the answers above with a quote from Alan J. Perlis, from the foreword of the well-known MIT book "Structure and Interpretation of Computer Programs", commonly called "SICP" :

Every computer program is a model, hatched in the mind, of a real or
  mental process. These processes, arising from human experience and
  thought, are huge in number, intricate in detail,and at any time only
  partially understood. They are modeled to our permanent satisfaction
  rarely by our computer programs. Thus even though our programs are
  carefully handcrafted discrete collections of symbols, mosaics of
  interlocking functions, they continually evolve: we change them as our
  perception of the model deepens, enlarges, generalizes until the model
  ultimately attains a metastable place within still another model with
  which we struggle."

Title: What's so bad about creative coding?


问:
Is this breaking SOA?
We're havng a bit of a disagreement in our team, and I would like to hear other people's views. We have a mature solution that uses an Entity Framework model, which is accessed by a repository layer, which is in turn accessed by a business logic layer. The BLL classes implement interfaces, which are also implemented by services in a WCF project. The WCF services are very thin wrappers around the BLL classes, and each service call is basically a one-liner that passes the call through to the BLL. We have a WPF project that uses the WCF services for its data access.

We have recently added an ASP.NET MVC4 project to the solution, to provide web access to some of the features in the WPF project. As the web server is on the same local network as the SQL Server database and the WCF web folder, I added a reference to the BLL project from the MVC project, and did the data access directly between the MVC controllers and the BLL classes.

Our senior technical chap objected to this, and said I was breaking SOA. He wants me to add WCF service references to the MVC project, and access the data via WCF.

My argument against this is that going via WCF does not add anything of benefit to the MVC project, but hurts the performance (I know this for a fact, as I tried it). Given that the WCF services just pass the calls straight throuh to the BLL classes, which implement the same interfaces, I don't see how it is any more SOA to use WCF than to call the BLL methods directly. Furthermore, performance is critical in this MVC project, and I don't want to do anything that will impact the performance unless there is a very good reason to do so. I can't see any good reason here. Even if we optimise the WCF project, it is still always going to be slower than accessing the BLLs directly.

According to the definitions of SOA that I've seen (for example, see the Definitions section in Wikipedia's SOA article http://en.wikipedia.org/wiki/Service-oriented_architecture), our BLLs are definitely within the pattern. I don't see any requirement to use web services to call it SOA. Sure, web services are a form of SOA, but they aren't the only form. As far as I can see, a layered approach, which ours defintely is, is completely compliant with the principle of SOA. Now I realise that I may not have put his argument very strongly, but that's mainly because I can't understand it. I'm hoping that some people who are more knowledgeable than me can come along and offer some comments one way or the other. We have a meeting to discuss this tomorrow, and I;m sure he's going to pressrue me very strongly to use WCF instead of referencing the BLLs directly. If he's right, then fair enough, we'll have to suffer the performance hit. However, if there isn't any benefit to using WCF in this case, then I need to be able to explain why the way I've done it so far is fully SOA.

I would appreciate any comments.

答:
Let me just make sure I got my assumptions correct before trying to give my opinion:
If I understand it correctly you have deployed a server which exposes its interfaces through WCF, and these interfaces matches those of your BLL. Now, you want to deploy a website that lives side-by-side with your WCF services, and that access your DAL through the BLL?

If the case is as I understood it, then I agree with your senior technical chap, simply because you will now have to make sure that the BLL libs that are deployed in both the WCF server and the ASP.NET project are always in sync. However, if the performance hit is noteworthy, then I would object against this approach since the gain is much smaller than the cost.

If however, what you want to do is have the WCF services and the ASP.NET site live side-by-side in the same IIS/Website/AppPool, then I think your senior got it wrong, and I (personally) think he got SOA all wrong.
A 'normal' service should live its own life, and - depending on how large the service is - could have a normal n-layered architecture. In an n-layered architecture you have one-or-more views, a domain, some BLL and one-or-more DAL. In this case you are simply adding a view: "Yesterday we exposed our application-logic through WCF, but now we also expose it through ASP.NET". In my opinion, going through WCF in this case, would be the same as adding a REST/JSON layer on top of a WS/SOAP layer and doing all the translation necessary between them. Why would you do this if they are really just different views of the same application?

Title: Is this breaking SOA?