答:
You can't have more productive threads than you have processors. (I'm ignoring I/O for now.) Lets suppose maxThreads is the total maximum number of threads you want to have. This is a soft limit. It may get exceeded temporarily, but the excess will correct itself.

Have a queue of unchecked strings, initially empty. Start one StringChecker thread.

Every time a StringChecker sees the queue empty, it starts a new StringGenerator thread. If the total number of threads now exceed maxThreads and this is not the only StringChecker thread, it stops. Otherwise, it pulls a string from the queue and checks it.

Every time a StringGenerator has a string ready to be checked but finds the queue is full, it starts a new StringChecker thread. After waiting for the queue to unblock and let it put its string into the queue, if the total number of threads now exceeds maxThreads and it is not the last StringGenerator, it stops.

Better Answer

I was playing out in my mind how this system and the one described by @rwong would behave, and realized we're going at this all wrong. How long it takes to generate a string versus how long it takes to check one is irrelevant. When the system reaches steady state, it will be checking strings at exactly the same rate it generates them. stringsGenerated = stringsChecked + stringsInQueue + stringsBeingChecked, and the last two terms are both small and bounded.

That means you may as well start as many threads as you deem useful, and have each thread:

```<code>loop
    generate a string
    check it
end loop
</code>```

I see that @Doval had the same idea, so I +1ed his comment.

Title: Is there an algorithm to determine the amount of work needed to keep workers busy?

Body:
I wrote a multi-threaded program that randomly generates strings, and after generating, checks to see if the string contains a certain value. Namely, StringGenerator and StringChecker. What I'm trying to figure out is how many StringGenerator threads I would need in order to keep StringChecker busy.

All StringGenerator threads have a reference to a Queue that contains all of the Strings needed to be checked, and when they generate a String, it gets added to the Queue. All StringChecker threads also have a reference to the same Queue and poll it to get the next string, and checks to see if it contains the keyword.

Because generating the Strings takes more time than checking them, what I want to know is if there are any equations, algorithms or analyses that can be done on the code that can help tell me approximately how many threads of each I will need such that the sum of all Strings generated by the StringGenerators is as close to the number of strings checked by the StringCheckers as possible.

Body:
You can't have more productive threads than you have processors. (I'm ignoring I/O for now.) Lets suppose maxThreads is the total maximum number of threads you want to have. This is a soft limit. It may get exceeded temporarily, but the excess will correct itself.

Have a queue of unchecked strings, initially empty. Start one StringChecker thread.

Every time a StringChecker sees the queue empty, it starts a new StringGenerator thread. If the total number of threads now exceed maxThreads and this is not the only StringChecker thread, it stops. Otherwise, it pulls a string from the queue and checks it.

Every time a StringGenerator has a string ready to be checked but finds the queue is full, it starts a new StringChecker thread. After waiting for the queue to unblock and let it put its string into the queue, if the total number of threads now exceeds maxThreads and it is not the last StringGenerator, it stops.

Better Answer

I was playing out in my mind how this system and the one described by @rwong would behave, and realized we're going at this all wrong. How long it takes to generate a string versus how long it takes to check one is irrelevant. When the system reaches steady state, it will be checking strings at exactly the same rate it generates them. stringsGenerated = stringsChecked + stringsInQueue + stringsBeingChecked, and the last two terms are both small and bounded.

That means you may as well start as many threads as you deem useful, and have each thread:

loop
    generate a string
    check it
end loop

I see that @Doval had the same idea, so I +1ed his comment.


问:
Is there an algorithm to determine the amount of work needed to keep workers busy?
I wrote a multi-threaded program that randomly generates strings, and after generating, checks to see if the string contains a certain value. Namely, StringGenerator and StringChecker. What I'm trying to figure out is how many StringGenerator threads I would need in order to keep StringChecker busy.

All StringGenerator threads have a reference to a Queue that contains all of the Strings needed to be checked, and when they generate a String, it gets added to the Queue. All StringChecker threads also have a reference to the same Queue and poll it to get the next string, and checks to see if it contains the keyword.

Because generating the Strings takes more time than checking them, what I want to know is if there are any equations, algorithms or analyses that can be done on the code that can help tell me approximately how many threads of each I will need such that the sum of all Strings generated by the StringGenerators is as close to the number of strings checked by the StringCheckers as possible.

答:
There is another approach. This is similar to @ganbustein's answer, but with one difference. It is known as the Task parallelism paradigm.

In task parallelism,

All execution is decomposed, and the decomposed tasks are packaged into tasks.
 (Also known as "closures", which means a self-contained unit of executable code and all data that is needed. If any data isn't immediately available (i.e. dependent on another task), this dependency is noted by the task parallelism engine, and the executable code will deal with it by wrapping it in a Future.)

The dependencies between tasks are established.

Tasks that are ready to execute are pushed into a common queue.

Any CPU that is available, will grab any task that is on the front of the common queue.

After executing the task, any subsequent tasks whose data dependency become satisfied will now be added to the common queue.

The key difference between Task Parallelism and @ganbustein's answer is this: "there is no affinity between task types, threads, or CPU cores."

To restate in a simple sentence, "any thread can execute any task type that shows up on the queue."

Given your example, you can instantiate as many threads as you have CPU cores, and all of these threads will run the following infinite loop:

If there is a string in the "waiting to be checked" queue, it will be popped and checked.
(In task-oriented thinking, this is a simplification of executing the StringCheckerTask.)

Otherwise, generate a new random string and add to the "waiting to be checked" queue.
(In task-oriented thinking, this is a simplification of executing the StringGeneratorTask.)

Keep looping until interrupted.

Expected result: You will see that all cores are fully occupied. Make sure your CPU has good ventilation.

Side effects: By maximizing CPU utilization, you will notice that it places heavy stress on your implementation of Queue structure. All of the CPUs will be reading and writing this queue, so this creates lots of memory access conflicts. (If your queue is not thread-safe, it will also start losing or corrupting data pretty quickly.)

ContentLicense: CC BY-SA 3.0


问:
Is there still a need for writing SQL?
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.

答: If you want to use a database yourself, yes.  Most of the ORMs that I tried to use just weren't sufficient or didn't cover my database.  Besides, how are you going to troubleshoot or write custom queries that aren't covered?</p>

ContentLicense: CC BY-SA 2.5

Title: Is there still a need for writing SQL?


问:
Two classes that behave identically yet are semantically different
I am writing a program which is a similar to Ruby's Active Record Migrations, in which that every migration has both an "Up" and "Down" in terms of creating a change to the database, "Up" meaning bring the database forward in time, and "Down" reversing that change.

My program has two main functions to achieve its use-cases

Get a list of scripts off the filesystem

Execute the appropriate migrations on the database

The "Up" and "Down" migrations are stored in their own separate files, but they match with a similar naming scheme

2014000000000001_CreateTable_up.sql

2014000000000001_CreateTable_down.sql

There is a 1:1 correlation between up and down scripts.  Having just an up without the corresponding down script is not valid (and vise verse).

I have two classes in my project to represent these filesystem files.

```<code>public sealed class UpScript // (and DownScript, which looks identical)
{
    public UpScript(long version, string name, string content)
    {
        Content = content;
        Version = version;
        Name = name;
    }

    public long Version { get; private set; }
    public string Name { get; private set; }
    public string Content { get; private set; }
}
</code>```

The reason that I did not make a single class called Script is I didn't want to create ambiguity about the purpose of a specific Script instance.  UpScript and DownScript classes should not be used interchangeability as they do not conform to the Liskov Substitution Principle.

The problem that I have here is a few parts of code that are dealing with both either UpScript or DownScript instances look almost identical.  How do I reduce the duplication without losing the expressiveness of having different classes?

My current ideas with concerns are:

Abstract base class

```<code>public abstract class Script
{
    protected Script(long version, string name, content)
    {
        // code
    }

    // properties
}

public sealed UpScript : Script
{
    public UpScript(long version, string name, string content)
        : this(version, name, content)
    {}
}

public sealed DownScript : Script
{
    public DownScript(long version, string name, string content)
        : this(version, name, content)
    {}
}
</code>```

This reduces the redundant code in the two classes, however, code that creates and consumes is still very duplicated.

Single class with Direction property

```<code>public enum Direction { Up, Down }

public sealed class Script
{
    protected Script(Direction direction, long version, string name, string content)
    {
        // ...
    }

    public Direction Direction { get; private set; }

    // ...
}
</code>```

This code reduces the duplication, however, it adds onus on consumes to ensure the proper script is passed to it and it creates ambiguity if you ignore the Direction property.

Single class with two Content properties

```<code>public sealed class Script
{
    protected Script(long version, string name, string upContent, string downContent)
    {
        // ...
    }

    public string UpContent { get; private set; }
    public string DownContent { get; private set; }
}
</code>```

This reduces duplication and is not ambiguous, however, the usage of the program is to either run the up script, or run the down scripts.  With this scheme, the code that gathers and creates these Script instances is doing twice as much work, I don't consider not doing this being premature optimization because if the user wants to do an up migration, there's no point is looking at down scripts.

With all that said I may be looking at the wrong problem to solve entirely.

If more information would be helpful in forming a suggestion, you can view ScriptMigrations on GitHub

答:
I think your solution with the abstract base class is just fine. It's common OO programming: you have an abstract type with two different implementations. You should not worry about about duplication of creating two classes. In a language like Scala that provides some syntactic facilities, you can define such cases in a more concise way, but for C# and Java I don't think you can do much better. In Scala you can use case classes for example:

```<code>trait Script(long version, string name, content)
case class UpScript(long version, string name, content) extends Script
case class DownScript(long version, string name, content) extends Script
</code>```

About instantiation, in your current case it's just fine as you have only two subclasses at the moment. You can think of having factories and then when reading the up files, use UpFactory, say, and vice versa. This way the client code will not be bound to the actual implementation.

Body:
I think your solution with the abstract base class is just fine. It's common OO programming: you have an abstract type with two different implementations. You should not worry about about duplication of creating two classes. In a language like Scala that provides some syntactic facilities, you can define such cases in a more concise way, but for C# and Java I don't think you can do much better. In Scala you can use case classes for example:

trait Script(long version, string name, content)
case class UpScript(long version, string name, content) extends Script
case class DownScript(long version, string name, content) extends Script

About instantiation, in your current case it's just fine as you have only two subclasses at the moment. You can think of having factories and then when reading the up files, use UpFactory, say, and vice versa. This way the client code will not be bound to the actual implementation.


问:
Adding values to HashMap
I want to add values to a HashMap, which would be used by methods in the same class. I have two solutions:

Adding all the values with static

When the first method is called, add the values

Solution #1:

```<code>private static Map<Character, String> codes = new HashMap<>();

static {
    codes.put('A', ".-");
    codes.put('B', "-...");
    codes.put('C', "-.-.");
    codes.put('D', "-..");
    codes.put('E', ".");
    codes.put('F', "..-.");
    // ...
}
</code>```

Solution #2:

```<code>boolean methodIsCalled = false;

public static char decode(String s) {
    if(!methodIsCalled) {
        addValues();
        methodIsCalled = true;
    }
    // ...
}

private static void addValues() {
    codes.put('A', ".-");
    codes.put('B', "-...");
    codes.put('C', "-.-.");
    codes.put('D', "-..");
    codes.put('E', ".");
    codes.put('F', "..-.");
    // ...
}
</code>```

Which one is the most efficient? Which one is the best practice?

答:
Your solution 1 may be problematic, as the hashmap is static and will be initialised only once, and is shared by all instances of your class. Is this your intended behavior or you want each instance have its own map? If you one only one map, I would suggest to pass the set to the constructor instead of using a static one, for example:

```<code>public class Data {
  private final Map<Character, String> codes;
  public Data(Map<Character, String> codes) { this.codes = codes}
}
</code>```

Your solution 2 adds the overhead of lazy initilization of the set, each time you need it,
and adds the ugly check methodIsCalled to the logic of your program. I think initilizing the map in the constructor is a better option.

```<code>public class Data {
  private final Map<Character, String> codes;
  public Data() {
     this.codes = new HashMap<>();
     codes.put('A', ".-");
     codes.put('B', "-...");
     codes.put('C', "-.-.");
     codes.put('D', "-..");
     codes.put('E', ".");
     codes.put('F', "..-.");
  }
}
</code>```

The other question you need to answer is that if you change the values of this hashmap later or not. If you don't change it, you better look for immutable hashMaps. One option is to use
Collections.unmodifiableMap(map).

You can also use Google Guava libraries to that allow you to initialize a map in one line and get an immutable map:

```<code>ImmutableMap.<Character, String>builder()
     .put('A', ".-")
     .put('B', "-...")
     .put('C', "-.-.")
     .put('D', "-..")
     .put('E', ".")
     .put('F', "..-.")
     .build();
</code>```

Title: Adding values to HashMap

Body:
Your solution 1 may be problematic, as the hashmap is static and will be initialised only once, and is shared by all instances of your class. Is this your intended behavior or you want each instance have its own map? If you one only one map, I would suggest to pass the set to the constructor instead of using a static one, for example:

public class Data {
  private final Map<Character, String> codes;
  public Data(Map<Character, String> codes) { this.codes = codes}
}

Your solution 2 adds the overhead of lazy initilization of the set, each time you need it,
and adds the ugly check methodIsCalled to the logic of your program. I think initilizing the map in the constructor is a better option.

public class Data {
  private final Map<Character, String> codes;
  public Data() {
     this.codes = new HashMap<>();
     codes.put('A', ".-");
     codes.put('B', "-...");
     codes.put('C', "-.-.");
     codes.put('D', "-..");
     codes.put('E', ".");
     codes.put('F', "..-.");
  }
}

The other question you need to answer is that if you change the values of this hashmap later or not. If you don't change it, you better look for immutable hashMaps. One option is to use
Collections.unmodifiableMap(map).

You can also use Google Guava libraries to that allow you to initialize a map in one line and get an immutable map:

ImmutableMap.<Character, String>builder()
     .put('A', ".-")
     .put('B', "-...")
     .put('C', "-.-.")
     .put('D', "-..")
     .put('E', ".")
     .put('F', "..-.")
     .build();


问:
How do I unit test a heuristic algorithm?
Say we have our route finding algorithm:

```<code>def myHeuristicTSP(graph):
    /*implementation*/
    return route
</code>```

Now we want to unit test this:

```<code>class TestMyHeuristicTSP:
    def testNullGraphRaiseValueError(self):
        self.assertRaises(ValueError, myHueristicTSP(None))

    def testSimpleTwoNodeGraphReturnsRoute:
        self.assertEquals(expectedResult, myHeuristicTSP(input))
</code>```

The question is, for a non-heuristic TSP algorithm, we can give a variety of graphs and check that they always return absolutely the shortest route.

But because a heurtistic algorithm, while is still deterministic, is less predictable, are simply meant to understand how the algorithm is meant to be working, and find those edge cases?

答:
For a heuristic algorithm which is supposed to not return the ideal but a "good enough" solution, you would have various test-cases and check

is the solution actually valid? You certainly want to make sure your route-finding algorithm doesn't return paths which are impossible or which don't actually lead from start to finish. You might not be able to prove that the solution is ideal, but you should at least be able to verify that the return value actually is a solution.

is the solution "good enough"? You should have some requirements which define how much worse the algorithm may be than the ideal solution. You should have test cases where the ideal solution is known (or at least a solution which is considered good enough to be used as a comparison standard) and confirm that the solution provided by the algorithm is not more than x% worse.

Is the algorithm fast enough? You often use a heuristic approach when you presume that they make up for their lack of precision by being much faster. To verify this you should measure their runtime and make sure they are indeed faster than an algorithm which gets the exact solution. Runtime measurements are always a bit fuzzy, so exceeding the expected runtime should be a warning, not an error (when your unit testing framework allows to differ between warnings and errors).


问:
Design for a shared checkout
I am currently working on a ecommerce system that is slightly different in structure to a typical ecommerce system in that you have multiple stores, accessing the same database from different URLs.

So for example i might have:

http://www.site1.com

http://www.site2.com

the above are essentially the same store, they point to the same database, in the main will share the same products (this may seem weird but these are the requirements of the client).  The only difference is, based on the URL the users, baskets, orders etc are split so that they do not cross each other. I.e. the orders/baskets/users of site1 are not visible to site2 so a pretty standard single database multitenant model.

The above is implemented, i am just slightly stuck on how to implement the checkout process.  The requirement is to have a shared checkout, so instead of:

https://www.site1.com/checkout

you would have (for clarity this will link to the same database as the above sites)

https://checkout.somesite.com/storeid/basketid

You could tie this in to the way it is handled at Shopify, multiple stores one checkout process.

The checkout process in the main is not difficult, i can use the storeId and basketId to identify what i need to identify in terms of create an order from a basket and assigning to a store if the user is a guest.  The issue i am facing is what to do when an existing user wants to checkout and login so that the order is associated to their account and some basic information (Email Address, Billing Address) is pre-populated for them.

The checkout process (https://checkout.somesite.com/storeid/basketid) does not concern itself with logins or account management of any sort, its just there to facilitate checkout so users, if they are at the beginning of the checkout process and wish to login will be redirected back to the corresponding sites login page.  From there i am thinking about this process, but just wanted to share it to see if there is something glaringly wrong with it:

User Logs in with correct credentials

Some object (may be the Cart or an intermediary CartOrder object) is updated to contain the id of the user, a unique session key (possibly a GUID) and a timestamp to state the expiry of the checkout session

User is redirected back to the checkout site with the session id appended in the querystring (i can't use cookies as the sites are on different domains)

Option: At this point i may create a local session to hold onto the value for the remainder of the checkout process making sure it is still valid along the way (a new login would also expire the session key)

Checkout!

Now there is a slight concern in that placing the session id in the query string it could be picked up by some malicious person, used and some information (name, address) could be visible. On the flip side to that, the checkout will be all SSL, the sessions are short lived and not really able to spoof accounts (or do anything on behalf of the account it represents) so i am not sure if it is being over thought in this process?

答:
I have dealt with a somewhat similar scenario in the past, though it was across subdomains. (I don't know what programming language you are using, so I'll just describe what I did using PHP) The approach that I used was to configure PHP on all servers to store sessions on 1 dedicated memcached server.  This allowed session data to be centralized and accessible from any server really, but you'll want to write some firewall rules to restrict access to only your servers.  Memcached doesn't have any security like that built in, you have to restrict it to only 1 IP address, or '0.0.0.0' which is any.  The second step was to configure the "cookie_domain" setting on each server to the parent domain.  Here are the config options from my php.ini:

```<code>session.save_handler = memcached
session.save_path = "[server ip address]:33023?persistent=1&weight=1&timeout=1&retry_interval=15"
session.cookie_domain = .somesite.com
</code>```

You will replace [server ip address] with your memcached server ip address.

Many folks don't know, PHP keeps track of the session id via a cookie though you can pass it through the query string too.  But if you are able to set up the site(s) the way I explained above, you won't have to do that since your sites will have access to the session cookie under the same cookie domain.  Browsers have security built in that prevent you from accessing cookies from another site.

HTH

Title: Design for a shared checkout

Body:
I have dealt with a somewhat similar scenario in the past, though it was across subdomains. (I don't know what programming language you are using, so I'll just describe what I did using PHP) The approach that I used was to configure PHP on all servers to store sessions on 1 dedicated memcached server.  This allowed session data to be centralized and accessible from any server really, but you'll want to write some firewall rules to restrict access to only your servers.  Memcached doesn't have any security like that built in, you have to restrict it to only 1 IP address, or '0.0.0.0' which is any.  The second step was to configure the "cookie_domain" setting on each server to the parent domain.  Here are the config options from my php.ini:

session.save_handler = memcached
session.save_path = "[server ip address]:33023?persistent=1&weight=1&timeout=1&retry_interval=15"
session.cookie_domain = .somesite.com

You will replace [server ip address] with your memcached server ip address.

Many folks don't know, PHP keeps track of the session id via a cookie though you can pass it through the query string too.  But if you are able to set up the site(s) the way I explained above, you won't have to do that since your sites will have access to the session cookie under the same cookie domain.  Browsers have security built in that prevent you from accessing cookies from another site.

HTH


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
I have been asked to write in a presentation of our software to a major multinational potential customer that we used "spaghetti code" coding technique.

Of course, we're in Italy... sounds good.

OwnerDisplayName: chiccorusso


答:
Sure:

Generally ORM encapsulates a lot, but in the end you should know what happens behind the scenes. This is crucial for performance and scalability. Though inside application I don't write that much SQL but I know roughly how the SQL or DDL looks like.

Direct SQL is often nice to write read-only queries. Much easier as to formulate it in ORM query language and you can also limit result set (e.g. 'select id from .....').

ORM should not keep you away from SQL at all. I use SQL a lot for ad-hoc queries directly on the DB-client (like mysql-client). It gives you very nice uniform interface and grouping functionalities.

Title: Is there still a need for writing SQL?

Body:
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.


答:
If you don't insist on lazy initialization (and for a small, non-growing map of 26 items you shouldn't), then why not optimize for readability instead? I would always use something like

```<code>private static Map<Character, String> codes = newMap(
  'A', ".-",
  'B', "-...",
  'C', "-.-.",
  ...
);
</code>```

(with a suitably defined helper function newMap).

Title: Adding values to HashMap

Body:
I want to add values to a HashMap, which would be used by methods in the same class. I have two solutions:

Adding all the values with static

When the first method is called, add the values

Solution #1:

```<code>private static Map<Character, String> codes = new HashMap<>();

static {
    codes.put('A', ".-");
    codes.put('B', "-...");
    codes.put('C', "-.-.");
    codes.put('D', "-..");
    codes.put('E', ".");
    codes.put('F', "..-.");
    // ...
}
</code>```

Solution #2:

```<code>boolean methodIsCalled = false;

public static char decode(String s) {
    if(!methodIsCalled) {
        addValues();
        methodIsCalled = true;
    }
    // ...
}

private static void addValues() {
    codes.put('A', ".-");
    codes.put('B', "-...");
    codes.put('C', "-.-.");
    codes.put('D', "-..");
    codes.put('E', ".");
    codes.put('F', "..-.");
    // ...
}
</code>```

Which one is the most efficient? Which one is the best practice?

Body:
If you don't insist on lazy initialization (and for a small, non-growing map of 26 items you shouldn't), then why not optimize for readability instead? I would always use something like

private static Map<Character, String> codes = newMap(
  'A', ".-",
  'B', "-...",
  'C', "-.-.",
  ...
);

(with a suitably defined helper function newMap).


答:
My C# is rusty, hopefully I haven't glossed over any language constraints.

I would implement UpScript and DownScript as interfaces that have the same members:

```<code>public interface IUpScript {
    public long Version { get; private set; }
    public string Name { get; private set; }
    public string Content { get; private set; }
}
// ...
public interface IDownScript {
    public long Version { get; private set; }
    public string Name { get; private set; }
    public string Content { get; private set; }
}
</code>```

This approach attempts to provide the minimal code needed to create a distinction between up and down, nothing more. Thoughts:

Classes implementing an interface will have the common properties you've defined as in your other approaches but don't inherit implementation details like a constructor.

Your implementing classes would be free to extend other classes if they needed.

It looks as though you don't need to support multiple implementations of up and down scripts but you'd have no trouble doing so.

Title: Two classes that behave identically yet are semantically different

Body:
I am writing a program which is a similar to Ruby's Active Record Migrations, in which that every migration has both an "Up" and "Down" in terms of creating a change to the database, "Up" meaning bring the database forward in time, and "Down" reversing that change.

My program has two main functions to achieve its use-cases

Get a list of scripts off the filesystem

Execute the appropriate migrations on the database

The "Up" and "Down" migrations are stored in their own separate files, but they match with a similar naming scheme

2014000000000001_CreateTable_up.sql

2014000000000001_CreateTable_down.sql

There is a 1:1 correlation between up and down scripts.  Having just an up without the corresponding down script is not valid (and vise verse).

I have two classes in my project to represent these filesystem files.

```<code>public sealed class UpScript // (and DownScript, which looks identical)
{
    public UpScript(long version, string name, string content)
    {
        Content = content;
        Version = version;
        Name = name;
    }

    public long Version { get; private set; }
    public string Name { get; private set; }
    public string Content { get; private set; }
}
</code>```

The reason that I did not make a single class called Script is I didn't want to create ambiguity about the purpose of a specific Script instance.  UpScript and DownScript classes should not be used interchangeability as they do not conform to the Liskov Substitution Principle.

The problem that I have here is a few parts of code that are dealing with both either UpScript or DownScript instances look almost identical.  How do I reduce the duplication without losing the expressiveness of having different classes?

My current ideas with concerns are:

Abstract base class

```<code>public abstract class Script
{
    protected Script(long version, string name, content)
    {
        // code
    }

    // properties
}

public sealed UpScript : Script
{
    public UpScript(long version, string name, string content)
        : this(version, name, content)
    {}
}

public sealed DownScript : Script
{
    public DownScript(long version, string name, string content)
        : this(version, name, content)
    {}
}
</code>```

This reduces the redundant code in the two classes, however, code that creates and consumes is still very duplicated.

Single class with Direction property

```<code>public enum Direction { Up, Down }

public sealed class Script
{
    protected Script(Direction direction, long version, string name, string content)
    {
        // ...
    }

    public Direction Direction { get; private set; }

    // ...
}
</code>```

This code reduces the duplication, however, it adds onus on consumes to ensure the proper script is passed to it and it creates ambiguity if you ignore the Direction property.

Single class with two Content properties

```<code>public sealed class Script
{
    protected Script(long version, string name, string upContent, string downContent)
    {
        // ...
    }

    public string UpContent { get; private set; }
    public string DownContent { get; private set; }
}
</code>```

This reduces duplication and is not ambiguous, however, the usage of the program is to either run the up script, or run the down scripts.  With this scheme, the code that gathers and creates these Script instances is doing twice as much work, I don't consider not doing this being premature optimization because if the user wants to do an up migration, there's no point is looking at down scripts.

With all that said I may be looking at the wrong problem to solve entirely.

If more information would be helpful in forming a suggestion, you can view ScriptMigrations on GitHub

Body:
My C# is rusty, hopefully I haven't glossed over any language constraints.

I would implement UpScript and DownScript as interfaces that have the same members:

public interface IUpScript {
    public long Version { get; private set; }
    public string Name { get; private set; }
    public string Content { get; private set; }
}
// ...
public interface IDownScript {
    public long Version { get; private set; }
    public string Name { get; private set; }
    public string Content { get; private set; }
}

This approach attempts to provide the minimal code needed to create a distinction between up and down, nothing more. Thoughts:

Classes implementing an interface will have the common properties you've defined as in your other approaches but don't inherit implementation details like a constructor.

Your implementing classes would be free to extend other classes if they needed.

It looks as though you don't need to support multiple implementations of up and down scripts but you'd have no trouble doing so.


答:
Nothing can beat Guava's ImmutableMap with its optimized memory consumption, but here are a pair of pure solutions:</p>

```<code>/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
  private static final Map<Character, String> codes1;

  static {
    Map<Character, String> temp= new HashMap<Character, String>();
    temp.put('A', ".-");
    temp.put('B', "-...");
    temp.put('C', "-.-.");
    temp.put('D', "-..");
    temp.put('E', ".");
    temp.put('F', "..-.");
    // ...
    codes1 = Collections.unmodifiableMap(temp);
  }

  private static final Map<Character, String> codes2 = Collections.unmodifiableMap(new HashMap<Character, String>() {
    {
      put('A', ".-");
      put('B', "-...");
      put('C', "-.-.");
      put('D', "-..");
      put('E', ".");
      put('F', "..-.");
      // ...
    }
  });
}
</code>```

Title: Adding values to HashMap

Body:
Nothing can beat Guava's ImmutableMap with its optimized memory consumption, but here are a pair of pure solutions:

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
  private static final Map<Character, String> codes1;

  static {
    Map<Character, String> temp= new HashMap<Character, String>();
    temp.put('A', ".-");
    temp.put('B', "-...");
    temp.put('C', "-.-.");
    temp.put('D', "-..");
    temp.put('E', ".");
    temp.put('F', "..-.");
    // ...
    codes1 = Collections.unmodifiableMap(temp);
  }

  private static final Map<Character, String> codes2 = Collections.unmodifiableMap(new HashMap<Character, String>() {
    {
      put('A', ".-");
      put('B', "-...");
      put('C', "-.-.");
      put('D', "-..");
      put('E', ".");
      put('F', "..-.");
      // ...
    }
  });
}


答:
Most optimization algorithms (including heuristics) work on some configurations (in your example a route) by applying operations on them. The operations for itself should guarantee that they deliver only valid configurations, so first there should be unit tests for each of them. When you know for sure the optimization algorithm uses only those operations, there should typically be no need for a validity test of the algorithm's result.

To create good unit tests for any kind of more complex algorithm, one actually has to know the algorithm itself in detail. For simple heuristics like "hill climbing" you typically can predict the outcome for small inputs. For example, for initial routes of 3 to 5 points, when given in a certain order, you can predict what will happen. This will stay true for most deterministic heuristic algorithms I know of, so that's probably a good place to start.

For more complex algorithms, and bigger size of the input, when you just feed the input into the algorithm and try to check the output, you are actually not doing a unit test anymore, you are doing acceptance or integration test. The reason why you have problems to "unit test" such an algo is because it typically consists of a handful of smaller parts (individual units). So for really unit testing such an algorithm, you will have to identify those parts and test them individually. Additionally, you can use code coverage or branch coverage techniques to make sure you have enough test cases.

If you are not looking for unit-tests, but automated acceptance or integration tests, you can try what @Phillip suggested under (2) or (3).

Title: How do I unit test a heuristic algorithm?

Body:
Say we have our route finding algorithm:

```<code>def myHeuristicTSP(graph):
    /*implementation*/
    return route
</code>```

Now we want to unit test this:

```<code>class TestMyHeuristicTSP:
    def testNullGraphRaiseValueError(self):
        self.assertRaises(ValueError, myHueristicTSP(None))

    def testSimpleTwoNodeGraphReturnsRoute:
        self.assertEquals(expectedResult, myHeuristicTSP(input))
</code>```

The question is, for a non-heuristic TSP algorithm, we can give a variety of graphs and check that they always return absolutely the shortest route.

But because a heurtistic algorithm, while is still deterministic, is less predictable, are simply meant to understand how the algorithm is meant to be working, and find those edge cases?


答:
The solution with the abstract base class is the way to go.

To reduce duplication in the code that determines which scripts to process, you can introduce a factory class/method that creates either a UpScript or a DownScript instance based on a parameter (the same parameter that determines if the scripts with the "_up" or the "_down" suffix should be used).

If the execution order of the scripts depends on the direction, you can add a comparison method to Script (with implementations in UpScript and DownScript) to correctly order the Script instances.

Execution of the scripts then becomes as easy as iterating over an ordered collection without needing to know if you are upgrading or downgrading.


问:
how to effectively manage multiple occurrences of one application
I have developed a web application for a client which is live to their customers. Recently, the application has been sold in such as way that it is replicated to other domain names so there are 4+ instances of the application which I am to develop and maintain.

At the moment, each copy of the app has it own SVN repository and when it comes to making changes to the application that effects all instances, I update one and then use Beyond Compare to merge changes over to the other copies.

Would it be a better solution to use svn branches to maintain a core system and to merge out to sub branches and visa versa for bugs? Each application may have changes made to it that are client specific, such as logos, colours etc.

Are Branches the best way to go or continue to have each in their own repository and use BC to merge where necessary?

答:
Distributed version control where you have a separate repository for each instance and commit the changes to them as needed.

http://hginit.com/ might help understand it.

We're in a similar situation and it's not something Subversion does well at all.  We're looking at Mercurial as an alternative.

If that's not a short term option you need to separate each instance out into core code (which can be shared) and code which can not.  This at least minimises customer specific code and makes the scale of the problem smaller.


问:
What are the caveats of implementing fundamental types (like int) as classes?
When designing and implenting an object-oriented programming language, at some point one must make a choice about implementing fundamental types (like int, float, double or equivalents) as classes or something else. Clearly, languages in the C family have a tendency not to define them as classes (Java has special primitive types, C# implements them as immutable structs, etc).

I can think of a very important advantage when fundamental types are implemented as classes (in a type system with a unified hierarchy): these types can be proper Liskov subtypes of the root type. Thus, we avoid complicating the language with boxing/unboxing (either explicit or implicit), wrapper types, special variance rules, special behavior, etc.

Of course, I can partially understand why language designers decide the way they do: class instances tend to have some spatial overhead (because the instances may contain a vtable or other metadata in their memory layout), that primitives/structs don't need to have (if the language doesnt allow inheritance on those).

Is spatial efficiency (and improved spatial locality, especially in large arrays) the only reason why fundamental types are often not classes?

I've generally assumed the answer to be yes, but compilers have escape analysis algorithms and thus they can deduce whether they can (selectively) omit the spatial overhead when an instance (any instance, not just a fundamental type) is proven to be strictly local.

Is the above wrong, or is there something else I'm missing?

答:
Is spatial efficiency (and improved spatial locality, especially in large arrays) the only reason why fundamental types are often not classes?

No.

The other issue is that fundamental types tend to be used by fundamental operations. The compiler needs to know that int + int isn't going to be compiled to a function call, but to some elementary CPU instruction (or equivalent byte-code). At that point, if you have the int as a regular object, you're going to have to effectively unbox the thing anyways.

Those sort of operations also don't really play nice with subtyping. You can't dispatch to a CPU instruction. You can't dispatch from a CPU instruction. I mean the entire point of subtyping is so you can use a D where you can a B. CPU instructions aren't polymorphic. To get primitives to do that, you have to wrap their operations with dispatch logic that costs multiple times the amount of operations as the simple addition (or whatever). The benefit of having int be part of the type hierarchy becomes a little moot when it's sealed/final. And that's ignoring all of the headaches with dispatch logic for binary operators...

Basically, the primitive types would need to have a lot of special rules around how the compiler handles them, and what the user can do with their types anyway, so it is often times simpler to just treat them as completely distinct.


答:
Yes, it pretty much comes down to efficiency. But you seem to be underestimating the impact (or overestimating how well various optimizations work).

First, it's not just "spatial overhead". Making primitives boxed/heap-allocated has performance costs too. There's the additional pressure on the GC to allocate and collect those objects. This goes doubly if the "primitive objects" are immutable, as they should be. Then there's more cache misses (both because of the indirection and because less data fits into a given amount of cache). Plus the bare fact that "load the address of an object, then load the actual value from that address" takes more instructions than "load the value directly".

Second, escape analysis isn't go-faster fairy dust. It only applies to values that, well, don't escape. It's certainly nice to optimize local calculations (such as loop counters and intermediate results of calculations) and it will give measurable benefits. But a much larger majority of values live in the fields of objects and arrays. Granted, those can be subject to escape analysis themselves, but as they're usually mutable reference types, any aliasing of them presents a significant challenge to the escape analysis, which now has to prove that those aliases (1) don't escape either, and (2) don't make a difference for the purpose of eliminating allocations.

Given that calling any method (including getters) or passing an object as argument to any other method can help the object escape, you'll need interprocedural analysis in all but the most trivial cases. This is far more expensive and complicated.

And then there are cases where things really do escape and can't reasonably be optimized away. Quite many of them, actually, if you consider how often C programmers go through the trouble of heap-allocating things. When an object containing an int escapes, escape analysis ceases to apply to the int as well. Say goodbye to efficient primitive fields.

This ties into another point: The analyses and optimizations required are seriously complicated and an active area of research. It's debatable whether any language implementation ever achieved the degree of optimization you suggest, and even if so, it's been a rare and herculean effort. Surely standing on the shoulders of these giants is easier than being a giant yourself, but it's still far from trivial. Don't expect competitive performance any time in the first few years, if ever.

That is not to say such languages can't be viable. Clearly they are. Just don't assume it will be line-for-line as fast as languages with dedicated primitives. In other words, don't delude yourself with visions of a sufficiently smart compiler.

Title: What are the caveats of implementing fundamental types (like int) as classes?

Body:
When designing and implenting an object-oriented programming language, at some point one must make a choice about implementing fundamental types (like int, float, double or equivalents) as classes or something else. Clearly, languages in the C family have a tendency not to define them as classes (Java has special primitive types, C# implements them as immutable structs, etc).

I can think of a very important advantage when fundamental types are implemented as classes (in a type system with a unified hierarchy): these types can be proper Liskov subtypes of the root type. Thus, we avoid complicating the language with boxing/unboxing (either explicit or implicit), wrapper types, special variance rules, special behavior, etc.

Of course, I can partially understand why language designers decide the way they do: class instances tend to have some spatial overhead (because the instances may contain a vtable or other metadata in their memory layout), that primitives/structs don't need to have (if the language doesnt allow inheritance on those).

Is spatial efficiency (and improved spatial locality, especially in large arrays) the only reason why fundamental types are often not classes?

I've generally assumed the answer to be yes, but compilers have escape analysis algorithms and thus they can deduce whether they can (selectively) omit the spatial overhead when an instance (any instance, not just a fundamental type) is proven to be strictly local.

Is the above wrong, or is there something else I'm missing?


答:
In these cases, I suppose question is not about efficient method - but rather when do you actually need that map initialized and ready..

in the case of static initialization - by the time class is loaded

your lazy loading approach may be necessary if you need to set 'huge' map, and say often those values come from an expensive source (i.e across network), even then you may not need an external flag.

Collection.isEmpty() would tell you if that has already been initialized or not (provided, of course at least one value would be there to be initialized)

Title: Adding values to HashMap


答:
There are only very few cases where you need “fundamental types” to be full objects (here, an object is data that either contains a pointer to a dispatch mechanism or is tagged with a type that can be used by a dispatch mechanism):

You want user-defined types to be able to inherit from fundamental types. This is usually not wanted as it introduces performance- and security-related headaches. It is a performance problem because compilation cannot assume that an int will have a specific fixed size or that no methods have been overridden, and it is a security issue because semantics of ints could be subverted (consider an integer that is equal to any number, or that changes its value rather than being immutable).

Your primitive types have supertypes and you want to have variables with type of a supertype of a primitive type. For example, assume your ints are Hashable, and you want to declare a function that takes a Hashable parameter which might receive regular objects but also ints.

This can be “solved“ by making such types illegal: get rid of subtyping and decide that interfaces aren't types but type constraints. Obviously that reduces the expressiveness of your type system, and such a type system wouldn't be called object-oriented any longer. See Haskell for a language that uses this strategy. C++ is halfway there because primitive types do not have supertypes.

The alternative is full or partial boxing of fundamental types. The boxing type need not be user-visible. Essentially, you define an internal boxed type for each fundamental type and implicit conversions between the boxed and fundamental type. This can get awkward if the boxed types have different semantics. Java exhibits two problems: boxed types have a concept of identity whereas primitives only have a concept of value equivalence, and boxed types are nullable whereas primitives are always valid. These issues are completely avoidable by not offering a concept of identity for value types, offering operator overloading, and not making all objects nullable by default.

You do not feature static typing. A variable may hold any value, including primitive types or objects. Therefore all primitive types need to be always boxed in order to guarantee strong typing.

Languages that do have static typing do well to use primitive types wherever possible and only fall back to boxed types as a last resort. While many programs are not tremendously performance sensitive, there are cases where the size and makeup of primitive types is extremely relevant: Think of large-scale number crunching where you need to fit billions of data points into memory. Switching from double to float might be a viable space optimization strategy in C, but it would have next to no effect if all numeric types are always boxed (and therefore waste at least half of their memory for a dispatch mechanism pointer). When boxed primitive types are used locally, it is fairly straightforward to remove the boxing through the use of compiler intrinsics, but it would be short-sighted to bet the overall performance of your language on a “sufficienty advanced compiler”.


问:
Does overriding a method affect a superclass's call?
I'm trying to understand some of the nuances of inheritance but I can't find an answer to this question. Consider the following:

```<code>class SuperClass {
    method foo {
        print "in SuperClass.foo"
    }
    method bar {
        print "in SuperClass.bar"
        foo();
    }
}
class SubClass inherits SuperClass {
    method foo {
        print "in SubClass.foo"
    }
}

SubClass a = SubClass.new()
a.bar()
</code>```

Is the output this:

```<code>in SuperClass.bar
in SuperClass.foo
</code>```

Or this:

```<code>in SuperClass.bar
in SubClass.foo
</code>```

答: It depends. In some languages, the superclass foo () would be called by default, but there is a way to declare that you want the subclass version to be called instead (in c++ and c# you use the "virtual" keyword in the declaration of superclass.foo() to achieve this).  In others (e.g. Java and most dynamic languages like ruby, python and so on) the subclass version is always used.</p>


答:
Even when the method call originates in the superclass, it should call the overriding method in the subclass. This behaviour is sometimes called “open recursion”, and this feature is crucial for techniques like the “strategy pattern”. Open recursion is generally considered to be a fundamental concept of object-oriented programming, although it is not without problems.

There are some caveats as some languages add special requirements.

In some languages, you always have to invoke methods with the dot-notation for this to work. You'd have to say this.foo() rather than just foo().

Some languages require you to explicitly mark methods as overrideable. E.g. C++ would require the foo method to be marked virtual for this to work as expected. In most languages, methods can be overridden by default.

Title: Does overriding a method affect a superclass's call?

Body:
I'm trying to understand some of the nuances of inheritance but I can't find an answer to this question. Consider the following:

```<code>class SuperClass {
    method foo {
        print "in SuperClass.foo"
    }
    method bar {
        print "in SuperClass.bar"
        foo();
    }
}
class SubClass inherits SuperClass {
    method foo {
        print "in SubClass.foo"
    }
}

SubClass a = SubClass.new()
a.bar()
</code>```

Is the output this:

```<code>in SuperClass.bar
in SuperClass.foo
</code>```

Or this:

```<code>in SuperClass.bar
in SubClass.foo
</code>```


答:
ORMs are a tool in the programmers tool box. They have their own issues. Some examples are:

Can't control sql

Suffers from n+1 problem

Title: Is there still a need for writing SQL?


答:
It depends on the language you are using (and sometimes on how the methods are declared).

There are essentially two ways for the implementation to perform method calls: static dispatch and dynamic dispatch.

In static dispatch, the compiler determines at compile time exactly which method to call, without taking the possibility into account that there might be a sub-class that overrides the method.

With static dispatch, the output would be

In SuperClass.bar

  In SuperClass.foo

In dynamic dispatch, the compiler does take it into account that a sub-class might override the method, so it sets thing up that the runtime environment can call the right method in either the super class or the sub class.

With dynamic dispatch, the output would be

In SuperClass.bar

  In SubClass.foo

Which method of dispatch gets used depends on the language you use, how the methods are declared and how you perform the call.

In C++ and C#, the compiler uses static dispatch by default, unless the method was declared as virtual.

In Java, the compiler uses dynamic dispatch by default.


答:
Most implementations I'm aware of impose three restrictions on such classes that allow the compiler to efficiently use the primitive types as the underlying representation the vast majority of the time.  These restrictions are:

Immutability

Finality (unable to be derived from)

Static typing

The situations where a compiler needs to box a primitive into an object in the underlying representation are relatively rare, such as when an Object reference is pointing to it.

This adds a fair bit of special case handling in the compiler, but it's not just limited to some mythical super-advanced compiler.  That optimization is in real production compilers in major languages.  Scala even allows you to define your own value classes.


问:
Understanding memory update propagation in x86/x86-64 CPU L1/L2/L3 caches and RAM
I'm trying to understand in a general sense how L1/L2 (and now L3 caches) are updated and how the updates are propagated in a multi-core x86/x86-64 CPU.

Assuming a 4 core CPU and 2 pairs of L1/L2 caches, where pairs of cores share a common L1/L2 pair and there's an interconnect between the 2 L1/L2 pairs. And the cache lines are 64-bit wide.
So we have:

Core-0/Core-1 on (L1/L2)-0

Core-2/Core-3 on (L1/L2)-1

(L1/L2)-0 is connected to (L1/L2)-1

Let's say there is a thread T0 running on Core-0 that is writing to a 64-bit integer variable called X, and there's another thread T1 on Core-3 continually reading variable X's value - Please ignore the logical race conditions for a moment.

Question:
Assuming X has been cached in Core-0's L1. When T0 writes a new value to X, Is the following sequence of events correct?

X's value is pushed from register to L1-0

X's value is pushed from L1-0 to L2-0

X's value is pushed from L2-0 to L2-1

X's value is pushed from L2-1 to L1-1

X's value is pushed from L1-0 to RAM

Note: Steps 2 and 4 may happen concurrently.

答:
First if you are concerned about recent (last 5-10 years, since Nahalem?) Intel x86 architecture, then you're a little off in your description of the caches.

Each core has their own 128K L1 cache split (64K data / 64K code). Above that, each core has its own L2 cache which basically acts as a buffer between the L1 and L3 cache. Each socket has its own L3 cache (up to 20MB, I think). The L1 and L2 caches are small, simple, and quick. The L3 cache is much larger and more complex (it is divided into small segments that all sit on a ring with other things like the memory controller and QPI bridge to other sockets). (Please ignore things like the load and store buffers that will make this even more complex.)

Also, cache lines are 64-bytes.

So it looks like this (on for example a dual socket machine, with 4 cores per CPU):

```<code>Core 0 (socket 0) -> L1-0 -> L2-0 -> L3-0 -> QPI link to socket 1
Core 1 (socket 0) -> L1-1 -> L2-1 -> ^
Core 2 (socket 0) -> L1-2 -> L2-2 -> |
Core 3 (socket 0) -> L1-3 -> L2-3 -> +

Core 4 (socket 1) -> L1-4 -> L2-4 -> L3-1 -> QPI link to socket 0
Core 5 (socket 1) -> L1-5 -> L2-5 -> ^
Core 6 (socket 1) -> L1-6 -> L2-6 -> |
Core 7 (socket 1) -> L1-7 -> L2-7 -> +
</code>```

Pre Nahalem, L2 caches were shared among core pairs. I haven't had to do a lot of performance work on this in a while, so I'm not really sure of the subtleties there.

The L3 cache is fully inclusive of the L1 and L2 caches below it. The cache contains the "correct" values for all memory addresses.

More correct than main memory, since writes can sit in L3 for a while before going to memory (write-back caching). All caches are coherent. That is, you will never have two different values for the same memory location. This coherency is maintained by a version of the MESI protocol, called MESIF (for Intel, AMD has a different caching strategy and uses MEOSI and arranged their caching differently).

Since the L1 and L2 are private to the core, the coherence only has to be managed at the L3 level (I think, I've been unable to get a definite answer on this). The cache interconnects have four lanes: data, request, acknowledge, and snoop (to keep up to date on other memory operations).

Now, we can get down to your questions.

If a thread on Core 0 is reading an address, the address will reside in L1-0 and L3-0 in either the Exclusive, Shared, or Forward state (all three show that the address is unmodified and cached). Now, Core-4 wants to write to it. A Request/Read-For-Ownership will send the cache line from the other L3 cache (L3-0) and cause the other caches to mark their copies as Invalid. It will now be in L1-4 and L3-1 (marked as Exclusive).

(Here is where ignoring store buffers simplified a lot.)

Core-4 will write from a register to the L1-4 cache. Causing to transition the line to the Modified state. This gets propagated to the L3-1 cache (since it is fully inclusive).

Now, Core-0 wants to read again. The L1-0 cache is Invalid at that address, so it sends a read request that misses the L3-0 cache and causes the L3-1 to send the cache line back across. The L3-1 now states that address is Shared, and the L3-0 holds the line as Forward (the most recent requester gets the Forwarding responsibility).

Clear as mud? There might be a few edits to this to clean up some of the language that I might be too vague on.

ContentLicense: CC BY-SA 4.0

Body:
First if you are concerned about recent (last 5-10 years, since Nahalem?) Intel x86 architecture, then you're a little off in your description of the caches.

Each core has their own 128K L1 cache split (64K data / 64K code). Above that, each core has its own L2 cache which basically acts as a buffer between the L1 and L3 cache. Each socket has its own L3 cache (up to 20MB, I think). The L1 and L2 caches are small, simple, and quick. The L3 cache is much larger and more complex (it is divided into small segments that all sit on a ring with other things like the memory controller and QPI bridge to other sockets). (Please ignore things like the load and store buffers that will make this even more complex.)

Also, cache lines are 64-bytes.

So it looks like this (on for example a dual socket machine, with 4 cores per CPU):

Core 0 (socket 0) -> L1-0 -> L2-0 -> L3-0 -> QPI link to socket 1
Core 1 (socket 0) -> L1-1 -> L2-1 -> ^
Core 2 (socket 0) -> L1-2 -> L2-2 -> |
Core 3 (socket 0) -> L1-3 -> L2-3 -> +

Core 4 (socket 1) -> L1-4 -> L2-4 -> L3-1 -> QPI link to socket 0
Core 5 (socket 1) -> L1-5 -> L2-5 -> ^
Core 6 (socket 1) -> L1-6 -> L2-6 -> |
Core 7 (socket 1) -> L1-7 -> L2-7 -> +

Pre Nahalem, L2 caches were shared among core pairs. I haven't had to do a lot of performance work on this in a while, so I'm not really sure of the subtleties there.

The L3 cache is fully inclusive of the L1 and L2 caches below it. The cache contains the "correct" values for all memory addresses.

More correct than main memory, since writes can sit in L3 for a while before going to memory (write-back caching). All caches are coherent. That is, you will never have two different values for the same memory location. This coherency is maintained by a version of the MESI protocol, called MESIF (for Intel, AMD has a different caching strategy and uses MEOSI and arranged their caching differently).

Since the L1 and L2 are private to the core, the coherence only has to be managed at the L3 level (I think, I've been unable to get a definite answer on this). The cache interconnects have four lanes: data, request, acknowledge, and snoop (to keep up to date on other memory operations).

Now, we can get down to your questions.

If a thread on Core 0 is reading an address, the address will reside in L1-0 and L3-0 in either the Exclusive, Shared, or Forward state (all three show that the address is unmodified and cached). Now, Core-4 wants to write to it. A Request/Read-For-Ownership will send the cache line from the other L3 cache (L3-0) and cause the other caches to mark their copies as Invalid. It will now be in L1-4 and L3-1 (marked as Exclusive).

(Here is where ignoring store buffers simplified a lot.)

Core-4 will write from a register to the L1-4 cache. Causing to transition the line to the Modified state. This gets propagated to the L3-1 cache (since it is fully inclusive).

Now, Core-0 wants to read again. The L1-0 cache is Invalid at that address, so it sends a read request that misses the L3-0 cache and causes the L3-1 to send the cache line back across. The L3-1 now states that address is Shared, and the L3-0 holds the line as Forward (the most recent requester gets the Forwarding responsibility).

Clear as mud? There might be a few edits to this to clean up some of the language that I might be too vague on.


答:
In Smalltalk all of them (int, float, etc.) are first class objects. The only special case is that SmallIntegers are codified and treated differently by the Virtual Machine for the sake of efficiency, and therefore the SmallInteger class will not admit subclasses (which is not a practical limitation.) Note that this doesn't require any special consideration on the part of the programmer as the distinction is circumscribed to automatic routines like code generation or garbage collection.

Both the Smalltalk Compiler (source code -> VM bytecodes) and the VM nativizer (bytecodes -> machine code) optimize the code generated (JIT) so that to reduce the penalty of elementary operations with these basic objects.


问:
How to abbreviate variable names
I always struggle in abbreviating variable names. Is there any standard for abbreviating variable names?</p>

答:
You shouldn't abbreviate stuff for the sake of abbreviating stuff, you should do it for your/others convenience, but if you want to then a general rule that I have for abbreviation is if a word is more than four or five letters long then I'll shorten it to the first three significant letters of that word, e.g.:

```<code>int damagePerSecond;
</code>```

could be abbreviated to

```<code>int dmgPerSec;
</code>```

or if you want it a short as possible,

```<code>int dps;
</code>```

Title: How to abbreviate variable names

Body:
You shouldn't abbreviate stuff for the sake of abbreviating stuff, you should do it for your/others convenience, but if you want to then a general rule that I have for abbreviation is if a word is more than four or five letters long then I'll shorten it to the first three significant letters of that word, e.g.:

int damagePerSecond;

could be abbreviated to

int dmgPerSec;

or if you want it a short as possible,

int dps;


答:
If you know what you are doing you can effectively use an ORM to replace much of your CRUD type code. They are not as effective for complex things though, they are hard to performance tune (you do know that performance is one of the critical parts of database design, not emulating objects) and they are downright horrible and dangerous in the hands of someone who doesn't understand or write SQL themselves.

I also want to point out that complex reporting is not easy to effectively do with an ORM. And further if you don't learn the simple SQL in the easy crud stuff, how will you ever get to the point where you can write complex SQL for reporting? I've never worked in an application that didn't have reporting needs and often quite complicated ones.

Nor are ORMs useful for BI or ETL processes for the most part. Nor are they useful for database admin queries or for finding information in the audit tables and undoing a particular set of database changes. There are many many things that are still most effectively done with SQL. The application querying the database is a small portion of what needs to query it in an Enterprise environment.

I also see many questions about how to do something using an ORM that the poster already  knows how to do in SQL. It's nice to learn new things, but when they are causing extra time and effort with no real gain over the orginal method (and often a real loss of performance), why are you using them other than they are "fashionable" right now.

Title: Is there still a need for writing SQL?


答:
If in doubt, spell it out.

The point of a variable name is so that the meaning of the code is clearer. Unless the abbreviation is very obvious one, then you may as well just use the smallest one possible. Variable names and function names are typically the only bits of human language in the code and so act both as 'landmarks' for the human eye to find relevant portions of code (or, in a large codebase, tools like grep or ack) and also as clues for comprehension.

When the next person comes to read your code, they will thank you for it. That person could well be you in a year's time. I have a lot of code I regret abbreviating, so nowadays I try to avoid it.

It's ok to abbreviate when...

... When the abbreviated form is used in spoken or written English by more than just the people working on your project (many dictionaries give this sort of information next to the term they define).

```<code>var extensible_markup_language_element; // don't do this
var xml_element; // better
var element; // possible if the name of the function or the documentation make it clear you're dealing with XML and not the periodic table
docs.toString(); // most people capable of reading code know docs == documentation
</code>```

... When the abbreviation refers unambiguously to a single concept and would be instantly recognised by someone who is not familiar with the codebase. Even then a comment or piece of documentation helps.

```<code>var auth = user.auth;
if (auth) // If the user is authenticated?
          // If the user is authorised to do something?
          // If the authentication function exists for that user group?
          // If some setting called auth is turned on for that user?
          // If the user is the author of the document in question?
          // If the user has some authority?

var attrNames = retrieveAttrs();
if (attrNames)  // hm, attrNames sounds like an array of strings - which will be boolean true even if empty - this if looks like a bug!

const MDF // author is writing an iOS app for ordering hand-carved artisanal fibreboard so anyone familiar with the problem domain knows this has plainly nothing to do with Microsoft Database Files. Though maybe the first time it comes up in the code the author should perhaps still put its full name
</code>```

... When the variable name exists only in a single scope or small function, and you do not expect the user to derive meaning from the name, use a single character. In such cases, i and j are common.

```<code>foreach $i (1..10) { say $announcement->[$i] }
</code>```

... When writing an interface (i.e. not a variable name, so outside of the scope of the question, mentioned only because variable names and interfaces which set them often use the same vocabulary) in which case other rules may apply, for instance:

```<code>some_command --transaction-message "Done" # a bit wordy - keep, but ALSO allow for convenience:
some_command --msg "Done" # might be useful
some_command -m "Done"    # if you can spare -m
</code>```

... When your codebase needs to refer to the same concept many times in the same project and when the abbreviation can be defined in a style guide for that project, and when it is unambiguous. If your project is not big enough for a style guide then it's not big enough for it to be worth it.

I'm not going to provide a code example to this one because by definition it only works in a large project, but see also the next item:

... When working on an established project which has had multiple contributors and a style guide which mandates abbreviations. In which case, abbreviate only as per the style guide, but look out for problems and be prepared to annotate with comments (like "this is a list of attribute names as strings").

Types should end in “_t” ; Raw struct definitions in “_struct”

- https://metacpan.org/source/SHLOMIF/XML-LibXML-2.0117/HACKING.txt

One final thought: if you still have unacceptably long variable names (e.g. composed of four or more semantic units like totalAfterTaxInLocalCurrency), it could be a symptom that your code is trying to do too much in a single scope and its functions need to be refactored out or your variables might be more logically managed in a single object.

Title: How to abbreviate variable names

Body: I always struggle in abbreviating variable names. Is there any standard for abbreviating variable names?</p>

Body:
If in doubt, spell it out.

The point of a variable name is so that the meaning of the code is clearer. Unless the abbreviation is very obvious one, then you may as well just use the smallest one possible. Variable names and function names are typically the only bits of human language in the code and so act both as 'landmarks' for the human eye to find relevant portions of code (or, in a large codebase, tools like grep or ack) and also as clues for comprehension.

When the next person comes to read your code, they will thank you for it. That person could well be you in a year's time. I have a lot of code I regret abbreviating, so nowadays I try to avoid it.

It's ok to abbreviate when...

... When the abbreviated form is used in spoken or written English by more than just the people working on your project (many dictionaries give this sort of information next to the term they define).

var extensible_markup_language_element; // don't do this
var xml_element; // better
var element; // possible if the name of the function or the documentation make it clear you're dealing with XML and not the periodic table
docs.toString(); // most people capable of reading code know docs == documentation

... When the abbreviation refers unambiguously to a single concept and would be instantly recognised by someone who is not familiar with the codebase. Even then a comment or piece of documentation helps.

var auth = user.auth;
if (auth) // If the user is authenticated?
          // If the user is authorised to do something?
          // If the authentication function exists for that user group?
          // If some setting called auth is turned on for that user?
          // If the user is the author of the document in question?
          // If the user has some authority?

var attrNames = retrieveAttrs();
if (attrNames)  // hm, attrNames sounds like an array of strings - which will be boolean true even if empty - this if looks like a bug!

const MDF // author is writing an iOS app for ordering hand-carved artisanal fibreboard so anyone familiar with the problem domain knows this has plainly nothing to do with Microsoft Database Files. Though maybe the first time it comes up in the code the author should perhaps still put its full name

... When the variable name exists only in a single scope or small function, and you do not expect the user to derive meaning from the name, use a single character. In such cases, i and j are common.

foreach $i (1..10) { say $announcement->[$i] }

... When writing an interface (i.e. not a variable name, so outside of the scope of the question, mentioned only because variable names and interfaces which set them often use the same vocabulary) in which case other rules may apply, for instance:

some_command --transaction-message "Done" # a bit wordy - keep, but ALSO allow for convenience:
some_command --msg "Done" # might be useful
some_command -m "Done"    # if you can spare -m

... When your codebase needs to refer to the same concept many times in the same project and when the abbreviation can be defined in a style guide for that project, and when it is unambiguous. If your project is not big enough for a style guide then it's not big enough for it to be worth it.

I'm not going to provide a code example to this one because by definition it only works in a large project, but see also the next item:

... When working on an established project which has had multiple contributors and a style guide which mandates abbreviations. In which case, abbreviate only as per the style guide, but look out for problems and be prepared to annotate with comments (like "this is a list of attribute names as strings").

Types should end in “_t” ; Raw struct definitions in “_struct”

- https://metacpan.org/source/SHLOMIF/XML-LibXML-2.0117/HACKING.txt

One final thought: if you still have unacceptably long variable names (e.g. composed of four or more semantic units like totalAfterTaxInLocalCurrency), it could be a symptom that your code is trying to do too much in a single scope and its functions need to be refactored out or your variables might be more logically managed in a single object.


答:
How do I reduce the duplication without losing the expressiveness of having different classes?

By considering the scenarios in which your program interacts with the scripts, as stated in your top-level description:

Get a list of scripts off the filesystem

Execute the appropriate migrations on the database

The first decision is which up or down scripts to apply during migration:

```<code>public interface IScriptSource
{
    IEnumerable<IScript> ReadUpScripts();

    IEnumerable<IScript> ReadDownScripts();
}
</code>```

The second decision is to execute each script, which will move the database forward or backward in time:

```<code>public interface IScript
{
    void Execute();
}
</code>```

This gives us a nice basis for addressing your primary concern:

The problem that I have here is a few parts of code that are dealing with both either UpScript or DownScript instances look almost identical.

With these top-level abstractions in place, we can shape implementations around shared details:

```<code>public abstract class Script : IScript
{
    protected Script(long version, string name, string content)
    {
        Version = version;
        Name = name;
        Content = content;
    }

    protected long Version { get; private set; }
    protected string Name { get; private set; }
    protected string Content { get; private set; }

    public virtual void Execute()
    {
        SomethingShared();

        MoveInDirection();

        SomethingElseShared();
    }

    protected abstract void MoveInDirection();
}
</code>```

Then differentiate the specifics of each type:

```<code>public sealed class UpScript : Script
{
    public UpScript(long version, string name, string content)
        : base(version, name, content)
    {}

    protected override void MoveInDirection()
    {
        // Up-specific
    }
}

public sealed class DownScript : Script
{
    public DownScript(long version, string name, string content)
        : base(version, name, content)
    {}

    protected override void MoveInDirection()
    {
        // Down-specific
    }

    protected override SomethingElseShared()
    {
        base.SomethingElseShared();

        // Down-specific
    }
}
</code>```

This will help consolidate the spread-out code by pairing it directly with the data.

It also gets the Liskov stamp of approval due to IScriptSource hiding the concrete types.

Body:
How do I reduce the duplication without losing the expressiveness of having different classes?

By considering the scenarios in which your program interacts with the scripts, as stated in your top-level description:

Get a list of scripts off the filesystem

Execute the appropriate migrations on the database

The first decision is which up or down scripts to apply during migration:

public interface IScriptSource
{
    IEnumerable<IScript> ReadUpScripts();

    IEnumerable<IScript> ReadDownScripts();
}

The second decision is to execute each script, which will move the database forward or backward in time:

public interface IScript
{
    void Execute();
}

This gives us a nice basis for addressing your primary concern:

The problem that I have here is a few parts of code that are dealing with both either UpScript or DownScript instances look almost identical.

With these top-level abstractions in place, we can shape implementations around shared details:

public abstract class Script : IScript
{
    protected Script(long version, string name, string content)
    {
        Version = version;
        Name = name;
        Content = content;
    }

    protected long Version { get; private set; }
    protected string Name { get; private set; }
    protected string Content { get; private set; }

    public virtual void Execute()
    {
        SomethingShared();

        MoveInDirection();

        SomethingElseShared();
    }

    protected abstract void MoveInDirection();
}

Then differentiate the specifics of each type:

public sealed class UpScript : Script
{
    public UpScript(long version, string name, string content)
        : base(version, name, content)
    {}

    protected override void MoveInDirection()
    {
        // Up-specific
    }
}

public sealed class DownScript : Script
{
    public DownScript(long version, string name, string content)
        : base(version, name, content)
    {}

    protected override void MoveInDirection()
    {
        // Down-specific
    }

    protected override SomethingElseShared()
    {
        base.SomethingElseShared();

        // Down-specific
    }
}

This will help consolidate the spread-out code by pairing it directly with the data.

It also gets the Liskov stamp of approval due to IScriptSource hiding the concrete types.


答:
Sometimes a client just wants a quick and easy query to return data for a report, export, datadump, etc and want to wait for an entire program be developed.

Also, a good SQL programmer can always write faster, more efficent SQL than any ORM I have used.  Also, I have found a lot of people just have the ORM point to stored procedures - really ignoring the benefits of the ORM cause ORM's are not great for complex processes.

Also, when using a database like Oracle with a very rich and powerful procedure language, you can do a lot without ever needed a "program".  PL/SQL on Oracle in the right hands is very fast and efficent.

Title: Is there still a need for writing SQL?


问:
How can I develop a productive Git(hub) branch workflow for an open source project?
I am writing a simple framework that I want to open source just for experience (and fun!). However, it has some cool ideas that could make it grow to a larger project and I want to be ready if that ever happens. I highly doubt that that will happen, but I want to use this as a learning experience on how to properly run an open source project.

I want to dive right into the development. I'm not too worried about the actual code since it should be mostly simple. However, I'm not that experienced with Github. I mean, I know all the basics and such, but I don't really know how to use all of the tools to my advantage.

How should I manage a workflow to best accommodate developers? I'm going to try to encourage the "standard" procedure:

Fork the repository

Clone the repository to your Git client

Make a new branch for the work

Do the actual work

Commit your work (if multiple commits, rebase them to create one commit for easy history on the main repo)

Submit a pull request with that one commit

Then, obviously, I will choose if I want to pull it or not. Here's where I get stuck. How should I manage my branches?

I drafted up this design:

Proposed Workflow:

Basically:

The master branch is for stable releases. Individual pull requests are only sent to the master branch if it's a critical bug and needs an individual release ASAP.

The beta branch is for the code for the next stable release. Bug fixes will be pulled to this branch.

The alpha branch is where the feature requests are added.

When a commit (not a pull request) is added to either the master or beta branch, the changes are "cascading" (i.e. a pull request is automatically created so that a commit to master will also be on beta and alpha; a commit on beta will be on alpha). I would do this with a simple script. Albeit it'd be somewhat ghetto, but it'd be automatic.

For a standard release, the beta would be merged into the master and then the alpha into the beta branch.

The reason for this is the feature requests aren't put into the next version so they're stable enough to be in the stable release.

Is this dumb? A consolidated "dev" branch would be the easiest to manage, but I'm afraid that some bugs would still get through. I guess I'd have to stop accepting feature additions a little bit before I release a new version.

EDIT: This question is extremely similar to my question: Is there an established or defined best practice for source control branching between development and production builds?. However, I'm looking at my proposed method vs. just not handling pull requests before a new release. Also, this is about open source software (so it might be harder to train new people on the system for this project).

答: Yes, use GitHub, it is the most popular and well-used. Have a public repo where you encourage people to commit on the beta branch. Don't have too many branches where it gets confusing or unmanageable. Instead, if you want to see new versions of the framework, encourage them to fork it. You could consider consolidating your alpha and beta branches. Good luck! </p>


答:
I was designing an OO langauge and runtime (this failed for a completely different set of reasons).

There is nothing inherently wrong with making things like int true classes; in fact this makes the GC easier to design as there are now only 2 kinds of heap headers (class & array) rather than 3 (class, array, and primitive) [the fact that we can merge class & array after this is not relevant].

The real important case the primitive types should have mostly final/sealed methods (+ really matters, ToString not so much). This allows the compiler to staticly resolve almost all calls to the functions themselves and inline them. In most cases this doesn't matter as copying behavior (I chose to make embedding available at language level [so did .NET]), but in some cases if the methods aren't sealed the compiler will be forced to generate the call to the function used to implement int + int.


问:
jQuery event binding management
Given the following elements:

```<code><div class="container">
  <span class="some-class">content</span>
  ..n span repetitions..
</div>
</code>```

Given the following .on()

```<code>$('.some-class').on('click', function () { ... });
</code>```

If you redraw the .container with new span.some-class, will you leak the old events?

What I mean is, before the redraw, should you do:

```<code>$('.some-class').off('click');
</code>```

Thanks!

答:
If you attach your event listener like this:

```<code>$(document).on({
    click: function () {
        // ...
    }
}, '.some-class');
</code>```

Then your event listener will not "leak" as you put it.  You can redraw, add additional elements with .some-class and they will all inherit the event listener.  This has the added benefit of only registering one event listener instead of "x" listeners depending on how many .some-class elements there are.  Much better performance.

Title: jQuery event binding management

Body:
If you attach your event listener like this:

$(document).on({
    click: function () {
        // ...
    }
}, '.some-class');

Then your event listener will not "leak" as you put it.  You can redraw, add additional elements with .some-class and they will all inherit the event listener.  This has the added benefit of only registering one event listener instead of "x" listeners depending on how many .some-class elements there are.  Much better performance.


问:
Is there a conventional way to combine file path strings?
In an example:

```<code>var assets = "images/"

var sounds = assets+"sounds/"
</code>```

Is it more conventional to put the slash on the back of a file path?

```<code>var assets = "/images"

var sounds = assets+"/sounds"
</code>```

Is there another method that is a good common practice?

答:
I think there is no magic or "common practice" on how to implement paths, but certainly string concatenation is not the way to go. You can develop your own API for dealing with cases, but it may require some effort. In particular, you should be careful about different platforms. For example, in Windows \ is the separator while in Unix-based systems / is the separator.

I'm not familiar with Javascript libraries, but I'm sure there should be libraries for handling these cases. In Java, for example, you can use the Path API
 to deal with platform independent path operations.


答:
In Java, the answer would be "neither of the above".  Best practice would be to assemble pathnames using the java.io.File class; e.g.

```<code>File assets = new File("images");
File sounds = new File(assets, "sounds");
</code>```

The File class also takes care of platform-specific pathname separators.

There is a separate issue of whether your pathname should start with a slash or not.  But that is more to do with correctness than best practice.  A pathname that starts with a slash means something different to a pathname that doesn't!!

There isn't explicit support for pathname handling in the core (ECMA) Javascript library, but (at least) Node.js provides support via the Path module.

Title: Is there a conventional way to combine file path strings?

Body:
In an example:

```<code>var assets = "images/"

var sounds = assets+"sounds/"
</code>```

Is it more conventional to put the slash on the back of a file path?

```<code>var assets = "/images"

var sounds = assets+"/sounds"
</code>```

Is there another method that is a good common practice?

Body:
In Java, the answer would be "neither of the above".  Best practice would be to assemble pathnames using the java.io.File class; e.g.

File assets = new File("images");
File sounds = new File(assets, "sounds");

The File class also takes care of platform-specific pathname separators.

There is a separate issue of whether your pathname should start with a slash or not.  But that is more to do with correctness than best practice.  A pathname that starts with a slash means something different to a pathname that doesn't!!

There isn't explicit support for pathname handling in the core (ECMA) Javascript library, but (at least) Node.js provides support via the Path module.


问:
Infix vs Prefix Notation - Which do you prefer?
I have been learning Clojure and looking at Scheme and CL which introduced me to the world of prefix notation. At first I didn't like it but it is still starting to grow on me. To be honest though, there are still long calculations that are difficult for me to understand but I think that is an issue of me needing more exposure/practice and I'll get it.

But that leads me to the question: Which type of notation do you prefer and why?

答:
I like prefix for function-like things, infix for operator-like things, postfix for property-like things, and mixfix for control-flow like things:

```<code>// prefix:
abs(-3)
sin(PI)

// infix:
1 + 2
4 / 5

// postfix:
list size
employee name

// mixfix:
if a then b else c // (where if/then/else is the mixfix function)
</code>```

What I don't like is languages that don't let me express things the way that reads most naturally to me. I don't like:

```<code>// lisp, have to do prefix for everything:
(+ 1 2)
(if a b c)
(size list)

// forth, have to do postfix for everything:
1 2 +
a b c if
1 + 2
4 / 5
</code>```

Body:
I like prefix for function-like things, infix for operator-like things, postfix for property-like things, and mixfix for control-flow like things:

// prefix:
abs(-3)
sin(PI)

// infix:
1 + 2
4 / 5

// postfix:
list size
employee name

// mixfix:
if a then b else c // (where if/then/else is the mixfix function)

What I don't like is languages that don't let me express things the way that reads most naturally to me. I don't like:

// lisp, have to do prefix for everything:
(+ 1 2)
(if a b c)
(size list)

// forth, have to do postfix for everything:
1 2 +
a b c if
1 + 2
4 / 5


答:
My personal preference is this:

```<code>var assets = "/images"

var sounds = assets+"/sounds"
</code>```

I always use absolute paths (/images/...), it feels less prone to error, to me.  It is also more fool proof to use var sounds = assets+"/sounds" because even if assets had a trailing slash and you ended up with /images//sounds, it would still resolve to /images/sounds.  The one disclaimer being that it depends on your request handler.  Apache seems to handle it fine (at least certain versions/configurations, see http://www.amazon.com//gp//site-directory//ref=nav_sad).  With the other way you'd end up with /imagessounds, not so fool proof :)  There is also the option of checking for double slashes and cleaning them up.  Not an option with the other approach.

Body:
My personal preference is this:

var assets = "/images"

var sounds = assets+"/sounds"

I always use absolute paths (/images/...), it feels less prone to error, to me.  It is also more fool proof to use var sounds = assets+"/sounds" because even if assets had a trailing slash and you ended up with /images//sounds, it would still resolve to /images/sounds.  The one disclaimer being that it depends on your request handler.  Apache seems to handle it fine (at least certain versions/configurations, see http://www.amazon.com//gp//site-directory//ref=nav_sad).  With the other way you'd end up with /imagessounds, not so fool proof :)  There is also the option of checking for double slashes and cleaning them up.  Not an option with the other approach.


答:
When building paths I often use a function that adds the trailing slash if it isn't already there.  Then paths can be built like:

```<code>filename := fs( 'assets') + fs( 'images') + fs( 'icons') + 'some.png';
</code>```

where fs() adds a trailing slash if its needed.

Body:
When building paths I often use a function that adds the trailing slash if it isn't already there.  Then paths can be built like:

filename := fs( 'assets') + fs( 'images') + fs( 'icons') + 'some.png';

where fs() adds a trailing slash if its needed.


问:
Version control for code that contains student exercises
I have a fairly substantial Python project that I have developed as an educational endeavor.  The version of the code that shall be given to students has exercises throughout, in the form of code that I have deleted and replaced with an exception.  To be specific:

```<code>    def mk_eq_term(i):
        # raise ExerciseError("BitBlaster::bitblast_EQ_Core")
        return PL.And(val,PL.Iff(le.bits[i],re.bits[i]))
</code>```

The last line is the real code; the second line is what shall be in the code given to students, once un-commented.  I am not an expert on version control (in fact, at present, I do not use revision control), but my reading on the subject indicates that this use case is suboptimal.  It seems like I will have to maintain two separate branches, and that any change I make against the "production" version will need to be reconciled against the "educational" version, even though I do not expect or intend to make changes to the codebase that will modify the exercise solutions.

What is the best solution for maintaining something like this?

答:
When you use git as version control you can.

use your full code as trunk.

branch of your students version.

continue dev on trunk.

merge trunk into branch.

do new adjustments for changed     code in students branch.

All changes in the students branch will persist, git will only take new changes from trunk and add those to the branch,
You will probably see conflicts when changing code on trunk that you have also altered on branch, but those should be easy to resolve. In most if not all cases you will want to take the trunk version, then do your fresh adjustments to branch.


问:
Capitalizing custom methods in a SDK based project
In projects which need heavy SDK usage, like Android and iOS development, I want the methods/functions I write to be obvious and since the whole framework is written with lower case method names I would like to have my method names start with upper case.

However is this a good approach if there are going to be other programmers included in the project? Would this create mental overhead & confusion or would it really simplify things?

```<code>{
    didReceiveMemoryWarning(); // obviously a framework method
    MemoryWarning(); // obviously custom method

    item.height(); // obviously a framework method
    item.SeventhDimensionOfItem(); // obviously custom extension
}
</code>```

答:
Unless you have any compelling reason, it is usually recommended to stick to the code conventions of the programming language you are using. Changing method naming conventions could make developers think that they might be consuming some external service or maybe crossing some other boundaries.

If you would like to point out that the method is not available from the default SDK, then I think that the best place to point that out is to include it in your method documentation. Most IDE's nowadays are able to show documentation such as JavaDoc and NDoc through their intellisense capability.


问:
Is there still a need for writing SQL?
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.

答: It's still required for writing triggers and stored procedures.  Stored procedures may have fallen out of favor currently, but they're still very useful in some situations.  SQL may also be required for some particularly hairy multi-table joins.</p>

Title: Is there still a need for writing SQL?


答:
Note that in .NET you should use the Path.Combine method.

```<code>var path = System.IO.Path.Combine("assets", "sounds");
</code>```

The reason for this is that it 'knows' the correct characters to be used when constructing the folder names.

This takes away the 'problem' of pre or post fixing.

Body:
Note that in .NET you should use the Path.Combine method.

var path = System.IO.Path.Combine("assets", "sounds");

The reason for this is that it 'knows' the correct characters to be used when constructing the folder names.

This takes away the 'problem' of pre or post fixing.