问:
Cost of maintenance depending on paradigms
Is there any data on which paradigms allow for code which is easier/cheaper to maintain? Certainly, independantly of the chosen paradigm, good design is cheaper to maintain than bad, but there should probably be major differences coming only from the paradigm choice.

Unstructured programming, for instance, generates very messy code (spaghetti code) which is expensive to maintain.

In object oriented programming, implementation details are hidden and thus it should be pretty cheap to change those.

In functional programming, there are no side effects, thus there is lesser risk of introducing bugs during maintainance, which should be cheaper.

Is there any data on which paradigms are the most cost-efficient when coming down to maintenance? If no such data exists, what is your take on the question?

答:
Human beings can only manage so much complexity at a given time.

You want a paradigm that either reduces or hides the complexity away for you.

Lower complexity means more maintainability.

Lower complexity means less communication effort.

The best paradigms in terms of maintainability are those that:

hide away the complexity so you don't have to have it in your face all the time.

allows you to add functionality without modifying existing ones.

IMHO I would go with a mixture of the following:

layered architecture ( not necessarily n-tier, just don't mix business logic with presentation logic  ).

use OOP in the bussiness logic. I know encapsulation and code reuse can be achieved using non-OOP, but with OOP you have well documented patterns. You can stand on the shoulders of giants.

develop an API so programmers build apps based on that API.

make the business logic API presentation-agnostic.

try the person that developes the business logic layer is not the same one that develops the presentation layer.

I don't know if all these are "paradigms", but I think these approach would be a good balance between cost-efficient maintenance and flexibility.


问:
Calculations in Vector Register
How do vector registers work in terms of calculations and alloting data to them ?
Is there a detailed reference available somewhere explaining how vector registers work and how data is fetched from them ?</p>

答:
There are machine architecture reference manuals put out by Intel and AMD, which document (among  many other things) exactly how vector registers and instructions in modern x86-style processors work.

ARM has comparable documentation for their architecture and its associated vector processing.

ContentLicense: CC BY-SA 3.0

Title: Calculations in Vector Register


问:
Bluetooth push application
I am considering the technical viability of software that I want to write.

Is there a way that I can push data to a phone (iPhone or Andriod) via Bluetooth without pairing with it?

I want to be able to walk into a room and have a computer push data to my phone when I get a certain distance from it, or push data to any phone automatically when it comes within a certain distance to a Bluetooth-ready device?

答:
It's not clear if you want to completely skip the pairing process or just avoid having to enter in a pin.

This SO Question has a number of useful answers related to both sides of that question, albeit with an emphasis on android.  Short answer is, yes, you may be able to do what you're asking in limited circumstances.

The Wikipedia entry on Bluetooth has a number of interesting components, and I would recommend looking at section 7.3 regarding connections and bonding and section 8 regarding security.

Finally, this article goes over a number of prevalent hacks against bluetooth.  They don't tell you how, and I wouldn't encourage exploiting those vulnerabilities, but it may be enough information for you to discover a legitimate way of doing what your describing.  And honestly, it was pretty easy to google, so it's not like I'm giving away secrets here.

Title: Bluetooth push application


问:
Are there examples of non CRUD approaches?
I'm a programmer but also have worked as an archivist. As archivist it's a lot about keeping data.

I often get into arguments with colleagues when it comes to operations on data. I don't like the U and the D in CRUD too much. Rather then update a record I prefer to add a new one and have a reference to the old record. That way you build a history of changes.
I also don't like deleting records but rather mark them as inactive.

Is there a term for this? Basically only creating and reading data? Are there examples of this approach?

答:
Not precisely your example, but in older financial systems you had WORM storage.  If you needed to "update" you wrote a new record and you always referred to the last record as current but no committed data could ever be overwritten.

A lot of folks carried that idea over into later systems.  I have heard what you are describing referred to as WORM tables, but only in those circles.


问:
How can I test database access methods in Java?
I want to write a test for a method that accesses a database such as following. </p>

```<code>public class MyClass{
    public String getAddress(Int id){
        String query = "Select * from Address where id="+id;
        //some additional statements
        resultSet = statement.executeQuery();
        return result.getString(ADDRESS);
    }
}
</code>```

<p>How can I test this method? I am using Java. </p>

答: You would probably be better served to skip the integration testing for most of these methods. Instead, you would want to look into mocks and stubs (Mockito is a well-regarded mocking framework for Java) and verifying that the method behaves in the proper way. Namely, building the expected SQL for the input (on a sidenote, you should be using parameterized queries, not just concatenating strings), passing it to the correct object, and returning the correct value from the mocked up row.</p>


问:
How to reduce tight coupling between two data sources
I'm having some trouble finding a proper solution to the following architecture problem.

In our setting (sketched below) we have 2 data sources, where data source A is the primary source for items of type Foo. A secondary data source exists which can be used to retrieve additional information on a Foo; however this information does not always exist.

Furthermore, data source A can be used to retrieve items of type Bar. However, each Bar refers to a Foo. The difficulty here is that each Bar should refer to a Foo which, if available, also contains the information as augmented by data source B.

My question is: how to remove the tight coupling between SubsystemA.1 and DataSourceB?

答:
I created an app with much the same data architecture behind it; we have an onsite SQL database containing most of the automation and internal day-to-day information, and then a third-party cloud service used for sales, account management, field personnel, etc. Helpdesk needed information from both regarding clients' physical locations and equipment, and had been getting it from two different applications until I stepped in.

The long and short is that one data source needs to have a reference to the records of the other. In our case, the third-party cloud data contains references to the onsite data because that's the arrangement we had the most control over. Now, with an ID for a record from either data source, we can get data from both; with a cloud ID, we pull the record from the cloud, get the onsite ID, and pull the onsite data. With an onsite ID, we poll both data sources based on that ID.

In my system, I didn't make either object a child of the other in the domain layer; any usage of the data from both of the stores must maintain two object instances. Neither one is guaranteed to exist, which is why I did it that way; the app can work only with cloud data, or with onsite data, or both, with more limitations the less data it has.

However, that's not difficult to change, especially if you are sure that one side will always exist; simply include a property in the object representing the side for which data will always exist, that is of the object type representing the other data store's record. More advanced "merging" of the two graphs into one is possible.

This sort of arrangement must necessarily be coupled at some level. You can have a DAL that can interface with both data stores, or you can segment the DALs, one per data store, and have a higher layer such as a Controller get the data from each and snap them together. But, at some level, your program has to have the smarts to put these two disparate data sources' data together.

You can reduce the coupling required in most cases by abstracting away details of exactly where the data comes from. If you get data from a web service, which is given to you as instances of generated classes, then put a converter in place to make a deep copy of the service class into something you control, which won't have to change if the data source does (only if the schema does).

Now, this can be a huge undertaking; the cloud we use has dozens of domain classes, some of which have hundreds of data fields, and - here's the kicker - you could very easily have to make large changes to the abstract data type to accommodate a move to a different cloud or other remote data source. For that reason, I didn't bother; I use the generated web service domain directly, and now that a change from the cloud to an offsite (but under our control) data store is looming, the details of which I still do not know, I am simply planning to change the forms and codebehinds of the app, which is where the data is "combined", to reflect the new schema and/or data objects. It's a big job whichever way you slice it.


问:
What software do you use to track time spent on a project?
What software do you use to track time spent on a project?</p>

答:
I use JIRA and its associated Agile Greenhopper tool

I find it's brilliant as an electronic Kanban task/planning board and it's various burn down charts etc seem more than adequate for time keeping/reporting.

ContentLicense: CC BY-SA 2.5


问:
Moving between sites using SAML
I'm tasked with developing an SSO system, and was guided towards using the SAML spec. After some research I think understand the interaction between a Service Provider and an ID Provider and how a user's identity is confirmed. But what happens when I redirect the user to another Service Provider? How do I ascertain the user's identity there? Do I send his SAML assertion tokens along with the redirect request? Or does the second Service Provider need to contact the ID Provider all over again?

答:
Ok, it has been a little while for me but I'll try. I have worked with both SimpleSAMLphp and Shibboleth implementations of SAML. SimpleSAMLphp being the easier of the two to setup demo IdPs and SPs.

Anyway, when your user visits another SP's domain that uses the same IdP that they have already authenticated to then you can either have your IdP re-authenticate them by the cookie on their machine or force them to enter their username/password again. You can also configure how long their login session lasts on the IdP.

The way you figure out their identity on the second SP is basically the same way that you would on the first SP. You can configure what user data will be sent to each SP individually, each SP can be sent the same user data or custom user data depending on the needs of that SP.

EDIT
RE: Do I send his SAML assertion tokens along with the redirect request? Or does the second Service Provider need to contact the ID Provider all over again?

I believe the SAML spec allows both. I remember that I could have the user visit the second SP's domain where the SP would then hit the IdP to get the assertion tokens or you can have the user visit the IdP first with a query string identifying the second SP and then redirect the user to the second SP along with the assertion tokens.

EDIT#2 By the way I would recommend NOT writing your own implementation of SAML unless you have a lot of time and other team members helping. Heck, last I checked Shibboleth didn't have a full implementation of the SAML spec, and they are the "SAML people." In addition, you may run into interoperability issues if you plan on supporting 3rd party SPs or IdPs if you have a custom written implementation.

Title: Moving between sites using SAML


答:
From this paper, it appears functional programming and object oriented programming offer good readability and maintainable code.  Imperative programming scores low on maintainability as it becomes difficult to reuse sections of large programs.  Structured programming suffers from low maintainability by being hard to make revisions once the program is written.

FWIW, from my experience, I have hated working on programs that have been written with a rigid, top-down approach.  Especially so when the original developers were not around.

Title: Cost of maintenance depending on paradigms

Body:
Is there any data on which paradigms allow for code which is easier/cheaper to maintain? Certainly, independantly of the chosen paradigm, good design is cheaper to maintain than bad, but there should probably be major differences coming only from the paradigm choice.

Unstructured programming, for instance, generates very messy code (spaghetti code) which is expensive to maintain.

In object oriented programming, implementation details are hidden and thus it should be pretty cheap to change those.

In functional programming, there are no side effects, thus there is lesser risk of introducing bugs during maintainance, which should be cheaper.

Is there any data on which paradigms are the most cost-efficient when coming down to maintenance? If no such data exists, what is your take on the question?


问:
How to TDD test that objects are being added to a collection if the collection is private?
Assume that I planned to write a class that worked something like this:

```<code>public class GameCharacter {
    private Collection<CharacterEffect> _collection;

    public void Add(CharacterEffect e) { ... }
    public void Remove(CharacterEffect e) { ... }
    public void Contains(CharacterEffect e) { ... }
}
</code>```

When added an effect does something to the character and is then added to the _collection.  When it is removed the effect reverts the change to the character and is removed from the _collection.

It's easy to test if the effect was applied to the character, but how do I test that the effect was added to _collection?

What test could I write to start constructing this class.  I could write a test where Contains would return true for a certain effect being in _collection, but I can't arrange a case where that function would return true because I haven't implemented the Add method that is needed to place things in _collection.

Ok, so since Contains is dependent on having Add working, then why don't I try to create Add first.  Well for my first test I need to try and figure out if the effect was added to the _collection.  How would I do that?  The only way to see if an effect is in _collection is with the Contains function.

The only way that I could think to test this would be to use a FakeCollection that Mocks the Add, Remove, and Contains of a real collection, but I don't want _collection being affected by outside sources.  I don't want to add a setEffects(Collection effects) function, because I do not want the class to have that functionality.  The one thing that I am thinking could work is this:

```<code>public class GameCharacter<C extends Collection> {
    private Collection<CharacterEffect> _collection;

    public GameCharacter() {
        _collection = new C<CharacterEffect>();
    }
}
</code>```

But, that is just silly making me declare what some private data structures type is on every declaration of the character.

Is there a way for me to test this without breaking TDD principles while still allowing me to keep my collection private?

答:
You shouldn't test classes but interfaces where by interface, beside the typical meaning, you could also understand the signatures of the public methods of a class. Your classes should adhere to strong contracts; from the testing point of view (and from other clients' POV) you shouldn't care how those contracts are respected/implemented.

In your particular case there is a problem with your class design; your add method does two things: firstly it changes the CharacterEffect and then it adds that object to the collection of character effects. This bad design decision makes it difficult to test!

If you really want to see a private field, you can use reflection, but that is not an orthodox way of doing things.


答:
You seem to understand the incremental part of TDD, that is to implement the smallest possible functionality at a time. However, there are cases like the one you are facing that make it extremely difficult to do. In your particular situation, I would not bother trying to implement them separatly and I would implement Add and Contains at the same time.

The typical TDD cycle starts with : Write your test and make it compile. In your case, your test would look like so :

```<code>var g = new GameCharacter();
var c = new CharacterEffect();
g.Add(c);
Assert.That(g.Contains(c));
</code>```

In order to make your test compile (step 2), you have to implement both Add and Contains, which I think is perfectly fine. TDD says that you should take the smallest step possible, and this seems to be the smallest you can do. You don't need to go crazy about implementing every method individually or you will likely hit the same walls again and again.

Title: How to TDD test that objects are being added to a collection if the collection is private?

Body:
Assume that I planned to write a class that worked something like this:

```<code>public class GameCharacter {
    private Collection<CharacterEffect> _collection;

    public void Add(CharacterEffect e) { ... }
    public void Remove(CharacterEffect e) { ... }
    public void Contains(CharacterEffect e) { ... }
}
</code>```

When added an effect does something to the character and is then added to the _collection.  When it is removed the effect reverts the change to the character and is removed from the _collection.

It's easy to test if the effect was applied to the character, but how do I test that the effect was added to _collection?

What test could I write to start constructing this class.  I could write a test where Contains would return true for a certain effect being in _collection, but I can't arrange a case where that function would return true because I haven't implemented the Add method that is needed to place things in _collection.

Ok, so since Contains is dependent on having Add working, then why don't I try to create Add first.  Well for my first test I need to try and figure out if the effect was added to the _collection.  How would I do that?  The only way to see if an effect is in _collection is with the Contains function.

The only way that I could think to test this would be to use a FakeCollection that Mocks the Add, Remove, and Contains of a real collection, but I don't want _collection being affected by outside sources.  I don't want to add a setEffects(Collection effects) function, because I do not want the class to have that functionality.  The one thing that I am thinking could work is this:

```<code>public class GameCharacter<C extends Collection> {
    private Collection<CharacterEffect> _collection;

    public GameCharacter() {
        _collection = new C<CharacterEffect>();
    }
}
</code>```

But, that is just silly making me declare what some private data structures type is on every declaration of the character.

Is there a way for me to test this without breaking TDD principles while still allowing me to keep my collection private?

Body:
You seem to understand the incremental part of TDD, that is to implement the smallest possible functionality at a time. However, there are cases like the one you are facing that make it extremely difficult to do. In your particular situation, I would not bother trying to implement them separatly and I would implement Add and Contains at the same time.

The typical TDD cycle starts with : Write your test and make it compile. In your case, your test would look like so :

var g = new GameCharacter();
var c = new CharacterEffect();
g.Add(c);
Assert.That(g.Contains(c));

In order to make your test compile (step 2), you have to implement both Add and Contains, which I think is perfectly fine. TDD says that you should take the smallest step possible, and this seems to be the smallest you can do. You don't need to go crazy about implementing every method individually or you will likely hit the same walls again and again.


问:
Should I change language to stop becoming stale?
I'm an ASP.Net/C# programmer using SQL Server as a back end.

I am the Technical Director of the company, I'm extremely happy in everything I do and consider the languages and system we use to be perfect for what we do.

In the back of my mind though I know that over time programmers can become stale. I remember as a wee youngster that all those "old" developers were past it and couldn't keep up with the youngsters.

So considering I'm happy in everything I'm doing. What options are there for keeping up with everything and avoiding becoming stale.

One particular idea that I use is to let all the new developers use and showcase the things that they think are cool. If anything catches my eye then absolutely it will be something we all use going forward.

Thoughts?

答:
It can be interesting to do as a hobby and you can gain some good insights. You might even decide that you like the "new way" of doing things better than the old way. However, from personal experience I would caution against taking a job change to work on a new language. Not to say that it won't work for everyone, but it certainly didn't for me.

I've been working in Objective-C on NeXT/Mac/iOS for countless aeons, and aside from a little dabbling - in numerous languages but mainly Python and Java - that's been my bread and butter. I decided it would be worth diving into Java more fully to see how it differed and maybe gain some knowledge I could use in ObjC, and got a job as a Java engineer. Fast-forward two months and I had already quit.

The thing is, it can be hard to find time (or I find it hard, anyway) to work on programming projects outside work, because that's supposed to be unwinding time. If you are self-employed or can agree it with your manager, setting aside some research time during your working hours can be the best way to go.


答:
EventSourcing sounds like the pattern that you may be looking for.

Let's take an example using a simple "car" object that we would want to keep track of the color of (pseudo C# code follows).

```<code>public class Car {
  public string Color { get; set; }
  public Car() { this.Color = "Blue"; }
}
</code>```

With a CRUD implementation when we update the color of the car the previous color would be lost.

```<code>MyCar.Color = "Red";
MyCar.Save();  // Persist the update to the database and lose the previous data
</code>```

This loss of information sounds to me like what you would like to avoid the most (hence the dislike for the update and delete part of the CRUD pattern).

If we were to rewrite the car class to instead respond to events when updating its change it may look like this:

```<code>public class Car {
    public string Color { get; private set; } // Cannot be set from outside the class

    public void ApplyEvent(CarColorChangedEvent e) {
      this.Color = e.Color;
    }
}
</code>```

Now how would we update the color of this object? We could create a CarColorChanged event!

```<code>var evnt = new CarColorChangedEvent("Red");
MyEventStore.save(evnt);
MyCar.ApplyEvent(evnt);
</code>```

Notice the lack of a save on the actual model object? That's because instead of persisting the model directly we persist the events that put the model to the current state. These events should be immutable.

Now's let's fast forward and change the color a few more times:

```<code>var evnt = new CarColorChangedEvent("Green");
MyEventStore.save(evnt);
MyCar.ApplyEvent(evnt);

var evnt = new CarColorChangedEvent("Purple");
MyEventStore.save(evnt);
MyCar.ApplyEvent(evnt);
</code>```

If we were to look at our event storage (could be a relation database, file based, etc..) we would see a series of events relating to our car object:

```<code>CarColorChangedEvent => Red
CarColorChangedEvent => Green
CarColorChangedEvent => Purple
</code>```

If we wanted to rebuild that car object we could do so simply by creating a new car object and applying the events from our eventstore to said object.

```<code>var MyCar = new Car();
var events = MyDatabase.SelectEventsForCar("CarIdentifierHere");
foreach(var e in events) {
  MyCar.ApplyEvent(e);
}
Console.WriteLine(MyCar.Color); // Purple
</code>```

With the stream of events we can roll back the state of the car to a previous time period simply by creating a new car object and only apply the events that we want:

```<code>var MyCar = new Car();
var event = MyDatabase.GetFirstEventForCar("CarIdentifierHere");
MyCar.ApplyEvent(e);
Console.WriteLine(MyCar.Color); // Red
</code>```

Title: Are there examples of non CRUD approaches?

Body:
I'm a programmer but also have worked as an archivist. As archivist it's a lot about keeping data.

I often get into arguments with colleagues when it comes to operations on data. I don't like the U and the D in CRUD too much. Rather then update a record I prefer to add a new one and have a reference to the old record. That way you build a history of changes.
I also don't like deleting records but rather mark them as inactive.

Is there a term for this? Basically only creating and reading data? Are there examples of this approach?

Body:
EventSourcing sounds like the pattern that you may be looking for.

Let's take an example using a simple "car" object that we would want to keep track of the color of (pseudo C# code follows).

public class Car {
  public string Color { get; set; }
  public Car() { this.Color = "Blue"; }
}

With a CRUD implementation when we update the color of the car the previous color would be lost.

MyCar.Color = "Red";
MyCar.Save();  // Persist the update to the database and lose the previous data

This loss of information sounds to me like what you would like to avoid the most (hence the dislike for the update and delete part of the CRUD pattern).

If we were to rewrite the car class to instead respond to events when updating its change it may look like this:

public class Car {
    public string Color { get; private set; } // Cannot be set from outside the class

    public void ApplyEvent(CarColorChangedEvent e) {
      this.Color = e.Color;
    }
}

Now how would we update the color of this object? We could create a CarColorChanged event!

var evnt = new CarColorChangedEvent("Red");
MyEventStore.save(evnt);
MyCar.ApplyEvent(evnt);

Notice the lack of a save on the actual model object? That's because instead of persisting the model directly we persist the events that put the model to the current state. These events should be immutable.

Now's let's fast forward and change the color a few more times:

var evnt = new CarColorChangedEvent("Green");
MyEventStore.save(evnt);
MyCar.ApplyEvent(evnt);

var evnt = new CarColorChangedEvent("Purple");
MyEventStore.save(evnt);
MyCar.ApplyEvent(evnt);

If we were to look at our event storage (could be a relation database, file based, etc..) we would see a series of events relating to our car object:

CarColorChangedEvent => Red
CarColorChangedEvent => Green
CarColorChangedEvent => Purple

If we wanted to rebuild that car object we could do so simply by creating a new car object and applying the events from our eventstore to said object.

var MyCar = new Car();
var events = MyDatabase.SelectEventsForCar("CarIdentifierHere");
foreach(var e in events) {
  MyCar.ApplyEvent(e);
}
Console.WriteLine(MyCar.Color); // Purple

With the stream of events we can roll back the state of the car to a previous time period simply by creating a new car object and only apply the events that we want:

var MyCar = new Car();
var event = MyDatabase.GetFirstEventForCar("CarIdentifierHere");
MyCar.ApplyEvent(e);
Console.WriteLine(MyCar.Color); // Red


问:
Sending files via HTTP to web service
I am bit frustrated at the lack of information about this online. Here is the issue:

I am in charge of creating a iOS application which sends sound data back and forth between the server and the app. The Audio is in small files and thus does not need to be streamed over, but rather it can be sent. Right now, I am using a TCP server I wrote to handle applications like this. However, I want to keep the system as simple as possible and writing your own server and client sockets can get a bit complex and leaves room for crashes. Overall it slows down development because I need to account for packet structure and other things.

My question is, can I write an ASPX or PHP web service that lets me pass the files back and forth through GET or POST?

答:
For the ASP side, sure you can write web services that will allow you to do what you're suggesting.  The latest and greatest of ASP.NET has some enhancements to help simplify the whole web services approach.

It's not the most efficient route, but it will work for your requirements.  This page from the ASP.NET site has a few tutorials that appear directly related to what you're trying to do.

You'll still need to have the client handle wrapping up the sound objects and then pushing them through the HTTP request.

Title: Sending files via HTTP to web service


答:
Where are you searching for information and not finding it? Uploading a file to a PHP webpage is a topic that has been covered quite a few times on the web over the years. So much so that even w3schools has a example.

From the client side (HTML example but it is just a basic HTTP POST):

```<code><form action="http://example/com/upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>
</code>```

The server side of things in PHP:

```<code><?php
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "<br />";
    } else {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
?>
</code>```

As far as sending the files back to the client simply store the in a web assecible location and it is a basic GET request:

```<code>GET http://example.com/myfile.wav
</code>```

Title: Sending files via HTTP to web service

Body:
I am bit frustrated at the lack of information about this online. Here is the issue:

I am in charge of creating a iOS application which sends sound data back and forth between the server and the app. The Audio is in small files and thus does not need to be streamed over, but rather it can be sent. Right now, I am using a TCP server I wrote to handle applications like this. However, I want to keep the system as simple as possible and writing your own server and client sockets can get a bit complex and leaves room for crashes. Overall it slows down development because I need to account for packet structure and other things.

My question is, can I write an ASPX or PHP web service that lets me pass the files back and forth through GET or POST?

Body:
Where are you searching for information and not finding it? Uploading a file to a PHP webpage is a topic that has been covered quite a few times on the web over the years. So much so that even w3schools has a example.

From the client side (HTML example but it is just a basic HTTP POST):

<form action="http://example/com/upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

The server side of things in PHP:

<?php
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "<br />";
    } else {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
?>

As far as sending the files back to the client simply store the in a web assecible location and it is a basic GET request:

GET http://example.com/myfile.wav


答:
You actually don't have to do any of the work if you don't want to. I agree with the previous comment -- don't build a SAML library -- they exist in many shapes and forms.

Read this to start with:  https://wiki.shibboleth.net/confluence/display/SHIB2/UnderstandingShibboleth

SSO is out of the box with Shibboleth so you don't have to even monkey with trying to re-invent the wheel either.  If you want a full walk through of this, read the training material which will walk you through an entire install for the IdP and a Drupal SP:

https://spaces.internet2.edu/display/ShibInstallFest/Shibboleth+Workshop+Series+-+Linux+Identity+Provider+%28Centos+6.2%29

You will need to work out how you want to register the trust for your 'internal federation of IdP & SP' but that is a small piece of the puzzle in the grand scheme of things.

So your questions are:

But what happens when I redirect the user to another Service Provider?
Ans: the SP software will intercept the request and validate if the user is logged in. If not, redirection occurs.  If so, the SP configuration will be the gate for attributes being released (usually after the IdP releases the attributes to it).

How do I ascertain the user's identity there?
Ans:  see above.  Choose your identifier wisely.  Highly recommended to NOT use email as the identifier. TL;DR is email changes and it's a bad choice.

Do I send his SAML assertion tokens along with the redirect request?

Ans:  you don't care.  Let the Idp+SP software deal with it. Read the docs if you need to go deeper into what happens, but app folks don't need to be bothered with it.

Or does the second Service Provider need to contact the ID Provider all over again?

Ans:  The IdP is consulted to retrieve attribute information when the user has signed in properly.

The 'I'm tasked with developing an SSO system' likely needs some planning and scale considerations (e.g. technology, # of sites etc, user audience plus a number of other planning questions).  It would be healthy to nail those down :)

Title: Moving between sites using SAML

Body: I'm tasked with developing an SSO system, and was guided towards using the SAML spec. After some research I think understand the interaction between a Service Provider and an ID Provider and how a user's identity is confirmed. But what happens when I redirect the user to another Service Provider? How do I ascertain the user's identity there? Do I send his SAML assertion tokens along with the redirect request? Or does the second Service Provider need to contact the ID Provider all over again?


答:
Event Sourcing is the way to go, and you should take a look at what Greg Young has to say about that.

http://goodenoughsoftware.net/

Also take a look at this presentation on his Database (Event Store). You can find other videos as well.

http://oredev.org/2012/sessions/a-deep-look-into-the-event-store

I wouldn't go for the "soft-deletes" answer unless you specifically need to be able to search for deleted items, but then you shouldn't think of them as deleted but rather archived. I think terminology is quite important here.

I would not want to maintain a "version table" either. All the "version tables" I have ever seen (including the on I am trying to clean up at the moment - 7 years of data corrupted because of bugs... and no way to get that back even though we have historical data... because that is just as corrupt) end up corrupted due to bugs in code and in the end you still lose data because you can't ever go back and recreate the data that the corruption messed up.

With the event sourcing model this isn't the case. You can always replay exactly what the user did. This is the very important difference between CRUD and Event Sourcing. The Event Sourcing architecture saves events in an event store, and not data objects or domain model objects. An event could easily impact multiple objects. Just think of a shopping cart solution where you convert each item in the shopping cart into an actual order. One event impacts all the item objects as well as the shopping cart objects, which is transformed into an order object.

If you kept a versioned copy of each row in every table in the database, then imagine the horror of having to rewind to a specific timestamp, not to mention the insane amount of space and performance overhead in maintaining that version table.

With Event Sourcing, you can easily rewind, by just replaying events until a certain point in time. Fast forwards can be put in place by using snapshots, but that's all a matter of implementation.

But the real advantage that I think you will like, seing as you are particularly interested in not losing data, is that if you discover a bug in the code that saves this data, then you don't need to go back and clean the data (which is often impossible because data is almost never complete). Instead just fix the bug, and replay all the events. Then you will have a database with nice correct data.

In case of debugging, how often have you asked the user to tell you what they did... why not just replay what they did and then stepping through the code! Pretty nifty huh.

Hope this helps.


问:
Is this an example of a composition or aggregation?
Composition and aggregation both are confusion to me. Does my code sample below indicate composition or aggregation?

```<code>class A {
     public static function getData($id) {
         //something
     }

     public static function checkUrl($url) {
         // something
     }

 class B {
    public function executePatch() {
           $data = A::getData(12);
     }

    public function readUrl() {
           $url = A::checkUrl('http/erere.com');
     }

    public function storeData() {
            //something not related to class A at all
     }
  }
}
</code>```

Is class B a composition of class A or is it aggregation of class A? Does composition purely mean that if class A gets deleted class B does not works at all and aggregation if class A gets deleted methods in class B that do not use class A will work?

答:
In PHP 5.4 there was introduced an additional mechanism allowing composition called "traits" so your example could be something like

```<code>trait A {
  public static function getData($id) {
    //something
  }

  public static function checkUrl($url) {
    // something
  }
}

class B {
  use A;
}
</code>```

You cannot instantiate trait so

```<code>$a = new A();
</code>```

would not work and you can use several traits within one class

Body:
In PHP 5.4 there was introduced an additional mechanism allowing composition called "traits" so your example could be something like

trait A {
  public static function getData($id) {
    //something
  }

  public static function checkUrl($url) {
    // something
  }
}

class B {
  use A;
}

You cannot instantiate trait so

$a = new A();

would not work and you can use several traits within one class


问:
How to find out if a company has insane policies
When interviewing for a job, is there a delicate yet accurate way to find out if they have insane policies, like "no open source", or "no installing software without permission", "not upgrading software until it's about to lose support", or "no visiting blogs"?</p>

答:
From my experience in working at in house IT at large companies  (banks, insurance etc.)

"no open source", - this is not in anyway insane policy. Depending on the OSS license this kind be quite valid. Saving money (up to a reasonable limit) is not usually a big problem as every project has a budget and as long as you can fit in it is OK.

"no installing software without permission" - this is very valid from infrastructure support, security and legal perspective. e.g. Installing wireshark can lead to dismissal.

"not upgrading software until it's about to lose support" - depends on which software. If it still using VS 2003/2005 for development team yes. If you are talking about upgrading 10000 desktops from XP to windows 7 and office 2010 then not. Those needs business justification.

"no visiting blogs"? - yes this is a bad policy.


问:
Is file system one of the NoSQL? What's the main difference?
I am confused about it.

I can use lucene to create index and run query against file system.
I can find any particular file very fast, if I can provide a primary key, in this case, directory path and filename act as primary key.

It looks very much like a NoSQL.

答:
A (Unix) file system is a hierarchical database for unstructured untyped data. The  BeFS is more like a metadata-addressable graph of semi-structured data. The VMS filesystem is a hierarchical database for semi-structured versioned data. The OS/400 filesystem is actually pretty close to SQL in its semantics. Different filesystems are very different!

NoSQL is a movement that advocates choosing the best-fitting database technology for your data model. (NoSQL == Not Only SQL)

If you have tree-shaped unstructured data, then storing it in the (Unix) filesystem definitely fits the goals of the NoSQL movement. If your data however is relational, then choosing the filesystem is actually exactly the opposite of NoSQL: remember, NoSQL means choosing the best-fitting database technology for your data model, and if your data is relational, then that model is SQL.


答:
Have your unit tests be implemented in a friend class.

That lets you poke into private and protected stuff freely for the purposes of the unit test without having to make it part of the external API.


问:
How to handle monetary values in PHP and MySql?
I've inherited a huge pile of legacy code written in PHP on top of a MySQL database. The thing I noticed is that the application uses doubles for storage and manipulation of data.

Now I came across of numerous posts mentioning how double are not suited for monetary operations because of the rounding errors. However, I have yet to come across a complete solution to how monetary values should be handled in PHP code and stored in a MySQL database.

Is there a best practice when it comes to handling money specifically in PHP?

Things I'm looking for are:

How should the data be stored in the database? column type? size?

How should the data be handling in normal addition, subtraction. multiplication or division?

When should I round the values? How much rounding is acceptable if any?

Is there a difference between handling large monetary values and low ones?

Note:
A VERY simplified sample code of how I might encounter money values in everyday life (various security concerns were ignored for simplification. Of course in real life I would never use my code like this):

```<code>$a= $_POST['price_in_dollars']; //-->(ex: 25.06) will be read as a string should it be cast to double?
$b= $_POST['discount_rate'];//-->(ex: 0.35) value will always be less than 1
$valueToBeStored= $a * $b; //--> any hint here is welcomed

$valueFromDatabase= $row['price']; //--> price column in database could be double, decimal,...etc.

$priceToPrint=$valueFromDatabase * 0.25; //again cast needed or not?
</code>```

I hope you use this sample code as a means to bring out more use cases and not to take it literally of course.

Bonus Question
If I'm to use an ORM such as Doctrine or PROPEL, how different will it be to use money in my code.

答:
It can be quite tricky to handle numbers with PHP/MySQL. If you use decimal(10,2) and your number is longer or has higher precision it will be truncated without error (unless you set proper mode for your db server).

To handle large values or high precision values you can use library like BCMath it will allow you to make basic operation on the large numbers and keep required precision.

I'm not sure what exactly calculations you will make but you have to also keep in mind that (0.22 * 0.4576) + (0.78 * 0.4576) will not equal 0.4576 if you will not use proper precision through the process.

Maximum size of DECIMAL in MySQL is 65 so it should be more than enough for any purpose. If you use DECIMAL field type it will be returned as string regardless of the use of an ORM or just plain PDO/mysql(i).

How should the data be stored in the database? column type? size?

DECIMAL with precision you need. If you are using exchange rates then you will need at least four decimal places

How should the data be handling in normal addition, subtraction. multiplication or division?

Use BCMath to be on save side and why using float may not be a good idea

When should I round the values? How much rounding is acceptable if any?

For monetary values normal two decimal places are acceptable but you may need more if for example you are using exchange rates.

Is there a difference between handling large monetary values and low ones?

Depends on what you mean by large. There is definitely a difference between handling numbers with high precision.


问:
Why do game developers prefer Windows?
Is it that DirectX is easier or better than OpenGL, even if OpenGL is cross-platform? Why do  we not see real powerful games for Linux like there are for Windows?</p>

答:
Tools, tools, tools.

That's what it comes down to.  Develop on Windows and you get access to some of the best development tools on the planet.  Nothing comes even remotely close to Visual Studio's debugger, the DirectX Debug Runtimes are awesome, PIX is awesome, and comparable equivalents just don't exist on other platforms/APIs.  Sure, there is some good stuff there; I'm not saying that the tools on other platforms are bad, but those that MS provide are just so far ahead of the pack (honourable exception: Valgrind) that it's not even funny.

Bottom line is that these tools help you.  They help you get stuff done, they help you be productive, they help you focus on errors in your own code rather than wrestle with an API that never quite behaves as documented.

Title: Why do game developers prefer Windows?


问:
How would you react if someone told you your code is a mess?
I am a good programmer, or so I thought before. I always love to program. And I want to learn many things about programming to make me a better programmer. I studied programming for 1 year and now I am working as a programmer for almost 2 years. So in short, I have almost 3 years programming experience.

Our team is composed of 5 programmers, and 4 of us are new, 1 has more than 3 year experience. We've been working for a program for almost a year now and nobody ever review my code and I was given a page to work with. We never had a code review and we are all new so we don't know what is a clean code looks like. I think programmers learn by themselves?

We deployed our program to the program without thorough testing. Now it is tight and we need an approval and code review first before we make changes with the code. For the first time, someone reviews my code and he says it is a mess.

I feel so sad and hurt. I really love programming and making them say something like that really hurts me. I really want to improve myself. But it seems like I'm not a genius programmer like in the movies. Can you give me advise on how to be better? Have you ever experience something criticizing your code and you feel really hurt? What do you do on those events.

答:
The truth is that probably in 2 years when you will see your current code you will agree that it was a mess. Learning programming is a never ending process and there will always be someone who is better at it than you.

So if person who said that your code is a mess is not just mean and it is not another case of "I would do it better" disease common among programmers you should ask him/her what exactly is wrong with your code and how can you improve it.


答:
I feel so sad and hurt. I really love programming and making them say
  something like that really hurts me. I really want to improve myself.

That is good. That is a lot better than having a reaction like "my reviewer has no idea what he is talking about", "my reviewer is too picky" or just "my reviewer doesn't like me" and ignoring them. This attitude is a good thing.

But it seems like I'm not a genius programmer like in the movies.

Not sure what kind of movies you watch, but 90% of the programmers in the movies are so fake I have tears by the end of the sequence.

Can you give me advise on how to be better?

Read and practise. Check out books like Code Complete or The Pragmatic Programmer. Look on Amazon for similar books.

Have you ever experience something criticizing your code and you feel
  really hurt? What do you do on those events..

Why do you feel hurt? I feel disappointed in myself for being such a moron in the first place. I use that motivation to clean up my code and make sure I don't make the same mistake again. The last thing I want to do it not learn from it. You have been put down once, don't let it happen again for the same reason.

No programmer is born perfect, or even close. The more code your write, the more reviews you get and reviews you provide, will make you an all-round better programmer.

Title: How would you react if someone told you your code is a mess?

Body:
I am a good programmer, or so I thought before. I always love to program. And I want to learn many things about programming to make me a better programmer. I studied programming for 1 year and now I am working as a programmer for almost 2 years. So in short, I have almost 3 years programming experience.

Our team is composed of 5 programmers, and 4 of us are new, 1 has more than 3 year experience. We've been working for a program for almost a year now and nobody ever review my code and I was given a page to work with. We never had a code review and we are all new so we don't know what is a clean code looks like. I think programmers learn by themselves?

We deployed our program to the program without thorough testing. Now it is tight and we need an approval and code review first before we make changes with the code. For the first time, someone reviews my code and he says it is a mess.

I feel so sad and hurt. I really love programming and making them say something like that really hurts me. I really want to improve myself. But it seems like I'm not a genius programmer like in the movies. Can you give me advise on how to be better? Have you ever experience something criticizing your code and you feel really hurt? What do you do on those events.


答:
One of the best things to me about being a developer is that every day is a learning process. There will always be someone out there who doesn't know something which you do, and there will always be someone who knows something which you don't. I certainly wouldn't consider myself to be anywhere but at an entry/junior level, but I appreciate any criticism I can get as long as it is both justified and given with respect.

An analogy that might be fitting relates to a time period in which I was a writing tutor at a university, as well as when I took part in creative writing courses. Writing code, for all intents and purposes, is much like writing a poem, essay, short story, or novel. Each individual has their own way of going about doing it, but at the same time, even the best writers (or, in this case, developers) make mistakes or let things slip through the cracks. We can often fail to notice these things because we become so used to our own voice (or again, in this case, style of code).

Much like in any field, there are those who are considered to be experts. If those people didn't exist, we wouldn't have anyone to learn from. Assuming this individual in question is truly an expert, I would listen to what he says and ask what he would suggest you do to improve upon your code. Never forget, though, that he is not the only one who can give his assistance; we have the good fortune that a plethora of resources such as SE/SO exist.


答:
After 20+ years I know that some of my own code is still a mess.  What it comes down to is making a decision between writing the best possible code versus writing what's required to get the job done.  Getting the job done within an agreed timeframe trumps the never-ending quest for technical perfection any day.

The trick is to learn to accept it.  Learn to accept that you could do better.  Learn to live with the flaws.  Learn to accept that you're not going to get it perfect this time, and probably the next time too, and that it's a deliberate choice because the alternative is not delivering.  And that's worse.

Disclaimer: none of this should be read as "bad code is OK".


答:
Don't let your emotions get in the way of improving your code.  The goal of a code review is to find problems, so you shouldn't be too surprised if there are some.  That said, they aren't supposed to be a coder-bashing session either.

They also shouldn't be just saying 'Ewwww' and leaving it at that.  There is always a reason why something is wrong in programming.  For instance, it's wrong to leave lots of commented-out code all over the place, but it's wrong because it clutters up the code and makes it harder to read, not because somebody said so in a book.

Your code is not you.  Remember that.


答:
Fortunately, Excel or OpenOffice Calc is all I need. That's because I'm not working on many projects in parallel.

In my previous job, we were using a in-house developed tool, sort of like Jira, to keep track of every single minute spent on one of several projects I had to work on concurrently. It's hard to say what was more annoying, the micromanagement that came with the tool (5 minutes spent on stackexchange?!?) or the fact that I couldn't focus on one project for at least a few days without getting interrupted by urgent tasks for other projects.

Body: What software do you use to track time spent on a project?</p>


答:
Don't take pride in how well you code.  Take pride in how well you learn.  Then learning that your code needs improvement provides you with an opportunity to demonstrate how good you are at learning, instead of coming across as criticism of how bad a programmer you are.

Read http://www.perlmonks.org/?node_id=270083 if you have no idea what I'm talking about.


答:
Mess is rather subjective. The best thing you can do is to actually ask that person (or the review report): why is it messy? (from their point of view, that is)

They're bound to answer you and you'll be able to either:

Argument against it (if you have a good reason to do so, of course)

Feel very happy, because you just learned something new and your future code is bound to be more awesome since you now know how to make it less messy thanks to their advice.


答:
Well, a person saying your code is a mess is not constructive, even if they're right. Did they give you reasons why it's a mess? Like, methods are too long, responsibilities mixed together, too much branching, etc. Honestly, any code I wrote a year ago I would say is complete crap because I've learned a ton since then. So don't feel bad about it. I would be more worried if you still liked reading the code you wrote that long ago.

The cleaner your code-base is, the less time you spend on fighting the code-base to solve a given problem. A year is a great point to be at because you can feel the pains of any design decisions you made earlier in the project.

On my current project, we've refactored several times as we got more comfortable with our technology stack. This should be encouraged and you should make note of tasks that take longer than they should because of present code-base.

Have you gone over some of the older parts of the code you wrote? You can probably see things you'd want to do differently now or refactor.

Also when you mention a lack of testing, this is always something to look at. On our project we had no automated testing and as a result a lot of highly coupled code. Even if you don't write unit/integration/whatever tests regularly, doing it for a little while will get you in the habit of making your code more modular (and consequently, less of a mess).


答:
First of all, you must understand that programming is an iterative process, much like writing an article or a book. First you write a "rough draft" of your program, just to get it to work.  At this stage, your code will be a mess. So you refactor to make the code clean.  Then you profile and see what you need to optimize to make it fast.  The trick is to refactor continuously, otherwise the mess will grow.  You have to clean your code regularly, just like you have to clean your house.

Code reviews are absolutely essential. You must have your code looked at by at least one other pair of eyes. When you spend countless hours looking at your code, you get used to it, and you can easily miss a bug or a code smell that your coworker might notice instantly.

Also, the act of explaining your code to someone else is a great way to see if you have missed anything. This is like reading a paper you are writing out loud. Your brain processes audio and visual information in different ways, and you can find flaws in your reasoning by switching modality. Also, if you explain your code to a coworker, and something does not make sense to her, that is a good indication that you should refactor your code.

When doing a code review it is very important for both the author and the reviewer to check their egos at the door. The goal is to make the code better. So the reviewer must be respectful, and the author must keep an open mind.  Remember, your co-workers are the ones who will have to maintain your code, so it must be clear to them. If the reviewer does not understand what a variable does, rename it. If the reviewer can't understand what a block of code does, refactor it into a function with a descriptive name.  Irrespective of what you may think, if your co-workers cannot understand your code, it is not good.

Speaking of refactoring, you absolutely must have a unit test framework, because without it, you cannot refactor.

Finally, I highly recommend reading "Clean Code" by Robert C. Martin.  It will tell you why your code is a mess, and what you can do to clean it up.


答:
Another choice would convert the file content to base64 and submit it as form field.

In PHP the code would:

```<code><?php
$data = file_get_contents('path_to_file');
$encripData = base64_encode($data);

$filename = 'my_file.txt';

$fields = array(
    'content'    =>   $encripData,
    'name'       =>   $filename,
);

$fieldsQueryString = http_build_query($fields);

// you should have curl library install here
$ch = curl_init("http://myserver/receive.php");
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsQueryString);

curl_exec($ch);
</code>```

The script PHP to receive the file will be:

```<code><?php

$content = $_POST['content'];
$name = $_POST['name'];

file_put_contents($name, base64_decode($content));
</code>```

I not tested it code but is a good idea of the implement.

Title: Sending files via HTTP to web service

Body:
Another choice would convert the file content to base64 and submit it as form field.

In PHP the code would:

<?php
$data = file_get_contents('path_to_file');
$encripData = base64_encode($data);

$filename = 'my_file.txt';

$fields = array(
    'content'    =>   $encripData,
    'name'       =>   $filename,
);

$fieldsQueryString = http_build_query($fields);

// you should have curl library install here
$ch = curl_init("http://myserver/receive.php");
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsQueryString);

curl_exec($ch);

The script PHP to receive the file will be:

<?php

$content = $_POST['content'];
$name = $_POST['name'];

file_put_contents($name, base64_decode($content));

I not tested it code but is a good idea of the implement.


答:
The confusion you are having here is because you are trying to write a test about the implementation details, not about the desired effect.  Thinking instead about the desired behaviors of the class is likely to lead you to a better test.

In this example, it seems to me you have two behaviors you want to test:

When added an effect does something to the character

When it is removed the effect reverts the change to the character

I'm not exactly sure what a character effect is, but here's an example test that makes a fairly reasonable assumption, and hopefully gets my point across even if it's a little off:

```<code>[Test]
public void AddAndRemovingEffectsAltersCharachterAppropriately()
{
    var originalStrength = _character.Strength;
    CharacterEffect strengthPotion = new StrengthPotion();
    _character.Add(strengthPotion);
    Assert.That(_character.Strength, Is.GreaterThan(originalStrength));

    //normally I'd make a second test for this,
    //but the answer edit box is not a great IDE  :)
    _character.Remove(strengthPotion);
    Assert.That(_character.Strength, Is.EqualTo(originalStrength));
}
</code>```

Notice: this test doesn't care about the collection at all.  It's not obvious from reading it that a collection is necessary.  The collection is merely an implementation detail.  It's beneath the notice of the test.

Side note: The "add" and "remove" names for methods do suggest a collection, and don't really communicate that domain relevant purpose of the methods.  I'd prefer something like Apply or Consume over Add.  Or perhaps character.Inventory.Add() if we are talking about equipment.

Body:
The confusion you are having here is because you are trying to write a test about the implementation details, not about the desired effect.  Thinking instead about the desired behaviors of the class is likely to lead you to a better test.

In this example, it seems to me you have two behaviors you want to test:

When added an effect does something to the character

When it is removed the effect reverts the change to the character

I'm not exactly sure what a character effect is, but here's an example test that makes a fairly reasonable assumption, and hopefully gets my point across even if it's a little off:

[Test]
public void AddAndRemovingEffectsAltersCharachterAppropriately()
{
    var originalStrength = _character.Strength;
    CharacterEffect strengthPotion = new StrengthPotion();
    _character.Add(strengthPotion);
    Assert.That(_character.Strength, Is.GreaterThan(originalStrength));

    //normally I'd make a second test for this,
    //but the answer edit box is not a great IDE  :)
    _character.Remove(strengthPotion);
    Assert.That(_character.Strength, Is.EqualTo(originalStrength));
}

Notice: this test doesn't care about the collection at all.  It's not obvious from reading it that a collection is necessary.  The collection is merely an implementation detail.  It's beneath the notice of the test.

Side note: The "add" and "remove" names for methods do suggest a collection, and don't really communicate that domain relevant purpose of the methods.  I'd prefer something like Apply or Consume over Add.  Or perhaps character.Inventory.Add() if we are talking about equipment.


问:
Can you explain why multiple threads need locks on a single-core CPU?
Assume these threads run in single core cpu. As a cpu only run one instruction in one cycle. That is said, even thought they share the cpu resource. but the computer ensure that one time one instruction. So is the lock un-necessary for multiplethreading?</p>

答: Except for setting 'bool' there is no guarrantee (at least in c) that reading or writing a variable takes only one instruction - or rather can't be interrupted in the middle of reading/writing it</p>


答:
I'm going to be the dick here and advise on the basis of.. well, the obvious. Obviously, your code IS a mess or the question you'd be asking is "WHY is somebody saying my code is a mess?" But you're not challenging the supposition. You're just acting hurt and quite frankly there might be crying but there's no feeling when it comes down to justifying programming.

But really, why are you asking? You know your code sucks or you'd be asking a different question. If somebody told me my back-end web code stank, I'd laugh and say "okay what's wrong with it?" If they told me my JavaScript stank, I'd give them the social programmer equivalent of  a fat lip and I'd never ask for advice on how to react because the little bitches are clearly !@#$ing wrong.

Own what you're good at. And I really mean take responsibility for it. because it only takes one goof for some twit to second-guess you. Don't ask permission to be good. Just know your stuff. The end.


答:
The problem does not lie with individual operations, but the larger tasks the operations carry out.

Many algorithms are written with the assumption that they are in full control of the state they operate on. With an interleaved ordered execution model like the one you describe, the operations may be arbitrarily interleaved with each other, and if they share state, there is a risk that the state is in an inconsistent shape.

You can compare it with functions that may temporarily break an invariant in order to do what they do. As long as the intermediary state is not observable from the outside, they can do whatever they want to achieve their task.

When you write concurrent code, you need to ensure that contended state is considered unsafe unless you have exclusive access to it. The common way to achieve exclusive access is synchronizing on a synchronization primitive, like holding a lock.

Another thing that synchronization primitives tend to result in on some platforms is that they emit memory barriers, which ensure inter-CPU consistency of memory.

Title: Can you explain why multiple threads need locks on a single-core CPU?

Body: Assume these threads run in single core cpu. As a cpu only run one instruction in one cycle. That is said, even thought they share the cpu resource. but the computer ensure that one time one instruction. So is the lock un-necessary for multiplethreading?</p>


答:
This is best illustrated with an example.

Suppose we have a simple task that we want to perform multiple times in parallel, and we want to keep track globally of the number of times that the task has been performed, for example, counting hits on a web page.

When each thread gets to the point at which it's incrementing the count, its execution will look like this:

Read the number of hits from memory into a processor register

Increment that number.

Write that number back to memory

Remember that every thread can suspend at any point in this process. So if thread A performs step 1, and then gets suspended, following by thread B performing all three steps, when thread A resumes, its registers will have the wrong number of hits: its registers will be restored, it will happily increment the old number of hits, and store that incremented number.

In addition, any number of other threads could have run during the time that thread A was suspended, so the count thread A writes at the end might be well below the correct count.

For that reason, it's necessary to ensure that if a thread performs step 1, it must perform step 3 before any other thread is allowed to perform step 1, which can be accomplished by all threads waiting to get a single lock before they begin this process, and freeing the lock only after the process is complete, so that this "critical section" of code cannot be incorrectly interleaved, resulting in a wrong count.

But what if the operation were atomic?

Yes, in the land of magical unicorns and rainbows, where the increment operation is atomic, then locking would not be necessary for the above example.

It's important to realize, however, that we spend very little time in the world of magical unicorns and rainbows. In almost every programming language, the increment operation is broken down into the above three steps. That's because, even if the processor supports an atomic increment operation, that operation is significantly more expensive: it has to read from memory, modify the number, and write it back to memory...and usually the atomic increment operation is an operation that can fail, meaning the simple sequence above has to be replaced with a loop (as we'll see below).

Since, even in multithreaded code, many variables are kept local to a single thread, programs are much more efficient if they assume each variable is local to a single thread, and let the programmers take care of protecting shared state between threads. Especially given that atomic operations are not usually enough to solve threading issues, as we'll see later.

Volatile variables

If we wanted to avoid locks for this particular problem, we first have to realize that the steps depicted in our first example aren't actually what happens in modern compiled code. Because compilers assume only one thread is modifying the variable, each thread will keep its own cached copy of the variable, until the processor register is needed for something else. As long as it has the cached copy, it assumes it doesn't need to go back to memory and read it again (which would be expensive). They also won't write the variable back to memory as long as it's kept in a register.

We can get back to the situation we gave in the first example (with all the same threading problems we identified above) by marking the variable as volatile, which tells the compiler that this variable is being modified by others, and so must be read from or written to memory whenever it's accessed or modified.

So a variable marked as volatile will not take us to the land of atomic increment operations, it only gets us as close as we thought we were already.

Making the increment atomic

Once we're using a volatile variable, we can make our increment operation atomic by using a low-level conditional set operation that most modern CPUs support (often called compare and set or compare and swap). This approach is taken, for example, in Java's AtomicInteger class:

```<code>197       /**
198        * Atomically increments by one the current value.
199        *
200        * @return the updated value
201        */
202       public final int incrementAndGet() {
203           for (;;) {
204               int current = get();
205               int next = current + 1;
206               if (compareAndSet(current, next))
207                   return next;
208           }
209       }
</code>```

The above loop repeatedly performs the following steps, until step 3 succeeds:

Read the value of a volatile variable directly from memory.

Increment that value.

Change the value (in main memory) if and only if its current value in main memory is the same as the value we initially read, using a special atomic operation.

If step 3 fails (because the value was changed by a different thread after step 1), it again reads the variable directly from main memory and tries again.

While the compare-and-swap operation is expensive, it's slightly better than using locking in this case, because if a thread is suspended after step 1, other threads that reach step 1 do not have to block and wait for the first thread, which can prevent costly context switching. When the first thread resumes, it will fail in its first attempt to write the variable, but will be able to continue by re-reading the variable, which again is likely less expensive than the context switch that would have been necessary with locking.

So, we can get to the land of atomic increments (or other operations on a single variable) without using actual locks, via compare and swap.

So when is locking strictly necessary?

If you need to modify more than one variable in an atomic operation, then locking will be necessary, you won't find a special processor instruction for that.

As long as you're working on a single variable, and you're prepared for whatever work you've done to fail and to have to read the variable and start over again, compare-and-swap will be good enough, however.

Let's consider an example where each thread first adds 2 to a the variable X, and then multiplies X by two.

If X is initially one, and two threads run, we expect the result to be (((1 + 2) * 2) + 2) * 2 = 16.

However, if the threads interleave, we could, even with all operations being atomic, instead have both additions occur first, and the multiplications come after, resulting in (1 + 2 + 2) * 2 * 2 = 20.

This happens because multiplication and addition are not commutative operations.

So, the operations themselves being atomic is not enough, we must make the combination of operations atomic.

We can do that either by using locking to serialize the process, or we could use one local variable to store the value of X when we started our calculation, a second local variable for the intermediate steps, and then use compare-and-swap to set a new value only if the current value of X is the same as the original value of X. If we fail, we would have to start over again by reading X and performing the calculations again.

There are several trade-offs involved: as the calculations become longer, it becomes much more likely that the running thread will be suspended, and the value will be modified by another thread before we resume, meaning failures become much more likely, leading to wasted processor time. In the extreme case of large numbers of threads with very long running calculations, we might have 100 threads read the variable and be engaged in calculations, in which case only the first to finish will succeed in writing the new value, the other 99 will still complete their calculations, but discover upon completion that they can't update the value...at which point they'll each read the value and start the calculation over. We'd likely have the remaining 99 threads repeat the same problem, wasting vast quantities of processor time.

Full serialization of the critical section via locks would be much better in that situation: 99 threads would suspend when they didn't get the lock, and we'd run each thread in order of arrival at the locking point.

If serialization is not critical (as in our incrementing case), and the calculations that would be lost if updating the number fails are minimal, there may be a significant advantage to be gained from using the compare-and-swap operation, because that operation is less expensive than locking.

Body:
This is best illustrated with an example.

Suppose we have a simple task that we want to perform multiple times in parallel, and we want to keep track globally of the number of times that the task has been performed, for example, counting hits on a web page.

When each thread gets to the point at which it's incrementing the count, its execution will look like this:

Read the number of hits from memory into a processor register

Increment that number.

Write that number back to memory

Remember that every thread can suspend at any point in this process. So if thread A performs step 1, and then gets suspended, following by thread B performing all three steps, when thread A resumes, its registers will have the wrong number of hits: its registers will be restored, it will happily increment the old number of hits, and store that incremented number.

In addition, any number of other threads could have run during the time that thread A was suspended, so the count thread A writes at the end might be well below the correct count.

For that reason, it's necessary to ensure that if a thread performs step 1, it must perform step 3 before any other thread is allowed to perform step 1, which can be accomplished by all threads waiting to get a single lock before they begin this process, and freeing the lock only after the process is complete, so that this "critical section" of code cannot be incorrectly interleaved, resulting in a wrong count.

But what if the operation were atomic?

Yes, in the land of magical unicorns and rainbows, where the increment operation is atomic, then locking would not be necessary for the above example.

It's important to realize, however, that we spend very little time in the world of magical unicorns and rainbows. In almost every programming language, the increment operation is broken down into the above three steps. That's because, even if the processor supports an atomic increment operation, that operation is significantly more expensive: it has to read from memory, modify the number, and write it back to memory...and usually the atomic increment operation is an operation that can fail, meaning the simple sequence above has to be replaced with a loop (as we'll see below).

Since, even in multithreaded code, many variables are kept local to a single thread, programs are much more efficient if they assume each variable is local to a single thread, and let the programmers take care of protecting shared state between threads. Especially given that atomic operations are not usually enough to solve threading issues, as we'll see later.

Volatile variables

If we wanted to avoid locks for this particular problem, we first have to realize that the steps depicted in our first example aren't actually what happens in modern compiled code. Because compilers assume only one thread is modifying the variable, each thread will keep its own cached copy of the variable, until the processor register is needed for something else. As long as it has the cached copy, it assumes it doesn't need to go back to memory and read it again (which would be expensive). They also won't write the variable back to memory as long as it's kept in a register.

We can get back to the situation we gave in the first example (with all the same threading problems we identified above) by marking the variable as volatile, which tells the compiler that this variable is being modified by others, and so must be read from or written to memory whenever it's accessed or modified.

So a variable marked as volatile will not take us to the land of atomic increment operations, it only gets us as close as we thought we were already.

Making the increment atomic

Once we're using a volatile variable, we can make our increment operation atomic by using a low-level conditional set operation that most modern CPUs support (often called compare and set or compare and swap). This approach is taken, for example, in Java's AtomicInteger class:

197       /**
198        * Atomically increments by one the current value.
199        *
200        * @return the updated value
201        */
202       public final int incrementAndGet() {
203           for (;;) {
204               int current = get();
205               int next = current + 1;
206               if (compareAndSet(current, next))
207                   return next;
208           }
209       }

The above loop repeatedly performs the following steps, until step 3 succeeds:

Read the value of a volatile variable directly from memory.

Increment that value.

Change the value (in main memory) if and only if its current value in main memory is the same as the value we initially read, using a special atomic operation.

If step 3 fails (because the value was changed by a different thread after step 1), it again reads the variable directly from main memory and tries again.

While the compare-and-swap operation is expensive, it's slightly better than using locking in this case, because if a thread is suspended after step 1, other threads that reach step 1 do not have to block and wait for the first thread, which can prevent costly context switching. When the first thread resumes, it will fail in its first attempt to write the variable, but will be able to continue by re-reading the variable, which again is likely less expensive than the context switch that would have been necessary with locking.

So, we can get to the land of atomic increments (or other operations on a single variable) without using actual locks, via compare and swap.

So when is locking strictly necessary?

If you need to modify more than one variable in an atomic operation, then locking will be necessary, you won't find a special processor instruction for that.

As long as you're working on a single variable, and you're prepared for whatever work you've done to fail and to have to read the variable and start over again, compare-and-swap will be good enough, however.

Let's consider an example where each thread first adds 2 to a the variable X, and then multiplies X by two.

If X is initially one, and two threads run, we expect the result to be (((1 + 2) * 2) + 2) * 2 = 16.

However, if the threads interleave, we could, even with all operations being atomic, instead have both additions occur first, and the multiplications come after, resulting in (1 + 2 + 2) * 2 * 2 = 20.

This happens because multiplication and addition are not commutative operations.

So, the operations themselves being atomic is not enough, we must make the combination of operations atomic.

We can do that either by using locking to serialize the process, or we could use one local variable to store the value of X when we started our calculation, a second local variable for the intermediate steps, and then use compare-and-swap to set a new value only if the current value of X is the same as the original value of X. If we fail, we would have to start over again by reading X and performing the calculations again.

There are several trade-offs involved: as the calculations become longer, it becomes much more likely that the running thread will be suspended, and the value will be modified by another thread before we resume, meaning failures become much more likely, leading to wasted processor time. In the extreme case of large numbers of threads with very long running calculations, we might have 100 threads read the variable and be engaged in calculations, in which case only the first to finish will succeed in writing the new value, the other 99 will still complete their calculations, but discover upon completion that they can't update the value...at which point they'll each read the value and start the calculation over. We'd likely have the remaining 99 threads repeat the same problem, wasting vast quantities of processor time.

Full serialization of the critical section via locks would be much better in that situation: 99 threads would suspend when they didn't get the lock, and we'd run each thread in order of arrival at the locking point.

If serialization is not critical (as in our incrementing case), and the calculations that would be lost if updating the number fails are minimal, there may be a significant advantage to be gained from using the compare-and-swap operation, because that operation is less expensive than locking.


答: basically crud cannot be completed without these 4 things . Crud means Create,Read,Update and delete so when you are only trying to read data you can use simple query for that but all these three things are attached to one and other and simple concepts of database</p>


答:
Everybody's code is a mess and there are no good programmers.

There are:

programmers that ship fast,

programmers that always ship semantically correct code,

programmers that always come up with the optimal solution, and the fastest algorithm,

programmers whose code is easy on the eye.

They hardly, if ever, end up being the same person.

And there are butthurt programmers that need to grow up and:

ask what's wrong,

take no comment personally, as a measure of their worth as a human being;

realize there are syntax guidelines in teams, and they gotta be followed, and they are arbitrary, so they're not meant to be discussed ad nauseam, as there is no optimal solution, nor final word;

get better at commenting their code;

get better at commenting their code; (sic)

find easier to debug, less clever, solutions to simple, mundane, tasks;

take a class in SQL

(I'd send half of this world's population to take a class in SQL, just to be on the safe side)

It's not art, it's a craft.

We give for granted you're clever: you're programming computers, goddamit.

Still AMD64 and x86 are not compelled by the power of your prose. Keep things simple.


答:
Shared memory.

It's the definition of... threads: a bunch of concurrent processes, with shared memory.

If there is no shared memory, they are usually referred as old-school-UNIX processes.

They might need a lock, now and then, when accessing a shared file, though.

(shared memory in UNIX-like kernels was indeed usually implemented using a fake file descriptor representing the shared memory address)


问:
What's the web framework to use on a front-end web application?
What do you consider a good client web framework to use on interface business application? jQuery? YUI!? Another? Some plugins useful?

The application will be use mostly internally replacing a desktop application for data entry and lots of queries/views.

答:
Here are some useful libraries:

jQuery and plugins

jQuery UI, a lot of things you may thought of implementing yourself

Underscore.js, implements the language core that's missing in JS 1.5

RequireJs, a library management system for JS

There's also Dojo framework there, which basically makes you program in JS like it's a desktop GUI application, but I can't say much about it. Watch video presentations on it.


问:
Real-Time Multi-User Gaming Platform
I'm considering developing a real-time multi-user game, and I want to gather some information about possibilities before I do some real development. I've thought about how best to ask the question, and for simplicity, the best way that occurred to me was to make an analogy to the field (or playground) game darebase.

In the field game of darebase, there are two or more bases. To start, there is one team on each base. The game is a fancy game of tag. When two people meet out in the field, the person who left his base most recently timewise captures the other person. They then return to that person's base.

Play continues until everyone is part of the same team.

So, analogizing this to an online computer game, let's suppose there are an indefinite number of bases. When a person starts up the game, he has a team that is located at, for example, his current GPS coordinates. It could be a virtual world, but for sake of argument, let's suppose the virtual world corresponds to the player's actual GPS coordinates.

The game software then consults the database to see where the closest other base is that is online, and the two teams play their game of virtual tag. Note that the user of the other base could have a different base than the one run by the current user as the closest base to him, in which case, he would be in two simultaneous battles, one with each base.

When they go offline, the state of their players is saved on a server somewhere. Game logic calls for the players to have some automaton-logic of some sort, so they can fend for themselves in a limited way using basic rules, until their user goes online again. The user doesn't control the players' movements directly, but issues general directives that influence the players' movement logic.

I think this analogy is good enough to frame my question.

I've been looking at smartfoxserver, but I'm not convinced yet that it is the best option or even that it will work at all.

One possibility, of course, would be to roll out my own web server, but I'd rather not do that if there is an existing service out there already that I could tap into.

Note that darebase is not the game I intend to implement, but, upon reflection, that might not be a bad idea either.

What I'm looking for, specifically, is an appropriate architecture that can do the following things:

Act as a repository of saved game states

Provide a framework that allows multiple players to communicate with each other.

(optionally) executing some of the gaming logic, for example, in the
game of darebase, who determines who tagged whom? Is it one or both
clients or is it the server?

I've never been involved with such a multi user real-time environment, so I can only guess at the pitfalls of one decision vs. another.

答:
Your requirements dont specifically preclude any of the more common server side languages.  But you might consider something like node.js, which is particularly good at handling the kind of 'real time' communication you want between clients.

You will probably want a central server.  I know you said you were looking at client to client communication.  But that can be problematic due to firewalls/routers.  There are certainly ways around that (ie, like skype does), but it probably wouldnt be worth the hassle for you.

Title: Real-Time Multi-User Gaming Platform


答:
Seems many answer attempted to explain locking, but I think what OP needs is an explanation of what multitasking actually is.

When you have more than one thread running on a system even with one CPU, there are two main methodologies that dictate how these threads will be scheduled (i.e. placed to run into your single-core CPU):

Cooperative Multitasking - Used in Win9x required each application to explicitly give up control. In this case, you wouldn't need to worry about locking since as long as Thread A is executing some algorithm, you would be guaranteed that it will never be interrupted

Preemptive Multitasking - Used in most modern OSs (Win2k and later). This uses timeslices and will interrupt threads even if they are still doing work. This is much more robust because a single thread can never hang your entire machine, which was a real possibility with cooperative multitasking. On the other hand, now you need to worry about locks because at any given time, one of your threads could be interrupted (i.e. preempted) and OS might schedule a different thread to run. When coding multithreaded applications with this behavior, you MUST consider that between every line of code (or even every instruction) a different thread might run. Now, even with a single core, locking becomes very important to ensure consistent state of your data.


问:
What are the caveats of the event system built on Messenger rather than on classic .NET events?
MVVM Light and PRISM offer messenger to implement event system.

the approximate interface looks like the following one:

```<code>interface Messanger
{
    void Subscribe<TMessageParam>(Action<TMessageParam> action);
    void Unsubscribe<TMessageParam>(Action<TMessageParam> action);
    void Unsubscribe<TMessageParam>(objec actionOwner);
    void Notify<TMessageParam>(TMessageParam param);
}
</code>```

Now this model seems beneficial comparing to classic .net events. It works well with Dependency Injection. Actions are stored as weak references so memory leaks are avioded and unsubscribe is not a must.
The only annoyance is the need to declare new TMessageParam for each specific message.
But everything comes at a cost. And what I'm really worried about is that I see no shortcomings of this approach.

Has anoyne the experience of some troubles with this design pattern?

Update

We tried it and the most unpleasant thing with messages is their implicitness from the point of view of interface. Messages contrary to Events are not exposed explicitly in the interface so additional documentation must be provided.

As Laurent said below very loose coupling comes at a cost of vagueness.

答: The major disadvantage of messaging-based systems is that it is less easy to understand what's going on. It can be tougher to debug what's happening than in an event based system, exactly because the messaging system is more loosely coupled. It's the same type of issue that comes with advanced systems like Rx (Reactive extensions).</p>


答:
Overall, your question is probably too broad to be answered in any depth, but I will try to give you some pointers in the right direction.

There are a number of good reasons why you will need to have your own server (web or otherwise):

Firstly, any game of moderate complexity will be unique enough that you won't find an existing service to simply hook into to run your game logic.  I'm not really even aware of any services which attempt to provide things like that (other than basic services, such as data or game resource storage, etc - you typically still need to write and host your own code).

Second, as with any networked application, you cannot really trust the client side (you simply cannot be sure that the client code hasn't been tampered with - period).  The typical solution is to run most of the game logic on the server side (or to at least validate whether what the clients are telling you is correct or not).  If you don't do this, sooner or later, someone is going to modify the client side to keep reporting victories, and ruin the game experience for others.

executing some of the gaming logic, for example, in the game of darebase, who determines who tagged whom? Is it one or both clients or is it the server?

Here, we need to keep the above point in mind, but also the practicalities.  A lot will depend on how you would like the game to play out.  Is it a game of skill, where players have some kind of mini-game to play, or is it simply random?  The difference is in the amount of communication happening between the client(s) and the server.  In the latter case, I'd definitely have the server do all the calculations, and simply serve up the result to the clients.  In the former case, it's far more complicated, since you'd want to have the game as responsive as possible for the players, while still being validated on the server-side.  Implementing something like that can be very difficult, so for your first game, I'd pick the simpler option - base the game around things that you can easily code, such as simple random number "rolls", which can then be translated into actions on the client like "you lunge at your opponent, but she dodges!", or something along those lines.

These are the basic realities of the situation.  You will almost certainly need your own server, where the majority of the game data and logic will live.  Regarding your fears that you are reinventing the wheel, don't worry too much - as long as you don't try to write the web server from scratch (as Jimmy Hoffa pointed out), you're fine.  In fact, judging from the confusion in the comments, I think most people took that for granted; I was just trying to convince you.

EDIT:  If you would like to read more about actual architectures, here's an article which outlines IBM's PowerUp MMO game (it's in Java, but the overreaching concepts stay the same).  It should be noted that this example caters for heavy communication between many clients and servers; you may be able to design your game to be far simpler, with only occasional communication (e.g. once per "battle").

Title: Real-Time Multi-User Gaming Platform

Body:
I'm considering developing a real-time multi-user game, and I want to gather some information about possibilities before I do some real development. I've thought about how best to ask the question, and for simplicity, the best way that occurred to me was to make an analogy to the field (or playground) game darebase.

In the field game of darebase, there are two or more bases. To start, there is one team on each base. The game is a fancy game of tag. When two people meet out in the field, the person who left his base most recently timewise captures the other person. They then return to that person's base.

Play continues until everyone is part of the same team.

So, analogizing this to an online computer game, let's suppose there are an indefinite number of bases. When a person starts up the game, he has a team that is located at, for example, his current GPS coordinates. It could be a virtual world, but for sake of argument, let's suppose the virtual world corresponds to the player's actual GPS coordinates.

The game software then consults the database to see where the closest other base is that is online, and the two teams play their game of virtual tag. Note that the user of the other base could have a different base than the one run by the current user as the closest base to him, in which case, he would be in two simultaneous battles, one with each base.

When they go offline, the state of their players is saved on a server somewhere. Game logic calls for the players to have some automaton-logic of some sort, so they can fend for themselves in a limited way using basic rules, until their user goes online again. The user doesn't control the players' movements directly, but issues general directives that influence the players' movement logic.

I think this analogy is good enough to frame my question.

I've been looking at smartfoxserver, but I'm not convinced yet that it is the best option or even that it will work at all.

One possibility, of course, would be to roll out my own web server, but I'd rather not do that if there is an existing service out there already that I could tap into.

Note that darebase is not the game I intend to implement, but, upon reflection, that might not be a bad idea either.

What I'm looking for, specifically, is an appropriate architecture that can do the following things:

Act as a repository of saved game states

Provide a framework that allows multiple players to communicate with each other.

(optionally) executing some of the gaming logic, for example, in the
game of darebase, who determines who tagged whom? Is it one or both
clients or is it the server?

I've never been involved with such a multi user real-time environment, so I can only guess at the pitfalls of one decision vs. another.


答:
Well don't feel broken. Eventually you will learn from the mistakes. Once you are done with the issue you can talk to guy so it makes him feel that you want to improve. Try to listen more and argue less.

I have been through this situation and I can understand.


答:
Remember this: The worst code you will ever see is your own!

Jeff Atwood of codinghorror.com wrote alot about the topic, you might want to start here: http://www.codinghorror.com/blog/2009/07/nobody-hates-software-more-than-software-developers.html

If you want to improve, start to read stuff about coding style, patterns, workflows, basically everything you can get your fingers on. Also learn more programming languages, see how they do stuff. If you are doing OOP, read this: http://en.wikipedia.org/wiki/Design_Patterns

Also talk to other programmers and do pair programming or watch others code.

Making mistakes is unavoidable, repeating them is.