问:
Should I include `assembly` as programming language in the CV?
In the answer for one question someone wrote that assembly is not a language, it's a process. I tend to agree, since the assembly "language" is dependent on the architecture it will run on, which may differ quite a bit from one CPU to another.

So if you've written assembly for one architecture, does that mean you can include it in the CV under merely assembly along with the other programming languages? Or do you explicitly say that you've written assembly for that particular architecture?

EDIT: Changed 'dabbled' to 'written'. English isn't my native language and I misunderstood the term, thinking it meant that you've used it a lot instead of just a bit.

答:
I think there are different nearly orthogonal reasons for writing assembler, and there may not be much commonality other than being passable conversant in the assembler language. Examples would include:

(1) Creating world beating performance for imporatnt math kernels. Knows math, the computer architecture, etc.

(2) Wrote lots of assembler in order to debug new hardware. May know little about the performance characteristics of the given machine, but knows a heck of a lot about hardware verification.

(3) Can read compiler generated assembler as a tool for debugging.

(4) Can use assembler to get at HW features unsupported by higher level languages.

(5) Writes compiler backends, and looks at generated assembler in order to tweak code generation/optimization algorithms as part of the compiler team.

In general, I think the correlation in skills among these distinct tasks is probably not very high. Hire someone with experience and demonstrated skill at task M for a job that requires task N, and you may be seriously dissapointed in the results.


问:
How does recursive backtracking work ?
I am trying to figure out recursive backtracking, i have good understanding of recursion and till some extent the concept of backtracking too but i am having difficulty understand the chronological order of how things are working when for loop is being used in following code. </p>

```<code>public static void diceRolls(int dice) {
    List<Integer> chosen = new ArrayList<Integer>();
    diceRolls(dice, chosen);
}

// private recursive helper to implement diceRolls logic
private static void diceRolls(int dice,List<Integer> chosen) {
     if (dice == 0) {
          System.out.println(chosen); // base case
       } else {
          for (int i = 1; i <= 6; i++) {
               chosen.add(i); // choose
               diceRolls(dice - 1, chosen); // explore
               chosen.remove(chosen.size() - 1); // un-choose
      }
  }
}
</code>```

<p>Now i am having problem understand that for example we pass 3 in diceRolls function, it calls the helper method, inside the for loop we add all the value of i (ie 1) after that it calls the method again so does the for loop complete itself before recursing or the method diceRolls(2,chosen) is passed now ? Because if 2 is passed then also the loop would only run once before recursing itself.   </p>

答: OndreJM's answer is on point. Just to add a little diagramatic magic, consider a simple recursive factorial program and follow the flowchart.

ContentLicense: CC BY-SA 3.0

Title: How does recursive backtracking work ?


问:
Is there a canonical book on design patterns?
I am interested in learning design patterns and would like to know what are considered top tier books in learning this subject.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on design patterns? What about that book makes it special?

答:
I think that the Refactoring to Patterns can be useful simply because it describes how certain desing / code can be refactored towards patterns in the GoF book. This may help to overcome the initial learning curve. Oh and it also contemplates on 'Pattern-happiness' :)

You may also find the first three volumes of Pattern-Oriented Software Architecture to be a good read.

ContentLicense: CC BY-SA 2.5


问:
How different is garbage collection in pure languages?
In a pure language like Haskell, all data is immutable and no existing data structures can be changed in any way. Additionally, many algorithms on immutable data and functional programming patterns generate large amounts of garbage by nature (chains of map creating intermediate lists for example).

What strategies and techniques do garbage collectors employ in the face of purity that they wouldn't otherwise? What works very well in an impure language's GC that doesn't in a pure context? What other new problems do pure languages create for GCs?

答:
The current implementation of ghc uses a strategy that only works because the language is pure functional and data is immutable: because no variable can ever be altered to refer to anything newer, objects only hold references to older objects, so it runs a generational garbage collector; since an object referred to by a higher generation cannot be deleted until that generation is GCd, it promotes objects to higher generations eagerly; and since nothing is going to alter references while the GC is sweeping them, it can run in parallel.

Here’s a paper with more detail.


问:
Spring StoredProcedure Inject declared parameters or not?
At work one of my colleague asked to me to change the way a Spring StoredProcedure subclass class was initialised from injecting the parameters with Dependency Injection mechanism (Constructor Injection) to a "more straight forward and simple way".

The actual code with DI initialization looks like :

```<code><constructor-arg><ref bean="datasource"/></constructor-arg>
<constructor-arg value="STOREDPR"></constructor-arg>
<constructor-arg>
<list>
                <bean parent="SQL.TIMESTAMP.IN">
                    <constructor-arg type="java.lang.String" value="parameter1" />
                </bean>
                <bean parent="SQL.TIMESTAMP.INOUT">
                    <constructor-arg type="java.lang.String" value="parameter2" />
                </bean>
                <bean parent="SQL.NUMERIC.IN">
                    <constructor-arg type="java.lang.String" value="parameter3" />
                </bean>
</list>
</constructor-arg>
</code>```

SubClass of StoredProcedure injected constructor :

```<code>public AStoreProcedure(DataSource datasource, String procedureName, List<SqlParameter> params) {
    super(datasource, procedureName);

    for(SqlParameter p : params)
        declareParameter(p);

    compile();
}
</code>```

In my opinion construction of a StoredProcedure with DI is not a bad idea since you can change the StoreProcedure signature(declared parameters) without having to change the code of your application, but just changing the XML ...

Do you think removing DI mechanism in this case make sense ?
What could be a good alternative ?

答:
You can do dependency injection with Java configuration. I is more and more being adapted and preferred.

You can do something like this to register your bean:

```<code>  @Bean
  public StoredProcedure storedProcedure(DataSource dataSource) {
    StoredProcedure storedProcedure = new GenericStoredProcedure();
    storedProcedure.setDataSource(dataSource);
    SqlParameter param1 = new SqlParameter("parameter1", Types.VARCHAR);
    storedProcedure.declareParameter(param1);
    //..
    storedProcedure.compile();
    return storedProcedure;
  }
</code>```

Body:
You can do dependency injection with Java configuration. I is more and more being adapted and preferred.

You can do something like this to register your bean:

  @Bean
  public StoredProcedure storedProcedure(DataSource dataSource) {
    StoredProcedure storedProcedure = new GenericStoredProcedure();
    storedProcedure.setDataSource(dataSource);
    SqlParameter param1 = new SqlParameter("parameter1", Types.VARCHAR);
    storedProcedure.declareParameter(param1);
    //..
    storedProcedure.compile();
    return storedProcedure;
  }


问:
Git repo with lots of medium-sized images?
I've just used git-tfs to checkout a TFS repo into a Git repo.  The .git directory comes to 2.33GiB, and the primary reason for this is a couple of large directories coming to about 650MiB each.  Each directory is chock full of (roughly 1500) JPEG image files that range from 50KiB to 5MiB in size.

This obviously makes the Git repo uncomfortably large, and yet the images do kind of logically fit into the solution as they are converted to smaller sized images and served out to the client.  A few of them would be OK, but the sheer number of them takes the repo to being too large.  Neither Github nor Bitbucket will even allow you to push a Git repository larger than 2GB (Github don't explicitly state this but I tried to push it and it failed).  What would be the best way to handle this?  This question on this same site has top answers suggesting that it's basically OK to check images into source control.

答: If these images are not going to change often then I think you can store them in an artifact repository like Nexus. Using it you have some version control because you can have different versions of the same artifact, it is well integrated with build tools (like Maven) and it handles binary files better than git. On the other hand you lose something like a 'git log' for your images and a single direct relation (version) between your source code (on Git) and these images (on Nexus).</p>


答: I was always a big fan of blob fields.  So I would store them in a database. You also have the advantage of  storing image metadata (if you have such a need) with the image . I have tried this approach with both Mssql Server and Oracle and both have lived up to the task. With mysql I couldnt say.</p>

Title: Git repo with lots of medium-sized images?

Body:
I've just used git-tfs to checkout a TFS repo into a Git repo.  The .git directory comes to 2.33GiB, and the primary reason for this is a couple of large directories coming to about 650MiB each.  Each directory is chock full of (roughly 1500) JPEG image files that range from 50KiB to 5MiB in size.

This obviously makes the Git repo uncomfortably large, and yet the images do kind of logically fit into the solution as they are converted to smaller sized images and served out to the client.  A few of them would be OK, but the sheer number of them takes the repo to being too large.  Neither Github nor Bitbucket will even allow you to push a Git repository larger than 2GB (Github don't explicitly state this but I tried to push it and it failed).  What would be the best way to handle this?  This question on this same site has top answers suggesting that it's basically OK to check images into source control.


答: There is no way to eliminate possible run-time disagreements between your database and your Java code. The best you can do is ro make your Java code depend only on parths of the schema that are necessary for your business logic, and run integration tests before deploying to production.</p>

Title: Spring StoredProcedure Inject declared parameters or not?

Body:
At work one of my colleague asked to me to change the way a Spring StoredProcedure subclass class was initialised from injecting the parameters with Dependency Injection mechanism (Constructor Injection) to a "more straight forward and simple way".

The actual code with DI initialization looks like :

```<code><constructor-arg><ref bean="datasource"/></constructor-arg>
<constructor-arg value="STOREDPR"></constructor-arg>
<constructor-arg>
<list>
                <bean parent="SQL.TIMESTAMP.IN">
                    <constructor-arg type="java.lang.String" value="parameter1" />
                </bean>
                <bean parent="SQL.TIMESTAMP.INOUT">
                    <constructor-arg type="java.lang.String" value="parameter2" />
                </bean>
                <bean parent="SQL.NUMERIC.IN">
                    <constructor-arg type="java.lang.String" value="parameter3" />
                </bean>
</list>
</constructor-arg>
</code>```

SubClass of StoredProcedure injected constructor :

```<code>public AStoreProcedure(DataSource datasource, String procedureName, List<SqlParameter> params) {
    super(datasource, procedureName);

    for(SqlParameter p : params)
        declareParameter(p);

    compile();
}
</code>```

In my opinion construction of a StoredProcedure with DI is not a bad idea since you can change the StoreProcedure signature(declared parameters) without having to change the code of your application, but just changing the XML ...

Do you think removing DI mechanism in this case make sense ?
What could be a good alternative ?


问:
How to keep a team well-trained?
I'm currently mentoring a small team of 4 junior dev in small software company. They are very smart and often achieve their tasks with a high-quality job but I'm sure they still can do better - actually I have exactly the same feeling for myself :) -. Besides some of them are more "junior" than other.

So I would like to find of a funny way to improve their CS skills (design, coding, testing, algorithmic...) in addition to the experience they acquire in their daily work. For instance, I was thinking of setting up weekly sessions, not longer than 2 hours, where we could get together to work on challenging CS exercises. A bit like a coding dojo.

I'm sure the team would enjoy that but is it really a good idea? Would it be efficient in a professional context? They already spend all their week to code so how should I organize that in order for them to get some benefits?

Any feedback welcome !

答:
As a manager or senior I would strive to keep throwing up challenges in the 'real' work. Try give people things to work on that are a little bit out of their league or at least challenges them. Send in one of their peers to help out and tutor if needed.

After someone finished something, challenge them to try a new/different approach.

Coach them at figuring things out on the spot instead of working around stuff they don't know how to do yet.

Integrate learning into the work itself, side projects for learning tend to get skipped with deadlines on the horizon.

Sometimes directly stating a need for a given expertize can help as a motivator.

Title: How to keep a team well-trained?


问:
JavaScript Combination Inheritance Pattern
In the chapter of Professional JavaScript for Web Developers on OOP, Nicholas Zachas describes a JavaScript inheritance pattern which he refers to as combination inheritance. The basic idea is that methods are inherited via prototype chaining; whereas parent properties are passed on to descendants by calling the parent constructor within the child constructor.

A small example:

```<code>function Parent() {
    this.parentProperty;
}

Parent.prototype.parentMethod = function() {
    console.info(parentProperty);
}

function Child() {
    Parent();
}

Child.prototype = new Parent();
</code>```

He concludes his discussion by saying that "combination inheritance is the most frequently used inheritance pattern in JavaScript."

However, in his following discussion on the prototypal inheritance pattern, he mentions a shortcoming of combination inheritance, namely that the child type invokes the parent constructor twice: once when creating the prototype and then again in the constructor.

My question is why does the combination inheritance pattern suggest extending the prototype by having the child's prototype be an instance of the parent type, why shouldn't it just reference the parent's prototype directly? Using the previous example, why not just do the following:

```<code>Child.prototype = Parent.prototype;
</code>```

答:
By doing:

```<code>Child.prototype = Parent.prototype;
</code>```

You are essentially creating a reference to Parent's prototype, which means any property added to Child's prototype is now added to Parent's prototype as well.

On the other hand by doing:

```<code>Child.prototype = new Parent();
</code>```

Child's prototype inherits all the properties of Parent via prototype chaining, thus adding a property to Child's prototype doesn't affect the Parent's prototype.

```<code>Child.prototype = Object.create(Parent.prototype);
</code>```

The above achieves same thing except it doesn't run the Parent's constructor function when creating Child's prototype.

Body:
By doing:

Child.prototype = Parent.prototype;

You are essentially creating a reference to Parent's prototype, which means any property added to Child's prototype is now added to Parent's prototype as well.

On the other hand by doing:

Child.prototype = new Parent();

Child's prototype inherits all the properties of Parent via prototype chaining, thus adding a property to Child's prototype doesn't affect the Parent's prototype.

Child.prototype = Object.create(Parent.prototype);

The above achieves same thing except it doesn't run the Parent's constructor function when creating Child's prototype.


问:
DRY unrelated, but nearly identical, code
I have some code that is nearly identical, but uses absolutely different types, with no inheritance between them, on the main variable.  Specifically, I am writing an analyzer with Roslyn for C# and VB.NET, with the following types:

Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax
  Microsoft.CodeAnalysis.VisualBasic.Syntax.AttributeSyntax

I am wondering if, because the code is doing the same thing, I should keep it as DRY as possible, splitting off as little as possible into separate (but identical other than the type) methods, or completely separate it because the two methods are not related and future changes could force one version to change, but not the other (although this is unlikely)?

Edit: A year or so later, I hit this same issue, and the Roslyn team helped me solve it: Write a base class that takes generics and has a TAttributeSyntax parameter that does most of the work. Then, write derived classes with the bare minimum of data that needs a specific type.

答:
You don't do DRY because someone wrote it in a book somewhere that it's good to do, you do DRY because it actually has tangible benefits.

Specifically from that question:

If you repeat yourself, you can create maintainability issues. If doStuff1-3 all have similarly structured code and you fix a problem in one, you could easily forget to fix the problem in other places. Also, if you have to add a new case to handle, you can simply pass different parameters into one function rather than copy-pasting all over the place.

However, DRY is often taken to an extreme by clever programmers. Sometimes to not repeat yourself you have to create abstractions so obtuse that your teammates cannot follow them. Sometimes the structure of two things is only vaguely similar but different enough. If doStuff1-4 are different enough such that refactoring them to not repeat yourself causes you to have to write unnatural code or undergo clever coding backflips that will cause your team to glare at you, then it may be ok to repeat yourself. I've bent over backwards to not repeat myself a couple of times in unnatural ways and regretted the end product.

So, basically, don't think "oh man, this code is pretty similar, maybe I should refactor to not repeat myself". Think "does refactoring to make this code base reuse common elements make the code more maintainable or less maintainable?" Then, pick the one that makes it more maintainable.

That being said, given SRP and just trying to have small, flexible classes generally, it might make sense to analyze your code for that reason, break apart bits of behavior that use generic types (you said that they are identical other than type) into small classes. Then you'll find out that some of these classes actually are totally identical (not just mostly identical), and then you can build a toolkit in case you want to add Microsoft.CodeAnalysis.CPlusPlus.Syntax.AttributeSyntax.


问:
Where should the database and mail parameters be stored in a Symfony2 app?
In the default folder structure for a Symfony2 project the database and mail server credentials are stored in parameters.yml file inside ProjectRoot/app/config/parameters.yml with these default values:

```<code>parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: null
    database_name: symfony
    database_user: root
    database_password: null
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt
</code>```

During development we change these parameters to the development database and mail servers. This file is checked into the source code repository.

The problem is when we want to deploy to the production server. We are thinking about automating the deployment process by checking out the project from git and deploy it to the production server.

The thing is that our project manager has to manually update these parameters after each update. The production database and mail servers parameters are confidential and only our project manager knows them.

I need a way to automate this step and suggestion on where to store the production parameters until they are applied?

答:
For production files you should not be using a file. A much better way that does not interfere with development practices (using the files) is to use ENV variables for your production environment.

Look at the cookbook for reference on this practice:

http://symfony.com/doc/current/cookbook/configuration/external_parameters.html


问:
Best approach for aliases namespace from config
I'm working on a library that contains a large number of components that have namespaces that are nested. Also, when a new module inside the library get's added, we then have to add the namespace and sometimes this namespaces can change and then it becomes hellish to maintain.

I have been thinking of a solution or approach to solving this problem and come up with this idea:

The optimal approach would be to have a .h file containing the all of the namespaces:

```<code>namespace Config {

     namespace PCA = LibraryName::Statistical::Components::PCA;
}
</code>```

And then I can include this config file into the main entry to the application..

But, how I get to this point is what I am having trouble getting to. So here is my thought process:

If I create a "pre-compiled" Config.h that contains something like (Syntax is not right, but I would parse this)

```<code>namespace Config {

     "aliases" = [

         "PCA" =>  "LibraryName::Statistical::Components::PCA"
      ];
}
</code>```

Then, some way inside the Makefile parse this syntax, and generate a .h file, with the aliases inside it and then this would work.. But I don't know if this is possible with a Makefile?

The second approach, would be to create a shell command, on the lines of: build_config which then parses this config file and then generate the .h to be used in the entry to the program?

Alternatively, I can use JSON and then parse the JSON using any of the above..

Can anyone give me any guidance to which approach would be better for this, also, is this just causing unnecessary problems?

ALSO: A series of clients / Users have also asked for the ability to change the namespace aliases..

答:
This is a classic XY problem. You have problem X, which is causing problem Y, so you're asking for the solution to problem Y. But the best way of solving problem Y is to solve problem X.

You're asking about generating namespace alias configuration files (Y). But your real problem (X) is that your namespacing is way too complex! C++'s namespaces are not intended to be deeply nested or particularly long. They're intended to be short and not deeply nested. Generally a single namespace is all that is required for a small to medium-sized library, and even large libraries if well-designed can sit in a single namespace.

Nearly all of the C++ standard library, not a small library at all, is in std. There's also std::chrono and a couple of other specialised namespaces, but we don't use std::containers::vector or std::algorithms::sorting::stable_sort, we use std::vector and std::stable_sort.

Simplify the namespacing and you won't need to generate a namespace alias configuration file or anything silly like that.


问:
Algorithm for determining transactions among weekly data series?
I'm trying to develop a small reporting tool (with sqlite backend). I can best describe this tool as a "transaction" ledger. What I'm trying to do is keep track of "transactions" from weekly data extract:

"new" (or add) - resource is new to my app since my app may not have tracked this resource before as it hasn't been seen via extracts.

"update" (or hit) - there is a recent use of that resource, update retention period by another week.

"delete" (or drop) - this item saw no use since last report (optional, but would be nice to have for graphing week-to-week changes in demand for resources).

All I've got is a weekly data extract (pipe-delimited flat file) coming from a legacy archiving/record-management system that I have no control over.

Each line can be distilled to basically this:

resource_id | resource info | customer_id | customer_info

Sample data:

```<code>10| Title X       | 1 | Bob
11| Another title | 1 | Bob
10| Title X       | 2 | Alice
</code>```

The goal is make it easy to report on resources that haven't seen use for X-months (based on last hit). There is a retention period where resources are kept around for ease of access if they're popular. A resource that hasn't seen use for 18 months is marked for long-term archival elsewhere.

This must be a common problem. Wondering if there a general-purpose algorithm to determine what's new/same/removed between data sets (db vs. latest extract)?

答:
As I understand from your question you actually have resource_id (+info) and "list" of customer(id + info).

So you can easily keep List of customer per resource and check last node in each list on the resource (in order to know last operation time; you just need to add date field to your customer in the code)

I'm not familiar with SQL, therefore I give my example with HashMap and List but I'm sure it's same idea: HashMap <Resource, List<Customer>>, when Resource should contain resourceID as key and Customer should contain customer ID, info and operation date.

With this idea you can know easily last operation time and can modify any resource (add\remove resource\customer).


问:
Web development advice for a distributed development team
I am a web developer. Worked in many projects. Now I have changed my work place. It is big organisation. I and my group are thinking about new project. There is no difficulty to write project but our organisation is big and it's has little offices in many places (within the country). There is no any problem about internet in center. But there is problem with internet in remote areas sometimes.

My question is: is there any solution to solve problem as it? If anybody has create project such this please tell little about what technologies you have used.

Thanks

答:
There are numerous steps in the web site design and development process. From gathering initial information, to the creation of your web site, and finally to maintenance to keep your web site up to date and current.
The exact process will vary slightly from designer to designer, but the basics are the same.

Information

Gathering

Planning

Design

Development

Testing and Delivery

Maintenance


问:
CharSequence to represent a named object
I always followed the opinion to not abuse interfaces in case of decomposition.
Usually I only implement them if I am absolutely sure to have a "is-a"-relation and avoid implementing them if there is a "has-a"-relation to another kind of object.

Now, this ethic leads me to a problem:
I'm writing a small library including a type containing a "name" property.
The objects representing this type are almost exclusively created through a XML-file where they are defined.
The idea behind giving those objects a name is to easily access them in the code.

The definition looks like this:

```<code><root>
    <object name="foo">
    ....
    </object>
</root>
</code>```

In the code it should be possible to apply any representor of this type by name or by the object itself. So the type includes a name:

```<code>public interface NamedObject {

    String getName();

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

So now the following two samples should create the same result:

Sample 1:

```<code>NamedObject obj = Utils.getFromXML("obj_name");
Foo.doStuff(obj);
</code>```

Sample 2:

```<code>Foo.doStuff("obj_name");
</code>```

The reason why this should work is that there may be a context where the programmer is already working with such a named object and so he should be able to use it directly like in Sample 1.
But there may be a context where he wants to call a method depending on such an object and the programmer might want to use a named object he defined in the XML. Then he could just lookup the name and use it via its name.

The actual problem is, that this is leading me to a mess in my structural design as there are a lot of objects requiring those kind of objects in their methods and in most cases there is a default behavoir defined as well.

So if there is a default behavior I need 3 implementations of the method.

```<code>public interface Bar {

    void doStuff()

    void doStuff(String namedObjectName);

    void doStuff(NamedObject object);
}
</code>```

So 6 functionalities for example would lead to 18 methods.

I think there might be no other way to represent the default behavoir than providing a method without parameter. I could run the default behavoir by accepting null pointers and run the default behavoir if a null pointer is given but in my eyes, a param-less method is the prettier solution.

So to get rid of one of the other two signatures the NamedObject-type could inherit from java.lang.CharSequence.
The implementations of the methods of java.lang.CharSequence could be done by using the name property.
Since Java 8 I could already default implement them in the interface using the getName() method.

With this move I could replace the method accepting the java.lang.String parameter representing the name and the method accepting the NamedObject with a single method accepting a java.lang.CharSequence representing either the name or the object itself.

The NamedObject-type itself CLEARLY DOES NOT represent a "is-a" relation to its name. It represents a "has-a" relation.

And that's the question. What's the best way to design a library including such a structure? Is my new intention ok?

答:
Inheriting from java.lang.CharSequence will probably cause you much more maintenance headaches in the future, not just because of the has-a/is-a design glitch.

I think the real problem is that you are trying to support calls like this directly:

```<code>  Foo.doStuff("obj_name");
</code>```

That way, your Foo class needs to be coupled to Utils.getFromXML, which makes it probably more complex than it needs to be. Lets ignore the "default behaviour" part of your question for a moment. So I recommend to design your interface just like this:

```<code>public interface Bar {
    void doStuff(NamedObject object);
}
</code>```

and if you need this, provide a helper or utility class XmlUtil containing a function like this

```<code>public void DoStuff(Bar bar, String objname)
{
    NamedObject obj = Utils.getFromXML(objname);
    bar.DoStuff(obj);
}
</code>```

So you can call it like

```<code>XmlUtil.DoStuff(Foo, "obj-name");
</code>```

which is only a little bit longer than your original call, but makes the Xml context explicit.

That way, you do not have to provide the same "string -> object" mapping in each Bar implementation over and over again, you can reuse the function above for any Bar implementation. Moreover, only your utility class now needs to be coupled to the Xml directly, not your `Bar implementations.

Body:
Inheriting from java.lang.CharSequence will probably cause you much more maintenance headaches in the future, not just because of the has-a/is-a design glitch.

I think the real problem is that you are trying to support calls like this directly:

  Foo.doStuff("obj_name");

That way, your Foo class needs to be coupled to Utils.getFromXML, which makes it probably more complex than it needs to be. Lets ignore the "default behaviour" part of your question for a moment. So I recommend to design your interface just like this:

public interface Bar {
    void doStuff(NamedObject object);
}

and if you need this, provide a helper or utility class XmlUtil containing a function like this

public void DoStuff(Bar bar, String objname)
{
    NamedObject obj = Utils.getFromXML(objname);
    bar.DoStuff(obj);
}

So you can call it like

XmlUtil.DoStuff(Foo, "obj-name");

which is only a little bit longer than your original call, but makes the Xml context explicit.

That way, you do not have to provide the same "string -> object" mapping in each Bar implementation over and over again, you can reuse the function above for any Bar implementation. Moreover, only your utility class now needs to be coupled to the Xml directly, not your `Bar implementations.


问:
Does push via web sockets increases server load if I have too many write requests?
I have too many write requests to database. Currently my app implementation is such that it makes pull call to server every 5 seconds to update the changed data. </p>

<p>If I implement push through web sockets, does it increase the server load(mainly number of queries getting fired on mysql)?  Because now on change of data (which is every second) it will send push to every client, thus every second it will now run sql query for every client and increases load on my db server ?
I am using mysql, php in backend. </p>

答:
The push event can simply be a notification that stuff have changed on the server.  It does not have to contain the actual data.  The clients can pull that data only if and when they need it.  This way, you will not have any additional overhead on the server.  On the contrary, you get rid of the polling requests every 5 seconds.

The only disadvantage of this approach is higher latency compared to the server pushing all data scenario, due to the extra round-trip, but your latency is currently at an average of roughly 2.5 seconds, (about half of the 5 second polling interval,) so the extra round-trip that I am suggesting actually represents a tremendous improvement over what you currently have.

Also, the server does not need to send a push notification to a client which has already received a push notification but has not asked for any data yet.  This means that you can also drastically reduce your push notifications.

So, the chatter between the client and the server goes as follows:

```<code>Server to client: "Stuff has changed".
Client to server: "Gimme the changed stuff since XX:XX:XX GMT".
Server to client: "Here is your changed stuff".
</code>```

Body:
The push event can simply be a notification that stuff have changed on the server.  It does not have to contain the actual data.  The clients can pull that data only if and when they need it.  This way, you will not have any additional overhead on the server.  On the contrary, you get rid of the polling requests every 5 seconds.

The only disadvantage of this approach is higher latency compared to the server pushing all data scenario, due to the extra round-trip, but your latency is currently at an average of roughly 2.5 seconds, (about half of the 5 second polling interval,) so the extra round-trip that I am suggesting actually represents a tremendous improvement over what you currently have.

Also, the server does not need to send a push notification to a client which has already received a push notification but has not asked for any data yet.  This means that you can also drastically reduce your push notifications.

So, the chatter between the client and the server goes as follows:

Server to client: "Stuff has changed".
Client to server: "Gimme the changed stuff since XX:XX:XX GMT".
Server to client: "Here is your changed stuff".


问:
is this a valid javascript design pattern when many instances are required?
I have some code that I'm refactoring, right now its just a list of functions, primarily jQuery.

The code is a form builder. The user adds sections, questions etc using jqueryUI drag/drop/sort. They can get quite long in the range of > 1k questions. I've been debating between patterns,frameworks, etc. and have settled on what I believe will be the best improvement without ripping everything out and starting completely over with something like angular or react.

I was also considering the module pattern but I'm concerned about having so many duplicates of the methods in memory (>1k) and thought this might serve me better. Is there anything I'm overlooking or gotchas that might cause an issue? I like that its all wrapped inside an IIFE and feels encapsulated.

Pattern example:

```<code>var Question = (function() {

    function Question(name, type) {
        // enforces new
        if (!(this instanceof Question)) {
            return new Question(name,type);
        }

        // constructor body
        this.name = name || 'default' ;
        this.type = type || 'text';
    }

    Question.prototype.someMethod = function(arg) {
        // method body
    }

    return Question;
}());
</code>```

it would be used like so:

```<code>Question question1 = new Question('name','picklist');
</code>```

答:
The pattern you've cited in your example is just fine, although in your case, not really required. The idea of the module pattern is to hide away the things you don't explicitly return. So in your case, your IIFE isn't really doing anything (if you had private helpers inside your modules, however, you would).

If you have common methods which are shared among components (for example, all form elements may have a getValue() method, you can use JavaScript's prototypal inheritance to create a parent object, and have the various form elements inherit from it:

```<code>function FormObject() {}
FormObject.prototype.getValue = function() { return 42; };

function Question() {
    // ...
}
Question.prototype = Object.create(FormObject);
Question.prototype.constructor = Question;
</code>```

This ugliness can be resolved with ES6's class feature, which is syntactic sugar to all of that:

```<code>class FormObject {
    // FormObject generic implementation here
}
class Question extends FormObject {
    constructor() {
        // ...
    }
    someMethod() {
        // ...
    }
}
var question1 = new Question(...);
</code>```

Also, if you're into modules, have a look at Browserify and webpack. For ES6 today, have a look at Babel.

formObject.js

```<code>class FormObject {
    // FormObject generic implementation here
}
module.exports = FormObject;
</code>```

question.js

```<code>var FormObject = require('./formObject');
class Question extends FormObject {
    constructor() {
        // ...
    }
    someMethod() {
        // ...
    }
}
module.exports = Question;
</code>```

main.js

```<code>require('./question.js');
var question1 = new Question(...);
</code>```

Body:
The pattern you've cited in your example is just fine, although in your case, not really required. The idea of the module pattern is to hide away the things you don't explicitly return. So in your case, your IIFE isn't really doing anything (if you had private helpers inside your modules, however, you would).

If you have common methods which are shared among components (for example, all form elements may have a getValue() method, you can use JavaScript's prototypal inheritance to create a parent object, and have the various form elements inherit from it:

function FormObject() {}
FormObject.prototype.getValue = function() { return 42; };

function Question() {
    // ...
}
Question.prototype = Object.create(FormObject);
Question.prototype.constructor = Question;

This ugliness can be resolved with ES6's class feature, which is syntactic sugar to all of that:

class FormObject {
    // FormObject generic implementation here
}
class Question extends FormObject {
    constructor() {
        // ...
    }
    someMethod() {
        // ...
    }
}
var question1 = new Question(...);

Also, if you're into modules, have a look at Browserify and webpack. For ES6 today, have a look at Babel.

formObject.js

class FormObject {
    // FormObject generic implementation here
}
module.exports = FormObject;

question.js

var FormObject = require('./formObject');
class Question extends FormObject {
    constructor() {
        // ...
    }
    someMethod() {
        // ...
    }
}
module.exports = Question;

main.js

require('./question.js');
var question1 = new Question(...);


问:
Javascript callback design: is it OK to have side effects?
Consider this javascript function:

```<code>function(){
    var someArr = [...];
    var someObj = {...};
    someArr.forEach(function(item){
        if (matchItem(item)){
            someObj.callMethod(item.someProp);
        }
    });
}
</code>```

Assuming that given code works correctly, let's take a look at it's design. As you can notice, someArr.forEach is passed a callback function. Meanwhile, object someObj belongs to the scope of that callback. So from inside the callback function we can manipulate someObj.

I.e., in this case the callback produces side effects.

We could also bind someObj to this object of the callback:

```<code>function(){
    var someArr = [...];
    var someObj = {...};
    someArr.forEach(
        function(item){
            if (matchItem(item)){
                this.callMethod(item.someProp);
            }
        },
        someObj
    );
}
</code>```

Again, we are producing some side effects here, though in more explicit manner. In general, this approach can not be considered functional, because it violates the no-side-effects principle.

How should we design code in such situations? Which way is more robust? What are the best practices?

Thank you!

答:
The Array.prototype.forEach is meant for side effects, it doesn't return anything. Whether you like it or not depends on your application, there's no clear best practice.

Object oriented programming is stateful by design, it's meant for side effects and for objects changing other objects, that's the entire point.

Functional programming is immutable by design*, the idea is that you have little to no side effects in your application, except on the very edge of your application (You have to exert output somehow, that's a side effect). You generally want every function to accept input, process it somehow, and then return an output, without modifying any of the inputted objects.

* That's not entirely accurate. Functional encourages immutability, and there are functional languages which enforce the no-side-effects rule, but you can produce side effects in functional style programming.

Personally, I like the functional style more, I keep my objects immutable or as immutable as possible. I can guarantee that if I have

```<code>var obj = {hello: 'world'};
</code>```

At the end of the scope, obj would still be {hello: 'world'}, regardless of what functions it was passed into. None of the functions modified it along the way.

TL;DR - There's no clear best practice here. It's OK to have side effects, as long as you're aware of the risks of things changing under your feet.

Body:
The Array.prototype.forEach is meant for side effects, it doesn't return anything. Whether you like it or not depends on your application, there's no clear best practice.

Object oriented programming is stateful by design, it's meant for side effects and for objects changing other objects, that's the entire point.

Functional programming is immutable by design*, the idea is that you have little to no side effects in your application, except on the very edge of your application (You have to exert output somehow, that's a side effect). You generally want every function to accept input, process it somehow, and then return an output, without modifying any of the inputted objects.

* That's not entirely accurate. Functional encourages immutability, and there are functional languages which enforce the no-side-effects rule, but you can produce side effects in functional style programming.

Personally, I like the functional style more, I keep my objects immutable or as immutable as possible. I can guarantee that if I have

var obj = {hello: 'world'};

At the end of the scope, obj would still be {hello: 'world'}, regardless of what functions it was passed into. None of the functions modified it along the way.

TL;DR - There's no clear best practice here. It's OK to have side effects, as long as you're aware of the risks of things changing under your feet.


问:
Preserving data in js with multipage application
One benefit of single page applications like Angular.js, is that you can store data in a global variable and access in multiple routes.

With multiple page applications, the data is lost during navigation. Ideally, such data should remain available on the user side while the user session is active. Using SessionStore does not solve this issue. There is the possibility of using LocalStore, but it is not limited to the session. One could fiddle something by extracting the session id from cookies.

Is there a better solution than using LocalStore?

答:
That's not an advantage. Global State is Evil.

Let's review over the things you've said:

Using SessionStore does not solve this issue - What? Why? It sounds exactly like you want. The browser knows what a "session" is a lot better than the server. It sounds to me that it's exactly what you want.

There is the possibility of using LocalStore, but it is not limited to the session. - That is true. localStorage sticks to the end of time, until you (or the user) delete it.

One could fiddle something by extracting the session id from cookies. - No, that's not true. localStorage and sessionStorage can only be accessed by scripts run on the same domain (same as cookies), except localStorage/sessionStorage are never sent to the server (unless explicitly done so with an AJAX request or similar techniques). If anything, one would manipulate cookies to steal the session ID.


问:
Purpose of `return self` from a class method?
I came across something like this in an open-source project. Methods that modify instance attributes return a reference to the instance. What is the purpose of this construct?</p>

```<code>class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    return self
</code>```

答:
It's to allow chaining.

For example:

```<code>var Car = function () {
    return {
        gas : 0,
        miles : 0,
        drive : function (d) {
            this.miles += d;
            this.gas -= d;
            return this;
        },
        fill : function (g) {
            this.gas += g;
            return this;
        },
    };
}
</code>```

Now you can say:

```<code>var c = Car();
c.fill(100).drive(50);
c.miles => 50;
c.gas => 50;
</code>```

Body:
It's to allow chaining.

For example:

var Car = function () {
    return {
        gas : 0,
        miles : 0,
        drive : function (d) {
            this.miles += d;
            this.gas -= d;
            return this;
        },
        fill : function (g) {
            this.gas += g;
            return this;
        },
    };
}

Now you can say:

var c = Car();
c.fill(100).drive(50);
c.miles => 50;
c.gas => 50;


答:
If you are using a SqLite database, if you add the date of the batch also as a column of the table,

```<code>10| Title X       | 1 | Bob    | 2015-03-01
11| Another title | 1 | Bob    | 2015-03-01
...............................
10| Title X       | 1 | Alice  | 2015-03-05
</code>```

it would pretty easy to use a SQL to get the resources not used in last X number of days

```<code>Select distinct r.ResourceID from Resources r
where not exists (SELECT julianday('now') - julianday(r.DateUpdated)) < X
</code>```

I have not tested the SQL but it should give you an idea

Title: Algorithm for determining transactions among weekly data series?

Body:
I'm trying to develop a small reporting tool (with sqlite backend). I can best describe this tool as a "transaction" ledger. What I'm trying to do is keep track of "transactions" from weekly data extract:

"new" (or add) - resource is new to my app since my app may not have tracked this resource before as it hasn't been seen via extracts.

"update" (or hit) - there is a recent use of that resource, update retention period by another week.

"delete" (or drop) - this item saw no use since last report (optional, but would be nice to have for graphing week-to-week changes in demand for resources).

All I've got is a weekly data extract (pipe-delimited flat file) coming from a legacy archiving/record-management system that I have no control over.

Each line can be distilled to basically this:

resource_id | resource info | customer_id | customer_info

Sample data:

```<code>10| Title X       | 1 | Bob
11| Another title | 1 | Bob
10| Title X       | 2 | Alice
</code>```

The goal is make it easy to report on resources that haven't seen use for X-months (based on last hit). There is a retention period where resources are kept around for ease of access if they're popular. A resource that hasn't seen use for 18 months is marked for long-term archival elsewhere.

This must be a common problem. Wondering if there a general-purpose algorithm to determine what's new/same/removed between data sets (db vs. latest extract)?

Body:
If you are using a SqLite database, if you add the date of the batch also as a column of the table,

10| Title X       | 1 | Bob    | 2015-03-01
11| Another title | 1 | Bob    | 2015-03-01
...............................
10| Title X       | 1 | Alice  | 2015-03-05

it would pretty easy to use a SQL to get the resources not used in last X number of days

Select distinct r.ResourceID from Resources r
where not exists (SELECT julianday('now') - julianday(r.DateUpdated)) < X

I have not tested the SQL but it should give you an idea


问:
Storing persistent data that only has a single instance but can change
I'm creating a website CMS in Rails (for fun and learning) and I'm trying to figure out how I'm going to store the data for an "about" page. Due to the nature of this page, the data will only have one instance, it may change and will be persistent so I want to store it in my database but I'm not sure if this is the best approach.

While a database is obviously quite capable but I feel like it's not the best place for it, as this data is not an object that will ever have multiple instances such as something like a user account.

Is there a normal way of doing this, is storing it in the database the normal thing to do and instead just pull forward a single row form the database?

答:
There are number of ways doing it,

Sometimes even if you see it as a single record, actually it could be multiple records. For example if you want to keep the history of the entries about records could be a list of records with one marked as active

If you have some text in about page and you want to store it in the database, it's possible that you have more text in other pages you need to store in the database (probably page_name,key,value)

you could store it in a key value table, and it won't get more simpler.


问:
Better application design - where to place interfaces
Where to place interfaces in a typical multi-layered app with DataAccess, BusinessLogic and an Endpoint modules? I propose 2 options

In both cases there's only dependency from abstractions, but in first one we place interfaces in the same module with implementation, in second - we move all interfaces in the separate module.

I have these pros and cons:

First approach

more stupid-simple (why shall we need this extra module? it's too complicated etc)

Second approach

more TDD-friendly as it allows us completely to separate from the
module that implements contract when we mock it.

more DI friendly - we can succeed in complete isolation of modules.

Yet the second option leads to greater overhead and requires more effort while developing.

So, my question is - what approach is generally better (or are there any other, more appropriate options)?

答:
Common practice I have seen in many projects is to store interfaces and associated data structures in a separate project, where all the other projects can reference it.

The reason behind it is, that when you actually implement interfaces you can use any interface without worrying references, because if you can refer the interface you can always use it's implementation with DI, in the actual executable.


答:
If it's data that the application works with and not resources that the application needs to be usable, then I would consider totally removing them from the repository entirely.

I'm not sure what your application is, but consider a music player. You may have images to represent various UI controls - buttons, icons, your application logo, and so on. However, you may also be displaying album artwork. You would need to distribute buttons and icons with your application so that other developers have them and they are included when users install the application, but you don't need to include music files or album artwork in your releases - your users will need to provide these. However, you may want to capture some as test cases. You should manage these files and control them, but they don't need to be in the same repository as your source code.


问:
Sending Exceptions as event arguments
Is it a good idea to send Exceptions as EventArgs in C#? (And not actually throw the Exception).

I have a class that performs a long running asynchronous task. If something goes wrong in the middle of the task, it will raise an Error event. Is it a good idea to add an Exception as part of the event arguments, or would it be better to use enums?

This class is just one of many that implement a certain interface. All classes in this interface raise the Error event when something goes wrong. Each class that implements this interface will run into different types of errors.

What are some of the best practices in a case such as this? Sending an Exception as an argument and not actually throwing it feels a bit wrong.

答:
Is it a good idea to send Exceptions as EventArgs in C#?

Enh? It's not a great idea.

Is it a good idea to add an Exception as part of the event arguments, or would it be better to use enums?

If you have a fixed set of ways the long running task could fail, then the enum may make sense. Since you say that there are a number of implementers for this interface, you likely have an open set of ways it can fail, making the exception more palatable.

What are some of the best practices in a case such as this?

In general, I dislike events for this sort of thing. You're not guaranteed that anyone is listening. Since something has already gone wrong, it's kinda likely that one of your event handlers will go off the rails, interrupting the chain and/or throwing an exception in the handler, leading to problems.

I would look to see if you couldn't change that to more of a single error handler delegate, perhaps using abstract base classes to force it to be provided via constructor rather than added post construction (which you can't really guarantee at compile time).

That said, passing around exceptions is a little smelly, but not terrible in cases like this. I mean, you're catching an exception and asking a strategy to deal with it. Converting the exception to something else (with likely loss of information) seems to be unnecessary overhead/confusion.

Title: Sending Exceptions as event arguments


答:
From a purely theoretical standpoint, (irrespective of the particular situation that you have at hand,) an event signifies a state transition of a system.  Now, if an error occurs during the processing of a request, then ideally, the system should have a built-in rollback mechanism, so no state transition should occur, therefore, no event should be issued.  If, nonetheless, a state transition does occur, then an event should of course be issued, but it should only contain information about the state transition.  Error information does not fit into this picture; it is irrelevant.  Observers of events expect to be notified about transitions so as to take appropriate action, they have no use and no interest in knowing anything whatsoever about errors.

Now, all that is completely unrelated to the response of a request.  When a client sends a request, the server sends back a response to that client, and only to that one client.   (Additionally, if the processing of the event results in a state change, then it will issue a state change event to all registered observers, but that's a different issue.) This response to the requesting client should, of course, contain error information in case of failure. The fact that you are using an event mechanism to implement your responses is completely irrelevant, and actually plays the role of a red herring in this discussion.  So, including an actual exception object within a response seems perfectly legit to me.

Title: Sending Exceptions as event arguments

Body:
Is it a good idea to send Exceptions as EventArgs in C#? (And not actually throw the Exception).

I have a class that performs a long running asynchronous task. If something goes wrong in the middle of the task, it will raise an Error event. Is it a good idea to add an Exception as part of the event arguments, or would it be better to use enums?

This class is just one of many that implement a certain interface. All classes in this interface raise the Error event when something goes wrong. Each class that implements this interface will run into different types of errors.

What are some of the best practices in a case such as this? Sending an Exception as an argument and not actually throwing it feels a bit wrong.


问:
multiple accounts with the same roles represented as one row in the database
Say there is an online hotel management application. One feature is the Receptionist will confirm and cancel bookings made by the customer. So all Receptionists do the same things. Is it bad practice to add a single row to the database representing all the Receptionists in the hotel then let them access it to login to the site? For example:

```<code>table Receptionist
    RecID primary key,
    username,
    password
</code>```

Then only one insert:

```<code>insert into Receptionist values('rec','rec');
</code>```

now, rather than each Receptionist having records of their own so they can login, all of them will just use this account to login. What's the benefit for having one row for each in this case? I'm thinking security, are there any others?

答: From your edit I see that the table indeed contains the login credentials. Sharing credentials is not good practice, and as you say security is the main reason. If all receptionists use the same credentials, and a receptionist leaves their position, you won't be able to lock them out of the system without changing credentials for everyone. Even without any receptionist leaving, you have no way to track which receptionists performed which operation -- that is, you have no audit trail. This leaves you open to "repudiation", in which a receptionist who does something they shouldn't have done can easily say they didn't do it -- because you have no audit trail. </p>


问:
How to update ui lively without refreshing page
I am doing a web application using struts2 framework. After user login, I show a dashboard about the current status of the user. To show the Dashboard UI(JSP), I used to get the information from the backend (Mysql). On page loading I trigger a request eg."getDashboardInformation" (via Jquery Ajax) to get user's current dashboard information and show that information in UI.

So the request trigger only when page loads. Now I want to trigger the request whenever the user's dashboard information get updated/inserted in the mysql table (related to dashboard).

Now how could I get the dashboard information lively (eg.cricinfo - scores automatically updated in ui) without the need of refreshing the page.

答:
You can use Web Sockets for doing this, but be aware that Web Sockets are a new technology and in case of browser support you might have some troubles.

Web sockets are some kind of event listeners. They are awaiting events from the server like socket.onopen-event.

So you could do the following to get this done on the client side:

At first there is the function which handles the response data...

```<code>function handleResponseData(data) {
    // data could be JSON string for example
    alert(data);
}
</code>```

Then you create the web socket version of handling data...

```<code>function doSocket() {
    socket = new WebSocket("ws://echo.websocket.org/");
    socket.onmessage = function(event) {
        handleResponseData(event.data);
    }
}
</code>```

And then the alternative version...

```<code>function doAlternative() {
    window.setInterval(function() {
        var xmlhttp;

        if(window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange=function() {
            if(xmlhttp.readyState==4 && xmlhttp.status==200 &&
                // Also check if server responded with data:
                xmlhttp.responseText)
            {
                handleResponseData(xmlhttp.responseText);
            }
        }

        xmlhttp.open("GET","echo.websocket.org",true);
        xmlhttp.send();
    }, 2000);
}
</code>```

The only thing left to do is to check if web sockets are supported and to run the appropriate function...

```<code>function initialize() {
    if(typeof(WebSocket) == "function") {
        doSocket();
    }
    else {
        doAlternative();
    }
}

window.addEventListener("load", initialize, false);
</code>```

With this code on the client side, you are now able to handle periodical updates.
But it is important to notice that as long as you run both versions, you will need two mechanisms on the server side to handle this:

A socket which periodically sends updates to the client and

A servlet which handles the requests sent in the interval function.

Finally, you can get some more information about web sockets here.

Body:
You can use Web Sockets for doing this, but be aware that Web Sockets are a new technology and in case of browser support you might have some troubles.

Web sockets are some kind of event listeners. They are awaiting events from the server like socket.onopen-event.

So you could do the following to get this done on the client side:

At first there is the function which handles the response data...

function handleResponseData(data) {
    // data could be JSON string for example
    alert(data);
}

Then you create the web socket version of handling data...

function doSocket() {
    socket = new WebSocket("ws://echo.websocket.org/");
    socket.onmessage = function(event) {
        handleResponseData(event.data);
    }
}

And then the alternative version...

function doAlternative() {
    window.setInterval(function() {
        var xmlhttp;

        if(window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange=function() {
            if(xmlhttp.readyState==4 && xmlhttp.status==200 &&
                // Also check if server responded with data:
                xmlhttp.responseText)
            {
                handleResponseData(xmlhttp.responseText);
            }
        }

        xmlhttp.open("GET","echo.websocket.org",true);
        xmlhttp.send();
    }, 2000);
}

The only thing left to do is to check if web sockets are supported and to run the appropriate function...

function initialize() {
    if(typeof(WebSocket) == "function") {
        doSocket();
    }
    else {
        doAlternative();
    }
}

window.addEventListener("load", initialize, false);

With this code on the client side, you are now able to handle periodical updates.
But it is important to notice that as long as you run both versions, you will need two mechanisms on the server side to handle this:

A socket which periodically sends updates to the client and

A servlet which handles the requests sent in the interval function.

Finally, you can get some more information about web sockets here.


问:
Thread.State BLOCKED vs WAITING
What is difference between the BLOCKED and the WAITING states of a thread.

As per JAVA code comments

```<code>    /**
     * Thread state for a thread blocked waiting for a monitor lock.
     * A thread in the blocked state is waiting for a monitor lock
     * to enter a synchronized block/method or
     * reenter a synchronized block/method after calling
     * {@link Object#wait() Object.wait}.
     */
    BLOCKED,

    /**
     * Thread state for a waiting thread.
     * A thread is in the waiting state due to calling one of the
     * following methods:
     * <ul>
     *   <li>{@link Object#wait() Object.wait} with no timeout</li>
     *   <li>{@link #join() Thread.join} with no timeout</li>
     *   <li>{@link LockSupport#park() LockSupport.park}</li>
     * </ul>
     *
     * <p>A thread in the waiting state is waiting for another thread to
     * perform a particular action.
     *
     * For example, a thread that has called <tt>Object.wait()</tt>
     * on an object is waiting for another thread to call
     * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
     * that object. A thread that has called <tt>Thread.join()</tt>
     * is waiting for a specified thread to terminate.
     */
    WAITING,
</code>```

Doesn't it mean that both of the states are similar in terms of waiting for lock ?

答:
I think the comments you posted give the answer. They are similar in that a thread is waiting for another thread. But they are not the same.

The BLOCKED state means waiting for an object's monitor. This often happens when a synchronized method or statement is used. The thread is waiting for access to synchronized code, or to do any other action that requires owning the object's monitor. This kind of blocking would often happen when there is no attempt and coordinate between threads, but there are two or more threads calling an object's synchronized methods or statements.

WAITING means waiting for a specific action, e.g. a Notify, or using join() to wait for a thread to terminate. This kind of waiting seems to indicate some attempt at coordination between threads, where one thread notifies another or waits for another to complete.

One potentially confusing factor is that calling Object.wait() requires owning the object's monitor, in order to begin waiting. But Object.wait() then releases the monitor until notified. So a thread might go through BLOCKED state to WAITING state as it obtains the monitor, then executes Object.wait() and begins waiting.
See Doc: Java 7 Object.wait().

Java 7 Docs appear to confirm this interpretation...

A thread state. A thread can be in one of the following states:

NEW A thread that has not yet started is in this state.

RUNNABLE A thread executing in the Java virtual machine is in this
     state.

BLOCKED A thread that is blocked waiting for a monitor lock is in this
     state.

WAITING A thread that is waiting indefinitely for another thread to
     perform a particular action is in this state.

TIMED_WAITING A thread that is waiting for another thread to perform
     an action for up to a specified waiting time is in this state.

TERMINATED A thread that has exited is in this state.

A thread can be in only one state at a given point in time. These
  states are virtual machine states which do not reflect any operating
  system thread states.

Java 7 Docs Thread.State

Title: Thread.State BLOCKED vs WAITING


问:
Can I do commercial web development with the Community edition of Visual Studio?
A friend of mine has a small company that needs a new website,

and I am interested in helping him, since I have worked a bit with Asp.net MVC. However, I am not sure if I'm allowed to sell or give away websites made with the community edition of Visual Studio.

The license says

IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW.

INSTALLATION AND USE RIGHTS. a. Individual license. If you are an
individual working on your own applications to sell or for any other
purpose, you may use the software to develop and test those
applications.

b. Organization licenses. If you are an organization, your users may
use the software as follows:

· Any number of your users may use the software to develop and test
your applications released under Open Source Institute (OSI)-approved
open source software licenses.

· Any number of your users may use the software to develop and test
your applications as part of online or in person classroom training
and education, or for performing academic research.

· If none of the above apply, and you are also not an enterprise
(defined below), then up to 5 of your individual users can use the
software concurrently to develop and test your applications.

· If you are an enterprise, your employees and contractors may not use
the software to develop or test your applications, except for open
source and education purposes as permitted above. An “enterprise” is
any organization and its affiliates who collectively have either (a)
more than 250 PCs or users or (b) more than one million US dollars (or
the equivalent in other currencies) in annual revenues, and
“affiliates” means those entities that control (via majority
ownership), are controlled by, or are under common control with an
organization.

c. Demo use. The uses permitted above include use of the software in
demonstrating your applications.

d. Backup copy. You may make one backup copy of the software, for
reinstalling the software.

If I understand correctly from this answer to a very similar question

I am allowed to sell software I've made, as long as its not customized for a big company which websites tend to be.

Is it true that I need cannot use Visual Studio community to make a website for my friend, even if I do it for free?

Is there a relatively cheap version of Visual Studio that will allow me to do this?

Edit: it might be worth saying that my friend is a car dealer and his company does sell cars for more than 1 million USD a year.

答:
From your question, it sounds like you would be a contractor for your friends business.  It doesn't sound like you'd be considered an affiliate as your consulting company is not under direct control of your friends business.  Since you probably don't have 250 or more computers, and you're consulting business probably doesn't do more than $1M in annual revenue, you wouldn't be considered an enterprise.

You sound exactly like what is described in a. and nothing like b. definition of an enterprise.  And the line above says if you are not any of the above and not an enterprise, you're good.  So my layman interpretation of the text you posted here is that you'd be fine to sell the app to your friends business.  Of course, consult a lawyer to be sure.  They probably could get you an answer fairy cheaply.   It wouldn't take one long to read the license and give you an answer.  I consulted a lawyer for a matter and our conversation took 15 minutes for me to describe and her to give advice, so I only paid $45.  ($180/hr rate).

Also I feel I should clarify something; nothing in the text you've pasted indicates that it matters who your customer is.  It matters if you're considered an affiliate or not, but I'd be surprised if you were considered one.


问:
What is O(m+n) and O(m*n) in Big O notation?
I understand that O(n) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set. An example of this is a for loop:

```<code>for n in 0.100
  puts n
end
</code>```

What does the O(m+n) and O(m*n) mean? I couldn't find any clear examples of this in the internet. Please provide examples! Thanks!

答:
That depends on the context, but typically, m and n are the sizes of two separate parts of the dataset, or two separate properties of the dataset, for example, filling a m×n array.  Usually, when the complexity depends on two independent factors, the second one gets denoted by m.

So we might say that finding the union of two sets is O(m+n), where m and n are the sizes of the inputs, but finding their Cartesian product is O(m·n).

Code sample:

// BOILERPLATE:
#include <array>
#include <iostream>
#include <utility>
#include <vector>

using std::array;
using std::cout;
using std::endl;
using std::ostream;
using std::pair;
using std::vector;

template<class T, class U>
  ostream& operator<< ( ostream& s, const pair<T,U>& x);

template<class T>
  ostream& operator<< ( ostream& s, const vector<T>& x );

template<class T, size_t N>
  ostream& operator<< ( ostream& s, const array<T,N>& x );
// END OF BOILERPLATE.

static const size_t M = 10, N = 5;

int main(void)
{
  static const array<int,M> a = {1,2,3,4,5,6,7,8,9,10}; // Inputs.
  static const array<int,N> b = {0,4,8,12,16};
  array<int,M>::const_iterator i = a.cbegin();  // Iterators.
  array<int,M>::const_iterator j = b.cbegin();

  vector<int> c;    // This vector will hold our results.

  // First, compute the set union of a and b,
  c.reserve(M+N);   // Which has at most M + N elements.

  while ( i < a.cend() || j  *j ) {
      c.emplace(c.end(), *j);
      ++j;
    } else if ( j == b.cend() || *i < *j ) {
      c.emplace(c.end(), *i);
      ++i;
    } else {
/* We can only have got here if: i and j are both valid and neither *i
 * nor *j is greater than the other.  Therefore, they are equal and this
 * element is a duplicate.
 */
      c.emplace(c.end(), *i);
      ++i;
      ++j;
    } // end if
  } // end while
/* The above loop terminates because it increments i, j or both at each step.
 * Provided that a and b are sorted and have no duplicates, it computes the
 * set union because it adds whichever of their next elements are smaller
 * until both are exhausted.  Since it walks each array to the end once, it
 * completes in M + N increment operations.
 */

  cout << "The set union of " << a
       << " and " << b
       << " is " << c << endl;

  c.clear();    // Done with it.

  vector< pair<int,int> > d;

  // Now, compute the Cartesian product, which has M*N elements.
  d.reserve(M*N);

  for ( i = a.cbegin(); i < a.cend(); ++i )
    for ( j = b.cbegin(); j < b.cend(); ++j )
      d.emplace(d.end(), pair<int,int>(*i, *j) );
  // We perform exactly M * N insertions.

  cout << "The Cartesian product is " << d << "."  << endl;

  d.clear();    // Done with it.

  return 0;
}

// MORE BOILERPLATE.  Not needed to understand the algorithms.

template<class T, class U>
  ostream& operator<< ( ostream& s, const pair<T,U>& x) {
    s << "(" << x.first << ", " << x.second << ")";
    return s;
  }

template<class T>
  ostream& show( ostream& s, const T& x ) {
/* Outputs a human-readable representation of an iterable container whose
 * value-type supports stream output to the stream s.
 */
    typename T::const_iterator i = x.cbegin();
    s << "{";

    if ( i < x.cend() ) {
      s << *i;
      ++i;
    }

    for ( ; i < x.cend(); ++i ) {
      s << ", ";
      s << *i;
    }

    s << "}";

    return s;
  }

template<class T>
  inline ostream& operator<< ( ostream& s, const vector<T>& x ) {
/* Outputs a human-readable representation of a vector.
 */
    return show(s, x);
  }

template<class T, size_t N>
  inline ostream& operator<< ( ostream& s, const array<T,N>& x ) {
/* Outputs a human-readable representation of an array.
 */
    return show(s, x);
  }
```

Body:
That depends on the context, but typically, m and n are the sizes of two separate parts of the dataset, or two separate properties of the dataset, for example, filling a m×n array.  Usually, when the complexity depends on two independent factors, the second one gets denoted by m.

So we might say that finding the union of two sets is O(m+n), where m and n are the sizes of the inputs, but finding their Cartesian product is O(m·n).

Code sample:

// BOILERPLATE:
#include <array>
#include <iostream>
#include <utility>
#include <vector>

using std::array;
using std::cout;
using std::endl;
using std::ostream;
using std::pair;
using std::vector;

template<class T, class U>
  ostream& operator<< ( ostream& s, const pair<T,U>& x);

template<class T>
  ostream& operator<< ( ostream& s, const vector<T>& x );

template<class T, size_t N>
  ostream& operator<< ( ostream& s, const array<T,N>& x );
// END OF BOILERPLATE.

static const size_t M = 10, N = 5;

int main(void)
{
  static const array<int,M> a = {1,2,3,4,5,6,7,8,9,10}; // Inputs.
  static const array<int,N> b = {0,4,8,12,16};
  array<int,M>::const_iterator i = a.cbegin();  // Iterators.
  array<int,M>::const_iterator j = b.cbegin();

  vector<int> c;    // This vector will hold our results.

  // First, compute the set union of a and b,
  c.reserve(M+N);   // Which has at most M + N elements.

  while ( i < a.cend() || j < b.cend() ) {
    if ( i == a.cend() || *i > *j ) {
      c.emplace(c.end(), *j);
      ++j;
    } else if ( j == b.cend() || *i < *j ) {
      c.emplace(c.end(), *i);
      ++i;
    } else {
/* We can only have got here if: i and j are both valid and neither *i
 * nor *j is greater than the other.  Therefore, they are equal and this
 * element is a duplicate.
 */
      c.emplace(c.end(), *i);
      ++i;
      ++j;
    } // end if
  } // end while
/* The above loop terminates because it increments i, j or both at each step.
 * Provided that a and b are sorted and have no duplicates, it computes the
 * set union because it adds whichever of their next elements are smaller
 * until both are exhausted.  Since it walks each array to the end once, it
 * completes in M + N increment operations.
 */

  cout << "The set union of " << a
       << " and " << b
       << " is " << c << endl;

  c.clear();    // Done with it.

  vector< pair<int,int> > d;

  // Now, compute the Cartesian product, which has M*N elements.
  d.reserve(M*N);

  for ( i = a.cbegin(); i < a.cend(); ++i )
    for ( j = b.cbegin(); j < b.cend(); ++j )
      d.emplace(d.end(), pair<int,int>(*i, *j) );
  // We perform exactly M * N insertions.

  cout << "The Cartesian product is " << d << "."  << endl;

  d.clear();    // Done with it.

  return 0;
}

// MORE BOILERPLATE.  Not needed to understand the algorithms.

template<class T, class U>
  ostream& operator<< ( ostream& s, const pair<T,U>& x) {
    s << "(" << x.first << ", " << x.second << ")";
    return s;
  }

template<class T>
  ostream& show( ostream& s, const T& x ) {
/* Outputs a human-readable representation of an iterable container whose
 * value-type supports stream output to the stream s.
 */
    typename T::const_iterator i = x.cbegin();
    s << "{";

    if ( i < x.cend() ) {
      s << *i;
      ++i;
    }

    for ( ; i < x.cend(); ++i ) {
      s << ", ";
      s << *i;
    }

    s << "}";

    return s;
  }

template<class T>
  inline ostream& operator<< ( ostream& s, const vector<T>& x ) {
/* Outputs a human-readable representation of a vector.
 */
    return show(s, x);
  }

template<class T, size_t N>
  inline ostream& operator<< ( ostream& s, const array<T,N>& x ) {
/* Outputs a human-readable representation of an array.
 */
    return show(s, x);
  }

ContentLicense: CC BY-SA 4.0


答:
They are linear and subquadratic time complexities respectively.

Suppose I've got two sets of data that I am performing some operation. If one set is the same size as the other, it's 2n. If it's anything more or less it's m+n. It's always O(n), we are just making sure to note that there are two independent factors here. We strip out the 2 because big O doesn't care about constants.

Subquadratic time functions similarly but it is dependent rather than independent. For every m, you do n things or vice versa. Thus we do at most n^2 operations. It's in O(n^2) but it's probably going to be less than that but definitely  more than O(n) so we use O(m*n) to make that clear.

So in summary, we could just call these O(n) and O(n^2) but in some cases, particularly when comparing very similar algorithms, it's important to have some precision of clarity.

Title: What is O(m+n) and O(m*n) in Big O notation?

Body:
I understand that O(n) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set. An example of this is a for loop:

```<code>for n in 0.100
  puts n
end
</code>```

What does the O(m+n) and O(m*n) mean? I couldn't find any clear examples of this in the internet. Please provide examples! Thanks!


问:
C++: Should class own or observe its dependencies?
Say I have a class Foobar that uses (depends on) class Widget. In good ol' days, Widget wolud be declared as a field in Foobar, or maybe as a smart pointer if polymorphic behavior was needed, and it would be initialized in constructor:

```<code>class Foobar {
    Widget widget;
    public:
    Foobar() : widget(blah blah blah) {}
    // or
    std::unique_ptr<Widget> widget;
    public:
    Foobar() : widget(std::make_unique<Widget>(blah blah blah)) {}
    (…)
};
</code>```

And we'd be all set and done. Unfortunately, today, Java kids will laugh at us once they see it, and rightfully, as it couples Foobar and Widget together. The solution is seemingly simple: apply Dependency Injection to take construction of dependencies out of Foobar class. But then, C++ forces us to think about ownership of dependencies. Three solutions come to mind:

Unique pointer

```<code>class Foobar {
    std::unique_ptr<Widget> widget;
    public:
    Foobar(std::unique_ptr<Widget> &&w) : widget(w) {}
    (…)
}
</code>```

Foobar claims sole ownership of Widget that is passed to it. This has following advantages:

Impact on performance is negligible.

It's safe, as Foobar controls lifetime od its Widget, so it makes sure that Widget doesn't suddenly disappear.

It's safe that Widget won't leak and will be properly destructed when no longer needed.

However, this comes at a cost:

It places restrictions on how Widget instances can be used, e.g. no stack-allocated Widgets can be used, no Widget can be shared.

Shared pointer

```<code>class Foobar {
    std::shared_ptr<Widget> widget;
    public:
    Foobar(const std::shared_ptr<Widget> &w) : widget(w) {}
    (…)
}
</code>```

This is probably closest equivalent ot Java and other garbage collected languages. Advantages:

More universal, as it allows sharing dependencies.

Maintains safety (points 2 and 3) of unique_ptr solution.

Disadvantages:

Wastes resources when no sharing is involved.

Still requires heap allocation and disallows stack-allocated objects.

Plain ol' observing pointer

```<code>class Foobar {
    Widget *widget;
    public:
    Foobar(Widget *w) : widget(w) {}
    (…)
}
</code>```

Place raw pointer inside class and shift the burden of ownership to someone else. Pros:

As simple as it can get.

Universal, accepts just any Widget.

Cons:

Not safe anymore.

Introduces another entity that is responsible for ownership of both Foobar and Widget.

Some crazy template metaprogramming

The only advantage I can think of is that I'd be able to read all those books I didn't find time for while my software is builing;)

I lean towards the third solution, as it is most universal, something has to manage Foobars anyway, so managing Widgets is simple change. However, using raw pointers bothers me, on the other hand smart pointer solution feel wrong to me, as they make consumer of dependency restrict how that dependency is created.

Am I missing something? Or is just Dependency Injection in C++ not trivial? Should class own its dependencies or just observe them?

答:
I would use an observing pointer in the form of a reference. It gives a much better syntax when you use it and the has the semantic advantage that it doesn't imply ownership, which a plain pointer can.

The biggest problem with this approach is lifetimes. You have to ensure that the dependency is constructed before, and destructed after your depending class. It isn't a simple problem. Using shared pointers (as dependency storage and in all classes that depend on it, option 2 above) can remove this problem, but also introduces the problem of circular dependencies which is also non-trivial, and in my opinion less obvious and therefore harder to detect before it causes problems. Which is why I prefer to not do it automatically and manually manage the lifetimes and construction order. I've also seen systems that use a light template approach which constructed a list of objects in the order they were created and destroyed them in opposite order, it wasn't foolproof, but it made things a lot simpler.

Update

David Packer's response made me think a little more about the question. The original answer is true for shared dependencies in my experience, which is one of the advantages of dependency injection, you can have multiple instances using the one instance of a dependency. If however your class needs to have it's own instance of a particular dependency then std::unique_ptr is the correct answer.


答:
O(n) does not mean time grows linearly with n.
It means time is bounded by a line that has some Y-intercept, and some slope times n, like this ...

... no matter how big n gets. The same goes for any other big-O.
For example, O(n x m) means there is some bounding curve C1 + C2 x (n x m),
and O(n + m) means the curve is C1 + C2 x (n + m).

(Keep in mind that better big-O does not mean better performance, except as n gets large.)


问:
3D array updating in C#
I'm curious because I have read that once an array is declared it can not be changed. Maybe if I lay out my thoughts.

Say, I have a cube with dimensions 5x5x5 and I have a viewport that can rotate the face of the cube to see object data in a area. Instead of slicing the image in flat planes, is it possible to have an update to array data according to current faced side of cube? Also, can I generate a layer shader to top layer to drop opacity and be able to select or modify interior cubes?

I know I've got to be explaining this badly.

答:
You seem to be confusing a lot of things. First of all an array in C# or any other language is referring to a data structure which stores values of certain type like integers, doubles, string etc. This is the representation of data not a rendering of a three dimensional object.

It is correct that a multidimensional array in C# cannot be resized once declared. You would need to declare a new array and copy the elements.

If you treat that 3D array like a cube, you can indeed update certain "slices". The smallest part an array consists of are the elements which can be accessed through their index. You can imagine them as boxes that store content and each have numbers identifying them. For a 3D array, that would be three numbers one for each dimension.

To update what you called a slice you would iterate through all boxes in two dimensions and keep the third fixed. As the 3D is only an abstraction there actually is no side you are facing when treating it figuratively as a thing.

For actual 3D rendering of cubes, which are not the same thing as an array, you might want to check out OpenGL, XNA Game or 3D rendering with WPF.

I hope that clarifies things a little.

Here is a tutorial on how to use arrays, should be simple enough to follow along for a beginner.

As for 3D rendering with C# I am not a great help, because I have never done it myself. But there are plenty tutorials for that as well. For example this.

Title: 3D array updating in C#


答:
I meant to write this as a comment, but it turned out to be too long.

How I know that Foobar is the only owner? In the old case it's simple. But the problem with DI, as I see it, is as it decouples class from construction of its dependencies, it also decouples it from ownership of those dependencies (as ownership is tied to construction). In garbage collected environments such as Java, that's not a problem. In C++, this is.

Whether you should use std::unique_ptr<Widget> or std::shared_ptr<Widget>, that is up to you to decide and comes from your functionality.

Let's assume you have a Utilities::Factory, which is responsible for the creation of your blocks, such as Foobar. Following the DI principle, you will need the Widget instance, to inject it using Foobar's constructor, meaning inside one of the Utilities::Factory's method, for example createWidget(const std::vector<std::string>& params), you create the Widget and inject it into the Foobar object.

Now you have a Utilities::Factory method, which created the Widget object. Does it mean, the method should me responsible for its deletion? Of course not. It is only there to make you the instance.

Let's imagine, you are developing an application, which will have multiple windows. Each window is represented using the Foobar class, so in fact the Foobar acts like a controller.

The controller will probably make use of some of your Widgets and you have to ask yourself:

If I go on this specific window in my application, I will need these Widgets. Are these widgets shared among other application windows? If so, I shouldn't be probably creating them all over again, because they will always look the same, because they are shared.

std::shared_ptr<Widget> is the way to go.

You also have an application window, where there is a Widget specifically tied to this one window only, meaning it won't be displayed anywhere else. So if you close the window, you don't need the Widget anywhere in your application anymore, or at least its instance.

That's where std::unique_ptr<Widget> comes to claim its throne.

Update:

I don't really agree with @DominicMcDonnell, about the lifetime issue. Calling std::move on std::unique_ptr completely transfers the ownership, so even if you create an object A in a method and pass it to another object B as a dependency, the object B will now be responsible for the resource of object A and will correctly delete it, when object B goes out of scope.

Title: C++: Should class own or observe its dependencies?

Body:
Say I have a class Foobar that uses (depends on) class Widget. In good ol' days, Widget wolud be declared as a field in Foobar, or maybe as a smart pointer if polymorphic behavior was needed, and it would be initialized in constructor:

```<code>class Foobar {
    Widget widget;
    public:
    Foobar() : widget(blah blah blah) {}
    // or
    std::unique_ptr<Widget> widget;
    public:
    Foobar() : widget(std::make_unique<Widget>(blah blah blah)) {}
    (…)
};
</code>```

And we'd be all set and done. Unfortunately, today, Java kids will laugh at us once they see it, and rightfully, as it couples Foobar and Widget together. The solution is seemingly simple: apply Dependency Injection to take construction of dependencies out of Foobar class. But then, C++ forces us to think about ownership of dependencies. Three solutions come to mind:

Unique pointer

```<code>class Foobar {
    std::unique_ptr<Widget> widget;
    public:
    Foobar(std::unique_ptr<Widget> &&w) : widget(w) {}
    (…)
}
</code>```

Foobar claims sole ownership of Widget that is passed to it. This has following advantages:

Impact on performance is negligible.

It's safe, as Foobar controls lifetime od its Widget, so it makes sure that Widget doesn't suddenly disappear.

It's safe that Widget won't leak and will be properly destructed when no longer needed.

However, this comes at a cost:

It places restrictions on how Widget instances can be used, e.g. no stack-allocated Widgets can be used, no Widget can be shared.

Shared pointer

```<code>class Foobar {
    std::shared_ptr<Widget> widget;
    public:
    Foobar(const std::shared_ptr<Widget> &w) : widget(w) {}
    (…)
}
</code>```

This is probably closest equivalent ot Java and other garbage collected languages. Advantages:

More universal, as it allows sharing dependencies.

Maintains safety (points 2 and 3) of unique_ptr solution.

Disadvantages:

Wastes resources when no sharing is involved.

Still requires heap allocation and disallows stack-allocated objects.

Plain ol' observing pointer

```<code>class Foobar {
    Widget *widget;
    public:
    Foobar(Widget *w) : widget(w) {}
    (…)
}
</code>```

Place raw pointer inside class and shift the burden of ownership to someone else. Pros:

As simple as it can get.

Universal, accepts just any Widget.

Cons:

Not safe anymore.

Introduces another entity that is responsible for ownership of both Foobar and Widget.

Some crazy template metaprogramming

The only advantage I can think of is that I'd be able to read all those books I didn't find time for while my software is builing;)

I lean towards the third solution, as it is most universal, something has to manage Foobars anyway, so managing Widgets is simple change. However, using raw pointers bothers me, on the other hand smart pointer solution feel wrong to me, as they make consumer of dependency restrict how that dependency is created.

Am I missing something? Or is just Dependency Injection in C++ not trivial? Should class own its dependencies or just observe them?


答:
Suppose you have an array (general sense, not programming sense) of 3D objects in a Cartesian grid of 5 x 5 x 5.

The eight corner cells of the array are (using zero-based indexing):

[0][0][0]

[0][0][4]

[0][4][0]

[0][4][4]

[4][0][0]

[4][0][4]

[4][4][0]

[4][4][4]

The six faces of the array are (for j, k range from 0 to 4):

[0][j][k]

[4][j][k]

[j][0][k]

[j][4][k]

[j][k][0]

[j][k][4]

Notice that some cells are shared by two or three faces.

In general, you can slice through in 3D space by having a hyperplane separator, which is an inequality.

compare(a * x + b * y + c * z + d, 0)

Fix the parameters (a, b, c, d), which defines how the hyperplane slice through the space. For each object, one can check the object's relative position to the hyperplane by plugging the object's (x, y, z) into the inequality, and check the sign of comparison. If the comparison result is greater-than, it is on one side of the hyperplane. If it is less-than, it is on the other side of the hyperplane.

The Wikipedia article linked above teaches how to choose the parameters of that inequality so that the hyperplane will pass through specific points, which would need to be manipulated by the user.

Title: 3D array updating in C#

Body:
I'm curious because I have read that once an array is declared it can not be changed. Maybe if I lay out my thoughts.

Say, I have a cube with dimensions 5x5x5 and I have a viewport that can rotate the face of the cube to see object data in a area. Instead of slicing the image in flat planes, is it possible to have an update to array data according to current faced side of cube? Also, can I generate a layer shader to top layer to drop opacity and be able to select or modify interior cubes?

I know I've got to be explaining this badly.


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答:
I currently work for a bunch of cheapskates.

When the decision is made between "build or buy", instead of making a rational decision based on economics, the managers chose to "build." This means that instead of paying a few thousand dollars for a component or tool, we spend man-months building our own. Purchasing a wheel from another company costs money which comes out of the budget - which counts against mismanagerial year-end bonuses. Programmers' time is free and therefore does not count against year-end bonuses (with the additional benefit of dinging the programmers for not getting everything done "on time"), therefore a reinvented wheel is a free wheel.

In a rational company, the cost vs benefits of purchasing wheels made by others vs reinventing one's own wheels would be based on short-term and long term costs, as well as opportunity costs lost because one can't be making new widgets while one is reinventing wheels. Every day you spend reinventing the wheel is another day you cannot write something new.

Presentation on build vs buy.

Article on build vs buy.

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

The built-in version will have had a lot more people banging away on it - thus finding and fixing more bugs than your homebrew code can ever have.

Finally, when your local developer leaves, and someone else has to maintain the code he wrote, it is going to get totally refactored out and replaced with what is in the framework. I know this will happen because my current employer has code that has been migrated to newer versions of VB over the years (the oldest product has been on the market for about 20 years) and this is what has happened. The developer with the longest employment in my office has been here 17 years.