问:
Experiences with C++ Async/actor model Library
I am fairly experienced with async and concurrent programming in c# using event, actor, and task based patterns, but now I have a task in c++ with which I have basic familiarity and it needs some asynchronicity and concurrency.  I have free reign on deciding how to do this, and do not have the required c++ experience to reinvent the wheel.  So after consulting the Google, I see several libraries and frameworks to add this in, but little independent discussion on them, so users of Stack Exchange, what experiences have you had with async libraries in c++?  I'm not asking which is best or even which I should use, but more have you used one or more, pros and cons of it as you have experienced, etc, pretty much what is your informal review?

Every library in the world uses the same descriptors, so the official Web sites have been consulted but only help so much, and all seem to offer the same basic features that I require (light cross domain concurrency, efficient thread yields/continuation, message based eventing, thread safe method availability).  So all things being more or less equal, I'm playing the dangerous game of fishing for the developer opinion.  So thoughts?  Thanks much.

While I feel that this question hits at minimum 4 of the subjective guidelines (not mindless fun, asking for experiences over opinions, looking for longer answers which if not purely personal experience should be backed by reference).  I was wrong to ask this question here, when posting this I was thinking the problem with subjective requests is that more often than not they are being treated as objective answers, which was not my aim.  The true problem is that it is impossible to ask for general opinions and have one true answer, this is not the venue to start a discussion about personal impressions on the tools used by the target demographic.  To be clear all of the libraries I find claim to solve the same problems so rather than being problem specific I was looking to compare subjective opinions.  I know there is no objective 'best' one my hope was for something akin to:  lib a provided more options than b, but I prefer b's naming conventions.  This was my mistake.  The answer given and marked as such may be helpful for people, great general points to keep in mind about concurrency.  Thank you all for your participation.

答:
(Disclaimer: I only have experience in parallelizing computational workloads. I do not have experience in async I/O. The opinions herein are merely based on reading online articles, blogs and Q&A websites.)

Applying concurrency to a C++ project is more or less a rigorous exercise in software engineering risk management. You have to choose strategies based on your acceptable level of risk; you have to keep your options open so that if the current strategy comes to a dead end you can switch to another strategy without losing a significant amount of completed work; you have to research and prototype a bit further than the current implementation schedule to keep yourself well-informed; avoid the latest and not-yet-proven fads, etc.

A few risks specific to concurrency:

Any third-party dependency not specifically designed to be usable in multi-threaded environment will be an additional risk.

Any closed-source dependency whose vendor has not fully-committed to supporting its users in multi-threaded environment will be an additional risk, and usually has no mitigations other than switching to an alternative.

Firstly, if it is not engineered to a high standard of thread-safety, it typically cannot be trusted in a multi-threaded environment.

"Fully-committed to supporting" means that they are willing to take the extra effort of investigating sporadic race conditions on your behalf as long as you can provide a proof-of-concept that (sporadically) reproduces the race condition. This assumes you are using the library correctly in the first place.

Computational workloads are relatively a lot easier to parallelize than I/O (latency) workloads.

If your workload is network-based and/or disk-based, you can lower the risk by using the existing asynchronous I/O that is provided either natively by the OS, or libraries such as boost::asio.

If this is your case, tackling async I/O would be your first prototypical step toward success.

This means you have to tolerate the proliferation of callbacks. You trade tediousness (lack of expressiveness, more code maintenance overhead, more documentations) for lowered risk (of using a tried-and-true approach).

Library-based C++ Coroutine is a somewhat high-risk approach.

You are basically playing sleight-of-hand before the operating systems.

C++ Coroutine implementation is tied to specific OS versions (say, at least on Windows). New OS versions may implement new process-level features which breaks pre-compiled C++ code linked against an outdated version of Coroutine.

If you use threading library, consider carefully whether the library has the full blessing of the OS vendor.

This typically means Intel TBB for Linux-based x86 systems, Microsoft PPL for x86-based Windows (Desktop and Server), etc.

Do not put too much hope on "silver-bullets" which claims to minimize necessary changes to legacy code. Typically, applying concurrency imply making massive changes to legacy code.

If your application is also memory-bound, try to see if you can mitigate that just by buying more and more RAM (and for your bill-payers to do the same). Otherwise, memory-bound issues can be hard to solve on top of concurrency.


问:
How to solve the Lava flow anti-pattern?
In this blog post, the author describes an anti-pattern called the "lava flow"

In a nutshell, the lava flow anti-pattern happens when many programmers lead the development of an application, each of them trying to gradually change the technology the said application is using.

Here's a summary of the situation the blog post describes:

Laurence starts the development of the application with the technology A

Laurence finds another job, Bruce comes in. He tries to convince the management that technology B is better. He asks for time to be allocated for refactoring. But due to budget and time constraints imposed by the management, he ends up writing new code with technology B, and tries to refactor – bits by bits – the old code from technology A to B.

Bruce finds another job, Ina comes in. She recommends technology C, ...

and this goes on over and over again.

At the end, the application is using technologies A, B, C, D, E, F. Because each programmer added their new technology, and tried to refactor the legacy code, but not all of it.

My question is the following, imagine what should have Bruce (the second programmer done) ? What is the best practice here? I understand that this depends on the situation, the technologies involved, and other factors... But is there a good rule of thumb?

Should you embrace legacy code?
Should you block the development process, and say "I can't do anything without any refactoring"?
Is the lava flow anti-pattern not so bad after all?

答:
Several ideas. Although I am not very sure how generally applicable they are.

First, in a lot of articles that reference this anti-pattern, the first advice is to resist the urge. One way to resist the urge is to understand the Dunning Kruger effect, and to spend time exploring whether the urge to refactor could have been influenced by the lack of familiarity of the original design and requirements of the existing architecture.

Second, along the same line of Dunning-Kruger effect, another way to resist the urge is to understand the "Shu-ha-ri" concept. That is, sufficient understanding and practice of the fundamentals is a prerequisite before one can contemplate exploration and innovation. When applied to the lava-flow anti-pattern, it means one should have a sufficient understanding of and maintenance experience on the existing system before being gradually allowed to make more dramatic changes to its architecture.

Third, an unreasonable yet sometimes effective way to resist the urge is to apply a healthy bit of "if it ain't broken, don't fix it." I say it is unreasonable because it is not based on reasoning, but instead on stubbornness. Yet it sometimes result in the correct outcome (a dramatic change not being carried out). The saying should not be taken literally; it should be seen as a tongue-in-cheek that reminds people of the importance of software stability.

Fourth, from the management perspective, lava-flow should be less likely to occur if there is more team continuity (that a team stays together for a longer period of time, without being overwhelmed by turnover rate, and for each project they work on, they will stick with it throughout a large part of its lifecycle.)

Some business analysis such as SWOT (strengths, weaknesses, opportunities, and threats) are useful in fostering an objective assessment of an architecture-change proposal.

Version control, change control and configuration management can be used to allow a team to safely explore alternative architectures while keeping the production system unaffected by the changes. If the exploration fails, it is acceptable to discard the failed attempts.

Finally, one must remember that innovation cannot happen in environments that do not permit exploration (and tolerate the risk of failures or wasted efforts).

ContentLicense: CC BY-SA 3.0


问:
Understanding basics of object declaration in Java
Is there a case when an object is declared without a call to the constructor?
as in, for example:

```<code>ArrayList<Integer> grades;
</code>```

Or is it always the case that  ArrayList<Integer> grades (as in our example here) would always be followed by a call to a constructor as in,

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

?

If the latter is the case i.e. a declaration of an object is always followed by its initialization with a constructor then why isn't

```<code>ArrayList<Integer> grades;
</code>```

already implies

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

Otherwise when is it the case that an object is declared without an immediate call to the constructor following it?

Is it the case that

```<code>ArrayList<Integer> grades;
</code>```

can be initialized by anything other than

```<code>= new ArrayList<Integer>();
</code>```

答:
then why isn't

```<code>ArrayList<Integer> grades;
</code>```

already implies

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

First, read @AvivCohn's answer about references.

Second, besides @Basilev's answer about dependency injection, there are also two reasons why an implicit call to new may not be desired (what follows are Java-specific and not programming concepts in general):

Construction of a new object is "expensive"

edit: As @MikePartridge mentioned helpfully in the comments, I don't mean "expensive" in the sense of object creation per se, but whether an object can be created with just a new MyObject(...) one-liner or not. Do see this link that dispels with the myth that object creation is expensive.

Your ArrayList example will be a bad example of showing why this is so, but consider an object that requires many fields to be set, which may each require their own expensive construction. The fields' values may have to be retrieved from a database or remote procedure calls. That is why we have the builder or factory patterns that builds the object for us, before assigning that to the reference.

This is related to dependency injection.

Of course, implicitly, there will be a new MyObject(...) called in the builder/factory, but the object will be initialized properly before the assignment.

On a related note, sometimes the constructor then becomes a private constructor following the builder pattern, as callers to the instantiation of said class need not know how the object is initialized.

There can be different ways of assigning an object to a reference

Here are actually two examples to show this, but I'm just going to club them under the same reason. In both examples, test can only be set once due to its final modifier, which prevents simple programming mistakes such as over-writing the reference (and then possibly making the wrong comparisons). In any case, they (hopefully) show why there cannot be an implicit assignment to new String(), and why it is not desired. Again, the call to new (just declaring "..." does that in Java) is done explictly during the assignment, instead of implicit as you have asked in your question.

switch/if logic to determine value to set

```<code>final String test;
switch (value) {
case A:
    test = "some-text";
    break;
case B:
    test = "more-text-please";
    break;
...
}
</code>```

try-catch to do alternative assignment in case of exceptions

```<code>final String test;
try {
    test = someMethodThatReturnsAStringOrMayThrowAnException();
} catch (SomeException e) {
    logThisException(e);
    test = "alternate-value";
}
</code>```

Body:
then why isn't

ArrayList<Integer> grades;

already implies

ArrayList<Integer> grades = new ArrayList<Integer>();

First, read @AvivCohn's answer about references.

Second, besides @Basilev's answer about dependency injection, there are also two reasons why an implicit call to new may not be desired (what follows are Java-specific and not programming concepts in general):

Construction of a new object is "expensive"

edit: As @MikePartridge mentioned helpfully in the comments, I don't mean "expensive" in the sense of object creation per se, but whether an object can be created with just a new MyObject(...) one-liner or not. Do see this link that dispels with the myth that object creation is expensive.

Your ArrayList example will be a bad example of showing why this is so, but consider an object that requires many fields to be set, which may each require their own expensive construction. The fields' values may have to be retrieved from a database or remote procedure calls. That is why we have the builder or factory patterns that builds the object for us, before assigning that to the reference.

This is related to dependency injection.

Of course, implicitly, there will be a new MyObject(...) called in the builder/factory, but the object will be initialized properly before the assignment.

On a related note, sometimes the constructor then becomes a private constructor following the builder pattern, as callers to the instantiation of said class need not know how the object is initialized.

There can be different ways of assigning an object to a reference

Here are actually two examples to show this, but I'm just going to club them under the same reason. In both examples, test can only be set once due to its final modifier, which prevents simple programming mistakes such as over-writing the reference (and then possibly making the wrong comparisons). In any case, they (hopefully) show why there cannot be an implicit assignment to new String(), and why it is not desired. Again, the call to new (just declaring "..." does that in Java) is done explictly during the assignment, instead of implicit as you have asked in your question.

switch/if logic to determine value to set

final String test;
switch (value) {
case A:
    test = "some-text";
    break;
case B:
    test = "more-text-please";
    break;
...
}

try-catch to do alternative assignment in case of exceptions

final String test;
try {
    test = someMethodThatReturnsAStringOrMayThrowAnException();
} catch (SomeException e) {
    logThisException(e);
    test = "alternate-value";
}


答:
I think your summary have over-simplified the blog post somewhat. :p I'm going to pick out three sentences, which I think is crucial as to explaining why code became... lava.

The code gen system had somewhat broken down after Bruce had left. None of the remaining team really understood how it worked, so it was easier just to modify the code by hand.

Lesson #1: The team needs to fully understand how the things work. If Bruce is a bad educator, address that (probably from management), not to work around the code through "modifying it by hand".

She asked Simon what to do. “Yeah, I think that code was written by some guy who was here before me. I don’t really know what it does. Best not to touch it in case something breaks.”

Lesson #2: Write tests. Let the tests break to sound out that someone's assumption is/was wrong, and then address that. On a related note, don't be afraid to refactor or even modernize the code. Just make sure that safeguards are in place to make it explicit when "things break", before the code goes into production.

Ina, frustrated by management who didn’t understand the difficulty of maintaining such horrible legacy applications, left for a start-up where she would be able to build software from scratch.

Lessons #3 and #4: You need buy-in from the management, and don't adopt a Not Invented Here mindset. One step better is to not confuse that with refactoring or modernizing the code. If you really must switch from J2SE 1.4 to Java 8 to take advantage of 12 years of improvements and at the same time solve a great deal of technical debt, which will involve re-writing 90% of the codebase, go ahead. There is nothing wrong with reinventing the wheel here, because you have to. Just don't redevelop things for the sake of redevelopment.

Related to lesson #3:
How can I convince management to deal with technical debt?

Title: How to solve the Lava flow anti-pattern?

Body:
In this blog post, the author describes an anti-pattern called the "lava flow"

In a nutshell, the lava flow anti-pattern happens when many programmers lead the development of an application, each of them trying to gradually change the technology the said application is using.

Here's a summary of the situation the blog post describes:

Laurence starts the development of the application with the technology A

Laurence finds another job, Bruce comes in. He tries to convince the management that technology B is better. He asks for time to be allocated for refactoring. But due to budget and time constraints imposed by the management, he ends up writing new code with technology B, and tries to refactor – bits by bits – the old code from technology A to B.

Bruce finds another job, Ina comes in. She recommends technology C, ...

and this goes on over and over again.

At the end, the application is using technologies A, B, C, D, E, F. Because each programmer added their new technology, and tried to refactor the legacy code, but not all of it.

My question is the following, imagine what should have Bruce (the second programmer done) ? What is the best practice here? I understand that this depends on the situation, the technologies involved, and other factors... But is there a good rule of thumb?

Should you embrace legacy code?
Should you block the development process, and say "I can't do anything without any refactoring"?
Is the lava flow anti-pattern not so bad after all?


问:
Is it a sane thing to return Streams wherever we would normally return Collections?
While developing my API that is not tied to any legacy code, I often find myself writing methods that are purely Streams pipeline terminated by collecting the results. Like this one:

```<code>ImmutableSet<T> deriveSomethingMeaningfulFromPrivateState() {
    return myPrivateThingies.stream()
        .map(this::ownerOfThing)
        .map(Owner::socialStatus)
        .filter(SocialStatus::isHeAFineMatey)
        .collect(MyCustomCollectors.toImmutableSet());
}
</code>```

Now, most of the clients of this class will usually need the Collection (in this case, an ImmutableSet) to search elements and iterate over it, but some clients may benefit from having a Stream so they could pipe some more operations on top of that Stream without the need to obtain a new stream from the Collection. So returning a Stream gives the cliens a superset of options they would have if they just had the Collection (after all, they can always collect() the Stream themselves:

```<code>Stream<T> deriveSomethingMeaningfulFromPrivateState() {
    return myPrivateThingies.stream()
        .map(this::ownerOfthing)
        .map(Owner::socialStatus)
        .filter(SocialStatus::isHeAFineMatey);
        // No collect
}
</code>```

This approach is tempting for me to try out as I don't see any potential flaws it could have. However, I've never seen this approach in any library (probably becase there weren't many libraries released after the appearance of Java 8), so I'm a bit afraid to adopt it. Existing library classes usually return Collections when they derive something from the private state.

Is there something bad that could happen if I decide to return a Stream wherever my pre-Java-8 self would return a Collection? Or probably am I doing something of an antipattern here with all that deriving from private state?

答:
The most important thing to consider: Streams can only be iterated once, whereas you have more flexibility over a Collection: you can continue to create more Streams or even Iterators to do additional, repetitive processing on the results.

So if you are not sure whether callers of the method are going to use the results once and only once, it's better to return a Collection.

Your sample code has one obvious error: why would a SocialStatus has the concept of a person, he?


问:
Can i write html on one line only in my php code?
i need to embed a html 301 redirect in my php code and i wanted to save chars in my html.
 Can i write HTML on one line since it is parsed? Is there anything against this practice?

```<code>?>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>301 Moved Permanently</title></head><body><h1>Moved Permanently</h1><p>The document has moved ">here.</p></body></html>
<?
</code>```

thank you

答:
The general practice is to redirect to an error page whose name is based on the type of error code, for instance a 301 redirect would be called 301.html.  You can pass url parameters for the location and you could use a small javascript to extract these parameter values.  The reason why you should generally use html rather than php is that html is more robust, and should there be serious problems with the server, at least if the server can still serve static files, the errors should still work as expected.

If readability is your issue, putting this page in its own file is as best as you can hope for.  You can fully expand the html in its own page, so it is readable, yet it is also equally functional.  If optimization is your concern, this is not the approach you should take.  There are plenty of libraries in php that will compact these files for you.  In the long run, it is not worth it to you to try to squeeze everything into one line, even for a page that isn't likely to change.

Body:
i need to embed a html 301 redirect in my php code and i wanted to save chars in my html.
 Can i write HTML on one line since it is parsed? Is there anything against this practice?

```<code>?>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>301 Moved Permanently</title></head><body><h1>Moved Permanently</h1><p>The document has moved <a href="<?php echo $location ?>">here</a>.</p></body></html>
<?
</code>```

thank you


答:
Your single-line HTML snippet will work fine. Improperly written browsers could conceivably choke on one-liners that exceed ridiculous maximum lengths, but in practice something like your snippet should not pose any problem.

Of course, since you work in PHP anyway, my preferred way of handling redirections would be something like:

```<code><?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.New-Website.com");
?>
</code>```

But that's up to you. :-)

Title: Can i write html on one line only in my php code?

Body:
Your single-line HTML snippet will work fine. Improperly written browsers could conceivably choke on one-liners that exceed ridiculous maximum lengths, but in practice something like your snippet should not pose any problem.

Of course, since you work in PHP anyway, my preferred way of handling redirections would be something like:

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.New-Website.com");
?>

But that's up to you. :-)


问:
Why do filesystems read and write in blocks?
I read that file systems usually access data in blocks, whose size is integral multiple of disk block size. Why don't they read individual disk blocks?</p>

答:
Because reading multiple blocks allows the OS to cache the next few blocks and avoid the latency when the application eventually needs them.

The biggest slowdown in accessing spinning disk drives (HDD and optical disk) is the seek time, literally the reading head moving to where the track with the block is.

This is alleviated with solid state but reading adjacent blocks is still faster than reading out of order.


问:
Where can I get free public raw data?
In web development, a mashup is a web page or application that uses and combines data, presentation or functionality from two or more sources to create new services.

There are many sources for getting data (raw information). Governments are good examples.

However many of those cost and have complicated licensing.
For instance SMHI in Sweden sells temperature data meanwhile our neighbor country Norway gives it away for free.

One would say what kind of application are you building and what data do you need?  I would say give me some interesting data and I will do a good mashup of it. I could just plot it on Google maps for instance.

So the question is: Where can I get free data?

Note: I'm not interested in data mining using a webcrawler!

Please share your sources with me.

答: For a comprehensive catalog of US government data and supported formats, look here: http://www.data.gov/</p>

ContentLicense: CC BY-SA 2.5

Title: Where can I get free public raw data?


问:
Why do schools teach arrays over List?
Most of the assignments in my school for the initial programming classes required me to use arrays. I work full time now, and I never used an array for any project that I have worked on. Even in the exisiting projects I never saw the use of arrays anywhere. In my opinion, List is easier to use and is a standard. Why do professors tell students to use arrays in their assignments? Is it just so that students understand the basics? </p>

<p>Since most of the universities teach Java, this question is specific to Java. </p>

答:
It's because the most crucial thing in academic education is to teach you to use the correct terminology to describe the things you do.

List is something other that array. and You can't use java.util.List in Java because it's an interface. You usually use java.util.ArrayList which being a List implementation, is not a list, but an object wrapper around dynamic array. So you say you use a 'List' but you use an array.

It's very reasonable to skip that terminological chaos and simply use arrays to learn students what is array. If you use arrays in Java, at least you use arrays.

Honestly, it's also the argument why teaching programming with Java isn't a good idea. It's hard to learn the basic concepts of programming correctly.

Title: Why do schools teach arrays over List?


答:
Read speed and caching is an important factor, but it's not the only factor, and perhaps not even the primary factor in selecting a filesystem's block size.  Every block on your filesystem has overhead associated with it.  The filesystem must track which blocks are free, which blocks belong to which files, etc.  This overhead must be stored on the disk somewhere, which takes away useful space that actually stores data.

If you make your filesystem blocks larger, that makes your overhead smaller, and gives you more useful space.  The trade off is the risk of more slack space in the last block of a file, which takes away useful space.  Some filesystems mitigate this risk by using a variable block size, or by block suballocation.  That comes with its own overhead and tradeoffs.  Also, blocks that are too large may no longer fit into a CPU's cache.

Then the question becomes why don't disk manufacturers just make their block sizes larger to better match the filesystem block sizes?  Two main reasons.  One is that disk manufacturers don't know what kind of filesystem will eventually be put on there.  The ideal block size for a desktop with a lot of little files is different from a media server in a RAID configuration storing movies, for example.  The second reason is manufacturing defects and wear might cause blocks to be marked as unusable, so it's important to select disk block sizes that will maximize the amount of useful remaining space when a defect occurs.

Title: Why do filesystems read and write in blocks?

Body: I read that file systems usually access data in blocks, whose size is integral multiple of disk block size. Why don't they read individual disk blocks?</p>


答:
Is there a case when an object is declared without a call to the constructor?

There certainly is.

All of them, in fact.

Declaring an object variable creates a location ("address") into which the program can later write a reference ("pointer") to an instance of an object [of the specified Type].

Instantiating an object is the action that calls the relevant constructor.

The ...

```<code>Type name = expression ;
</code>```

... syntax is just a compact way of doing the declaration and instantiation as a "one-liner", but it is functionally no different to ...

```<code>Type name [ = null ] ;
name = new Type( argument, ...);
</code>```

Secondly:

Is it the case that "ArrayList<Integer> grades" can be initialized by anything other than "= new ArrayList<Integer>()".

Again, Yes.

You can initialise the variable called grades to the value of any expression of the data Type "ArrayList", for example.

```<code>ArrayList<Integer> grades = class.getStudentGrades();
</code>```

Title: Understanding basics of object declaration in Java

Body:
Is there a case when an object is declared without a call to the constructor?
as in, for example:

```<code>ArrayList<Integer> grades;
</code>```

Or is it always the case that  ArrayList<Integer> grades (as in our example here) would always be followed by a call to a constructor as in,

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

?

If the latter is the case i.e. a declaration of an object is always followed by its initialization with a constructor then why isn't

```<code>ArrayList<Integer> grades;
</code>```

already implies

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

Otherwise when is it the case that an object is declared without an immediate call to the constructor following it?

Is it the case that

```<code>ArrayList<Integer> grades;
</code>```

can be initialized by anything other than

```<code>= new ArrayList<Integer>();
</code>```

Body:
Is there a case when an object is declared without a call to the constructor?

There certainly is.

All of them, in fact.

Declaring an object variable creates a location ("address") into which the program can later write a reference ("pointer") to an instance of an object [of the specified Type].

Instantiating an object is the action that calls the relevant constructor.

The ...

Type name = expression ;

... syntax is just a compact way of doing the declaration and instantiation as a "one-liner", but it is functionally no different to ...

Type name [ = null ] ;
name = new Type( argument, ...);

Secondly:

Is it the case that "ArrayList<Integer> grades" can be initialized by anything other than "= new ArrayList<Integer>()".

Again, Yes.

You can initialise the variable called grades to the value of any expression of the data Type "ArrayList", for example.

ArrayList<Integer> grades = class.getStudentGrades();


问:
Definition of the NHibernate Mapping by Code / EF Code First pattern?
Sub-questions:

Does this pattern have a formal definition?

Who invented it?

Is it considered a DSL?

The reason why I am asking is because I would like to better assess its applicability to non-classic-DB scenarios, for example as an alternative to configuration files with a custom format, that don't need to be changeable after compilation.

答:
```<code>Does this pattern have a formal definition?
</code>```

This is also referred as convention over configuration.

```<code>Who invented it?
</code>```

This is a hard question, according to Wikipedia it goes back to 1960's. Apparently it's influenced by the concept of default.

```<code>Is it considered a DSL?
</code>```

I would say yes, because it's specific to the domain of ORM framework (related to the examples you have pointed out)

Body:
Does this pattern have a formal definition?

This is also referred as convention over configuration.

Who invented it?

This is a hard question, according to Wikipedia it goes back to 1960's. Apparently it's influenced by the concept of default.

Is it considered a DSL?

I would say yes, because it's specific to the domain of ORM framework (related to the examples you have pointed out)


答:
For the sake of simplicity, Java designers decided Strings, despite not being primitives, can be declared and initialized as such.

```<code>String s = "test";
</code>```

which is the same as

```<code>String s = String("test");
</code>```

Something similar they did with arrays:

```<code>int[] numbers = {1,2,3};
</code>```

Those are examples of objects being initialized without explicitly calling their constructors with new(). but you ca be sure the constructor is being called anyway.

Body:
For the sake of simplicity, Java designers decided Strings, despite not being primitives, can be declared and initialized as such.

String s = "test";

which is the same as

String s = String("test");

Something similar they did with arrays:

int[] numbers = {1,2,3};

Those are examples of objects being initialized without explicitly calling their constructors with new(). but you ca be sure the constructor is being called anyway.


问:
Most efficient LINQ result for Contains() query
I currently use the following:

```<code>var result = list.Union(otherList).SelectMany(l => l.children).ToList()

foreach(var child in lotsOfChildren){
    something = result.Contains(child)
}
</code>```

I only use result for querying if the list contains items, using result.Contains(x).

This look to be inefficient to me, as, presumably, Contains() has to enumerate the entire (static) list each time, to check if an item is contained.

I noticed ToDictionary() and ToLookup() extension methods, however both these require a key to be defined, which is unnecessary.

I guess what I'm really looking for is a ToHashSet() sort of thing - would I have to create this manually, as in .ToLookup(c => c.GetHashCode, c => c)?  Or is there a built in method I'm missing? Or, alternatively, is this something the compiler will optimise, and I don't need to care about.

答:
You can trivially define an extension method for ToHashSet if that's what you're looking for.

```<code>public static class Extensions
{
    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
    {
        return new HashSet<T>(source);
    }
}
</code>```

You should now be able to use it in your original example:

```<code>var result = list.Union(otherList).SelectMany(l => l.children).ToHashSet()

foreach (var child in lotsOfChildren)
{
    something = result.Contains(child)
}
</code>```

Body:
You can trivially define an extension method for ToHashSet if that's what you're looking for.

public static class Extensions
{
    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
    {
        return new HashSet<T>(source);
    }
}

You should now be able to use it in your original example:

var result = list.Union(otherList).SelectMany(l => l.children).ToHashSet()

foreach (var child in lotsOfChildren)
{
    something = result.Contains(child)
}


问:
How to selecting Teams with Minimum Difference between Knowledge Levels
For the below challenge from a programming site, I am bit confused.

Problem Statement:

A Professor of Physics gave projects to the students of his class. The students have to form a team of two for doing the project. The professor left the students to decide the teams. The number of students in a class will be even.

Each student has a knowledge level. It tells how much knowledge each student has. The knowledge level of a team is the sum of the knowledge levels of both the students.

The students decide to form groups such that the difference between the team with highest knowledge and the one with lowest knowledge is minimum.

Input

First line of the input will contain number of test cases t; In the next t lines the first number is n the number of students in the class followed by n integers denoting the knowledge levels of the n students

Output

Your output should be a single line containing the lowest possible difference between the team with highest knowledge and the one with lowest knowledge.

Sample Input

2

4 2 6 4 3

6 1 1 1 1 1 1

Sample Output

1

0

[My Attmept]

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectTeam
{
    class Program
    {
        static void Main(string[] args)
        {
            int testCasesCount = Convert.ToInt32(Console.ReadLine());
            // Solve each test case
            for (int i = 0; i < testCasesCount; i++)
            {
                String line = Console.ReadLine();
                String[] components = line.Split(' ');
                int numberOfStudents = Convert.ToInt32(components[0]);
                int[] studentsKnowledge = new int[numberOfStudents];

                // Read input

                for (int j = 0; j < numberOfStudents; j++)
                {
                    studentsKnowledge[j] = Convert.ToInt32(components[j + 1]);
                }

                // Done

                // Solve
                List<int> listOfPossibleTeams = new List<int>();
                for (int k = 0; k < numberOfStudents; k+=2)
                {
                    int knowledge = studentsKnowledge[k] + studentsKnowledge[k + 1];

                    // Create others
                    if (k >= 2)
                    {
                        int toPair = studentsKnowledge[k];
                        for (int l = k-1; l >= 0; l--)
                        {
                            listOfPossibleTeams.Add(toPair + studentsKnowledge[l]);
                        }
                        toPair = studentsKnowledge[k + 1];
                        for (int l = k-1; l >= 0; l--)
                        {
                            listOfPossibleTeams.Add(toPair + studentsKnowledge[l]);
                        }
                    }
                    //
                    listOfPossibleTeams.Add(knowledge);
                }

                listOfPossibleTeams.Sort();

                // select minimum knowledge diff

                int minumimKnowledge = int.MaxValue;
                for (int m = 0; m <= listOfPossibleTeams.Count() - numberOfStudents / 2; m++)
                {
                    int diff = Math.Abs(listOfPossibleTeams[m] - listOfPossibleTeams[m +(numberOfStudents / 2) - 1]);
                    if (diff < minumimKnowledge)
                    {
                        minumimKnowledge = diff;
                    }
                }

                Console.WriteLine(minumimKnowledge);
            }
        }
    }
}
</code>```

But the above solution fails for test case:

1

8 4 2 4 2 1 3 3 7

My Code outputs 0, while the actual answer is 2.

My Approach is to create all the possible valid combinations of teams, and get their knowledge, sort all the knowledge, and select n/2(n is number of students) contiguous elements having minimum difference between the boundaries of selection. But this doesn't work.

Eventually I found the problem solved by someone in the internet, and I tried the solution and it worked. But I do not understand how does it work? The code below:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectTeam
{
    class Program
    {
        static void Main(string[] args)
        {
            int testCasesCount = Convert.ToInt32(Console.ReadLine());
            // Solve each test case
            for (int i = 0; i < testCasesCount; i++)
            {
                String line = Console.ReadLine();
                String[] components = line.Split(' ');
                int numberOfStudents = Convert.ToInt32(components[0]);
                List<int> studentsKnowledge = new List<int>();

                // Read input

                for (int j = 0; j < numberOfStudents; j++)
                {
                    studentsKnowledge.Add(Convert.ToInt32(components[j + 1]));
                }
                studentsKnowledge.Sort();
                // Done

                // Solve
                int diff = (studentsKnowledge[0] + studentsKnowledge[numberOfStudents - 1]);
                int max = diff, min = diff;
                for (int k = 1; k < studentsKnowledge.Count / 2; k++)
                {
                    diff = studentsKnowledge[k] + studentsKnowledge[numberOfStudents - 1 - k];
                    if (diff > max)
                        max = diff;
                    if (diff < min)
                        min = diff;
                }
                Console.WriteLine(max - min);
            }
        }
    }
}
</code>```

I do not understand how does the above code works. The above code doesn't even creates all the possible combinations. Is it using some mathematical concept which I am not able to think of, or is my interpretation of the problem wrong? Please help.

答:
In this answer I will focus on the thinking part and less on the coding part. In other words, if the thinking is not correct, the code will probably not give the result you expected, even if the code implements your thinking faithfully.

I will just point out the flaw in the code part, without going into detail: listOfPossibleTeams contained all possible sums of pairs, without considering conflicts - if you have already paired up students A and B, it is not be allowed to pair up B and C again because that would have assigned B to two teams simultaneously. However, the array listOfPossibleTeams will contain the sums of A+B and B+C and A+C, and your subsequent use of this array did not try to detect this conflict. This is why the answer it gives was wrong.

The mathematical knowledge needed to understand this conflict is taught in Combinations

Understanding why the correct solution works is a bit more involved. The mathematical knowledge is taught in Order statistic, but typically students who are good at computer science are able to come up with an intuition about order statistic regardless of whether they learn it from school formally. (Just personal opinion; no references)

One way of intuitively thinking about the problem is this, via divide-and-conquer:

Suppose the students are divided into two groups - the upper half and the lower half.

Let's say pick two students from the upper half (named A and B), and two students from the lower half (named C and D).

Would it be better if we pair up the two from the upper half (A with B), and then pair up the two from the lower half (C with D)?

Or, would it be better if we pair up one from from each half, giving (A with C), and (B with D)?

You will notice that it is always better to pair up one from the lower half with one from the upper half (the latter case).

Now, further subdividing into more tiers, and repeat the test. Eventually you will intuitively see that pairing the highest with the lowest might be a good strategy worth trying.

Trying to prove it with theorems will involve a lot more effort. Most of the time, a beginning computer science student will just give it a try, and see if the code gives the same answers as the worked examples. In other words, not everyone go through the theoretical process when looking for a solution. Some goes with intuition and were able to cope with the assignments, at least in the introductory level.


问:
Is SICP still relevant?
Today, I came across this book entitled:The Structure and Interpretation of Computer Programs

I read the Table Of Contents and it really interests, me. It seems to be exactly what I've been looking for! From what I've read online, the book seems to have been pretty influential.

However, everyone who read it, read it like 20 years ago from what it seems.

Does the book still provide valuable knowledge?
Has it been superseded by another influential book I should be aware of?

答:
However, everyone who read it, read it like 20 years ago from what it seems.

Actually, it was the basis of MIT's 6.001 introduction to programming until fairly recently, and still is used for similar courses in other universities even today.

Has it been superseded by another influential book I should be aware of?

Not really.

There are other books that take different approaches to teaching, such as How to Design Programs, which was specifically created to address certain perceived shortcomings in SICP, or Concrete Abstractions, but SICP is still a timeless classic.

Abstraction, Reuse, Analytic Thinking, Program Design, those aren't things that just go out of fashion.

Personally, I'd recommend starting with HtDP, and then move on to SICP, but that's just my opinion.

Title: Is SICP still relevant?


问:
Is the Model part of MVC an inner platform
I'm not particularly up on MVC as an architecture but isn't the Model just a duplication (except slower and buggier) of the database?

Given modern databases support stored queries, user definable functions etc. why treat them as an implementation detail?

Is it because programmers generally don't want to learn SQL/ Relational design?
Or because there's a fundamental mismatch between relation and object models?

Broadly the database can present an API, why do it twice & more slowly.

Any McConnell like numbers to back up viewpoints would be greatly appreciated

答:
You've got things the wrong way around.

The model is not a poor replica of the data base. No programmer cares about the data base. The data base exists only so that in a future invocation, we can easily reconstruct the same state of our business objects as before. Data bases are strictly a means to an end. They allow some processing and offer some tricks to speed up the inefficiency caused by mass storage access, but then they are also the sole cause of these inefficiency problems. If we could get by entirely without data bases and instead persist our business objects magically in the memory of tamed unicorns instead, we'd do it in a heartbeat.

The model isn't like that. The model supports all operations that we can do in our preferred programming language, which is why we chose it. The model is what we'd like to program. It is so central to the system that it is very important not to pollute it with concerns of other levels. This is why indices, table scans etc. should be kept out of the model, but also why combo boxes, HTTPRequests etc. should be kept out.

Not having a model would mean that the same code that deals with reading and writing widgets also deals with SQL INSERTs and connection parameters. That would be very bad, because thinking about two entirely different things all the time halves your efficiency as a developer. This s why it makes sense to separate those concerns and have layers dealing with the UI, with business logic, and with data storage. It leads to an increased amount of code, but since each of the resulting classes has a clearer focus of what it's supposed to do, general efficiency increases.

This result has been hard-won over several generations of programmers, and since it's non-obvious, every new generation has to be convinced anew that they will be better off not trying to do everything at once. But the majority of professionals will confirm that in this respect, having more and simpler classes is better, even if you end up with more code lines in total.


问:
Why (or why not) are existential types considered bad practice in functional programming?
What are some techniques I might use to consistently refactor code removing the reliance on existential types? Typically these are used to disqualify undesired constructions of your type as well as to allow consumption with a minimal of knowledge about the given type (or so is my understanding).

Has anyone come up with a simple consistent way to remove reliance on these in code which still maintains some of the benefits? Or at least any ways of slipping in an abstraction that allows their removal without requiring significant code churn to cope with the alteration?

You can read more about existential types here ("if you dare..").

答:
I am not too familiar with Haskell, so I will try to answer the general part of the question as a non-academic functional C# developer.

After doing some reading, it turns out that:

Java wildcards are similar to existential types:

Difference between Scala's existential types and Java's wildcard by example

Wildcards aren't implemented in C# completely: generic variance is supported, but call site variance is not:

C# Generics: Wildcards

You might not need this feature everyday, but when you do you will feel it (e.g. having to introduce an extra type to make things work):

Wildcards in C# generic constraints

Based on this information existential types / wildcards are useful when implemented properly and there is nothing wrong with them per se, but they can probably be misused just like other language features.


问:
Restructure Service - Http - Notification communication
I am trying to restructure a project to make components reusable and clearer.

Consider the following scenario:

A WakefulBroadcastReceiver (in my case called SimpleWakefulReceiver) will start my LocationService. Once a new GPS fix has been received, the client should transmit this to a server and the server response should be shown to the user.

Implementation attempt:

I have two other classes:

HttpManager

NotificationManager

The LocationService creates an anonymous reference and calls a method like this:

```<code>new HttpManager(this).sendGps(longitude, latitude, accuracy, utcTime);
</code>```

The constructor of the HttpManager class

```<code>public HttpManager(Context context)
{
    this.context = context;
}
</code>```

After receiving a response from the server, I do practically the same as above within the HttpManager class:

```<code>new NotificationManager(context).sendNotificationToUser(resultData);
</code>```

The problem:

When the job is done, an error has occurred or other conditions, the WakeLockshould be released and the service should be stopped.

Therefor I often call the methods

context.stopService(new Intent(context, LocationService.class));

SimpleWakefulReceiver.completeWakefulIntent(new Intent(context, LocationService.class));

within the NotificationManager and the HttpManager class which seems like a code smell.

I'm looking for a structure where I don't have to call these methods often. I'm also not sure if it is very elegant with these anonymous references or maybe implementing a ResultReceiver or IntentService would be the better way.

Question

How can I structure the project to remove this code smell?

答:
Your SimpleWakefulReceiver should not be making direct references to HttpManager. An HttpManager manages your communication with the server. It's purpose answers the question: "How do I communicate with the server?" You need another class to answer the question What do I communicate to the server?"

The Single Responsibility Principle states:

In object-oriented programming, the single responsibility principle states that every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

...

Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to change.

Try to restructure your classes with this behavior in mind. Do not be afraid to add more classes. Your classes should be small and nimble.

In your specific case, you can create a class that is responsible for wrapping the ability to send the GPS data to the server and processing it's response. Then you should only call these service startup and shutdown procedures in that one place. The rest of your code should not have to worry about these tasks, as those classes have other responsibilities.


答:
The model is just that: an object-based model of the business domain.  The database is also a model of the business domain, but in a different form, i.e. tables and relations. They complement each other; what one lacks, the other provides.   It's not an inner platform; an inner platform would subvert the technology it is imitating.  The Model does not do that; it depends on the features of a database; it doesn't replace those features.

Object-relational mapping is an imperfect solution to the impedance mismatch problem.  But relational databases and their SQL language are a mature, well-established technology with many intrinsic benefits.  Using an ORM allows you to have the best of both worlds; you can store objects in a mature, well-established technology, but still use SQL to solve set theory problems.

Further Reading

The "Vision" project, a cautionary tale about inner platform effect

(This is what an Inner Platform really looks like.  You can skip the preamble and start reading at the subheading "Introducing Vision")

Title: Is the Model part of MVC an inner platform

Body:
I'm not particularly up on MVC as an architecture but isn't the Model just a duplication (except slower and buggier) of the database?

Given modern databases support stored queries, user definable functions etc. why treat them as an implementation detail?

Is it because programmers generally don't want to learn SQL/ Relational design?
Or because there's a fundamental mismatch between relation and object models?

Broadly the database can present an API, why do it twice & more slowly.

Any McConnell like numbers to back up viewpoints would be greatly appreciated


问:
Does jQuery basically use CSS3 for animation and effects?
I originally started out this question with "what is jQuery, and how does it work", in terms of all that fancy animation, effects, slideshow plugins, etc. I was uncertain as to how JQuery does all that fancy stuff. But after reading around on the internet, I am happy to acknowledge that jQuery is basically a "JavaScript library", and by that, I think it means that jQuery is pure text, of JavaScript code, consisting of public methods, functions, constants etc, with the idea that calling these simple methods or functions can replace loads of JavaScript code, and that its has a nice consistent feel to it.

So am I right in saying that all that fancy animation, effects etc  are not "actually" achieved by JavaScript/jQuery?  They are achieved by using CSS3? And CSS3 is a style sheet language which the browser can understand, and has the capabililites of carrying out those style sheet instructions?

Very fuzzy and ambiguous question, I know, but just trying to get my head round how you get those amazing jQuery animations etc.

答:
Yes and no. jQuery uses dom-manipulation using the css-attributes to animate html-elements.

You can see how the .animate()-function works quiet good when you use the step-function:

```<code>$( "div" ).animate({
    'font-size': "26px"
}, {
  step: function( now, fx ) {
    console.log(fx);
  }
});
</code>```

The jQuery.fx.prototype contains the information of the current state of the animation:

elem: the element which is animated

prop: The property of the html-tag which is animated

now: the current state of the property

start/ end: the start and end values of the animated property

unit: the unit of the property

Some value might be familiar to css, in fact, yes jQuery uses the CSS values to change the look of an animated element.

If you look at the value now of the fx-object you can see the calculated values from jQuery. So jQuery calculates the values between the start and end -values to provide an animation. But I can't give an answer on how the calculation works, that's by now to deep for me.

In conclusing this means jQuery calculates it's own values to animate the elements. But, if I'm right, there are no transitions of CSS3 used at the moment.

Demo (Just open your console and start the fiddle)

I hope I could explained it clear enough to increase your understanding.

Body:
Yes and no. jQuery uses dom-manipulation using the css-attributes to animate html-elements.

You can see how the .animate()-function works quiet good when you use the step-function:

$( "div" ).animate({
    'font-size': "26px"
}, {
  step: function( now, fx ) {
    console.log(fx);
  }
});

The jQuery.fx.prototype contains the information of the current state of the animation:

elem: the element which is animated

prop: The property of the html-tag which is animated

now: the current state of the property

start/ end: the start and end values of the animated property

unit: the unit of the property

Some value might be familiar to css, in fact, yes jQuery uses the CSS values to change the look of an animated element.

If you look at the value now of the fx-object you can see the calculated values from jQuery. So jQuery calculates the values between the start and end -values to provide an animation. But I can't give an answer on how the calculation works, that's by now to deep for me.

In conclusing this means jQuery calculates it's own values to animate the elements. But, if I'm right, there are no transitions of CSS3 used at the moment.

Demo (Just open your console and start the fiddle)

I hope I could explained it clear enough to increase your understanding.


问:
Java Socket or SocketChannel
I am designing a server for a remote file store in Java and trying to decide whether to use asynchronous java.nio.SocketChannels or the older blocking model with Sockets. What kind of factors should I consider when choosing between these two server architectures and what kinds of tasks would be better suited to one versus the other?

Specifically, I am wondering how these respective approaches compare as:

the number of connected clients scale up,

the length of a client connection increases, and

the amount of data transferred increases.

Also, are there any other factors that I should be aware of that would favor one approach over the other?

答:
Why are you trying to solve an already solved problem? There already exists at least two good ones:

Grizzly

Writing scalable server applications in the Java™ programming language has always been difficult. Before the advent of the Java New I/O API (NIO), thread management issues made it impossible for a server to scale to thousands of users. The Grizzly NIO framework has been designed to help developers to take advantage of the Java™ NIO API. Grizzly’s goal is to help developers to build scalable and robust servers using NIO as well as offering extended framework components: Web Framework (HTTP/S), WebSocket, Comet, and more!

Netty

Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server.

'Quick and easy' doesn't mean that a resulting application will suffer from a maintainability or a performance issue. Netty has been designed carefully with the experiences earned from the implementation of a lot of protocols such as FTP, SMTP, HTTP, and various binary and text-based legacy protocols. As a result, Netty has succeeded to find a way to achieve ease of development, performance, stability, and flexibility without a compromise.

It sounds to me like you are less interested in solving the problem yourself than you are in just having the problem be solved - so you can have your remote file store. Personally, I use Netty in my application and it works great. Don't reinvent the wheel - use someone else's.

Title: Java Socket or SocketChannel


答:
Only in the least complicated of applications might the model be a duplicate of the database and not necessarily even then.

Fundamentally that assumes a 1 to 1 mapping between the data presented to the consumer and the table structure of the database (be that relational or otherwise) and in reality that its seldom the case.

If we look at MVC the Model is the model for the view - even if this does just represent a single row from a single table the odds are that there are going to be lookups, fields that as presented to the consumer have a value but as stored in the database have an ID, your model may well then contain the display values as well as the actual data that is persisted.

Then we get into all kinds of interesting questions about validation - what and how and where.

Now take another step - note that I said "consumer" - what if that consumer is not an end user looking at a screen, what it its an Single Page App consuming an API. At this point from the point of view of the client facing app there is no database - but there is a model...

What this is giving us is a logic separation where we look at models that are appropriate to the context they're used in - one for the UI maybe a different one for use in business logic and then a the storage model which may well be relational and involve several tables. By treating them separately and ensuring we are comfortable mapping between them we end up with a great deal of flexibility in our overal structure (where the "system" may then fairly trivially span multiple applications).

Of course if all your doing is straight CRUD over tables of data then the relation between data model and view model may be quite close but if using a relational database there will still always be some mapping.


问:
How to budget for a programmer you're not ready to hire yet?
I am trying to work up a budget for an app, specifically a budget for hiring a third-party programmer to add a specific feature, and I'm trying to figure out how to get a decent number.  The requirements are beyond my ability to estimate, so I'll obviously need to talk to someone with more experience, but I don't know anyone with this sort of experience.

My first thought was to just post a job on oDesk or something similar, but here's the thing: I'm not ready to hire someone yet, and it seems less-than-professional to post a job listing just so I can poll programmers on how much something might cost me later.

I can't imagine I'm the first person to encounter this problem.  Is posting a job listing an acceptable way of price estimating, or if not, how does one estimate a budget without doing that?

For what it's worth, what I'm looking for is largely a self-contained feature, with minimal integration with the pre-existing code. As an example, imagine hiring someone to animate a ball bouncing across the screen whenever a button is hit.  I can handle the menu design and button, I just need someone to work up the code that happens when that button is hit (creating an animating a new object onscreen, simulating gravity and impact physics, etc).  I'm trying to figure out how much to budget for "the programmer I'm going to hire to animate that ball," so their familiarity with the code of the project at large isn't terribly important.

答:
Maybe you should hire a developer to make the estimate and determine the budget for you. When the requirements are beyond your capability of estimate the estimate is probably way of and useless.

Also make a min-max estimation, min for when everything is easy and a max for when things are difficult.

And multiply the estimate by 2 ;) Software estimation is very difficult and developers are optimistic.


问:
Missing `$` like operators in Haskell
Below I've produced what I believe to be a summary of the standard $ like operators for various classes in Haskell. There's some gaps however. Following the applicative pattern, you would think those operators would be $$ and <$$> however I didn't see operators like that on Hoogle or Hayoo. Could someone fill in the gaps with the most commonly used operators for such gaps?

```<code>              | Function first           | Op   | Function second          | Op   |
----------------------------------------------------------------------------------
| Plain       | (a -> b)   -> a   -> b   | $    | a   -> (a -> b)   -> b   |      |
| Functor     | (a -> b)   -> f a -> f b | <$>  | f a -> (a -> b)   -> f b |      |
| Applicative | f (a -> b) -> f a -> f b | <*>  | f a -> f (a -> b) -> f b | <**> |
| Monad       | (a -> m b) -> m a -> m b | =<<  | m a -> (a -> m b) -> m b | >>=  |
-----------------------------------------------------------------------------------
</code>```

答:
The lens package provides these operators:

(&) :: a -> (a -> b) -> b

(<&>) :: Functor f => f a -> (a -> b) -> f b

From the lens documentation on (&):

This is the flipped version of ($), which is more common in languages like F# as (|>) where it is needed for inference. Here it is supplied for notational convenience and given a precedence that allows it to be nested inside uses of ($).

Since 7.8 (&) can be found in Data.Function too.

Title: Missing `$` like operators in Haskell


问:
Is Dependency Inversion a valid alternative to the pImpl idiom?
If I want to present to the user of my code an interface, that is unlikely to change, I can write only the public part of the classes in public headers and have a single private pointer to another object, that holds the private declarations. I believe this is known as The pImpl idiom.

Now imagine another approach. The public part of the class is placed into an IClass or ClassBase or whatever class, placed in the public headers. Then, in a private header (== not exposed to the user), this base class is inherited and it's methods implemented.

To me it seems that the second approach achieves the same goals as the first one. But are there any drawbacks? When to prefer which?

答:
With Pimpl, other code is free to create instances and use the class as normal. From the outside it looks exactly like a normal class. This is pretty convenient for a user but there is an efficiency penalty.

With the entire implementation of the class being private, your code is going to have to provide some way for the user to create instances - a factory method or something similar. Also, all your method calls will need to be virtual and the client code will need to use it by reference. Without knowing the actual type and size (etc) of the variable it can't be allocated on the stack or passed by value.

Both approaches protect client code from changes in the implementation but I don't think you can say they're exactly equivalent. Which one you use depends on the expected usage of the class and personally I've found uses for both patterns within the same project.


问:
Do conditional delegation or different member types break the Composite pattern?
Here's how I understand the composite pattern:

In the composite pattern, a root object is composed of objects which may be further composed.  Moreover, to be considered composite, all those objects expose a common interface.

My question appears twice in italics below.  An example given by a mentor of mine is a filesystem represented by objects:

```<code>interface Node {
  public int size();
}

class Folder implements Node {
  List<Node> contents;

  public int size() {
    int size = 0;
    for (Node n : contents)
      size += n.size();

    return size;
  }
}

class File implements Node {
  int size;

  public int size() {
    return size;
  }
}
</code>```

This seems pretty clean.  It has a nice property that I'm wondering about:

A size() call on Folder calls size() on all member Nodess, there is no condition guarding size() calls on member Nodes.  If there were a condition guarding size() calls on children Nodes, would the structure no longer be Composite pattern?

To clarify, I'll give another example.  Say a Person object can grab(), and Person is composed of 2 Hands and 1 Mouth.  Both Hand and Mouth can grab().  On an instance of Person, calling person.grab() will call grab() on one of its members capable of grab().  For instance, the left Hand will grab() if the right Hand is already full, and both Hand will grab if the object is heavy.

Is that Composite pattern, even though there are conditional guards on member calls?

答:
The composite pattern is a good choice for (recursive) tree-like structures, where the clients want to use operations from the interface without actually knowing if something is a composite or a leaf. In other words, they are expecting the derived classes to confirm to the Liskov substitution principle. What does not matter is how the operations are implemented internally.

So your Person example is not a bad choice for the composite pattern because its internal grab implementation contains a conditional. It is a bad choice because a Person is not a recursive tree-like object. It may be composed of hands and mouth, but not of other Person objects, and I do not see a good term which would qualify as a common base class for Person and Hand, or a use case where a client can ignore the fact he is asking a person to grab, or a hand.


问:
Working with static constructor in Java
I didn't get a complete understanding of static constructors in Java. If it is allowed, why it is allowed? In what scenarios would you use it? What purpose would it serve? Can someone give me a simple example please?</p>

答:
While I understand that there are many who see the notion of a "static constructor" as a misnomer, I do not believe that to be the case. The issue is in the process of constructing both classes and their instance objects. It's been stated in other threads that construction of the class is the job of the compiler. Even in Java, this is only half true.

The compiler constructs a scaffold for each class definition. The scaffold contains metadata about the class and what instances should have in them at the time of construction. If a class defines a field that is assigned a constant primitive value, then that value is included in the scaffold by the compiler. For any other value types being assigned, the compiler generates an initialization routine that is to be run 1 time, before the creation of the first class instance, that updates the scaffold with the proper values. This update cannot be done by the compiler.

Since this one-time update to the scaffold is often a critical prerequisite to the proper functioning of the instance constructors, it is also reasonable to call it a type of constructor. This is why in common OO languages that support the concept, it is called a static constructor. The concept behind the static initialization blocks in Java is little more than a semantic change to keep in line with the notion that a Java programmer should be both system and implementation agnostic.

Title: Working with static constructor in Java


问:
How do personal assistants typically generate sentences?
This is sort of a follow up to this question about NLG research directions in the linguistics field.

How do personal assistant tools such as Siri, Google Now, or Cortana perform Natural Language Generation (NLG)? Specifically, the sentence text generation part. I am not interested in the text-to-speech part, just the text generation part.

I'm not looking for exactly how each one does it, as that information is probably not available.

I am wondering what setup is required to implement sentence generation of that quality?

What kind of data would you need in a database (at a high level)?

Does it require having a dictionary of every possible word and it's meaning, along with many books/corpora annotated and statistically analyzed added to it?

Does it require actually recording people talk in a natural way (such as from TV shows or podcasts), transcribing them to text, and then adding that somehow to their "system"? (to get really "human"-like sentences)

Or are there just simple syntax-based sentence patterns they are using, with no gigantic semantic "meaning" database? Where someone just wrote a bunch of regular expressions type thing..

What are the algorithms that are used for such naturally written human-like sentences?

One reason for asking is, it seems like the NLG field is very far from being able to do what Siri and Google Now and others are accomplishing. So what kind of stuff are they doing? (Just for the sentence text generation part).

答:
If you have a so-called deep syntactic representation of what you want to generate, such as read(he,book), then it's relatively easy to generate its linear representation. One needs a formal grammar describing the syntax of the language and a morphological lexicon for inflected forms. Generation is an order of magnitude easier than analysis (since one is "creating ambiguity", not resolving it).

If you have only a logical representation (say, in first-order logic), things get more complicated. Let's say, you have buy(John,book) ∧ read(John,book). One could generate two sentences like John bought a book. John read a book but it feels unnatural. A better output would be John bought a book. He read it. Even better would be to generate one compound sentence with and. The logical representation might be similar to the deep syntactic representation above but there are no pronouns, no clause boundaries, etc. The phase of translating a purely logical representation of what one wants to convey into something more "human-like" is called "language planning" or "sentence planning" and is the harder task in the process.

OwnerDisplayName: Lance Pollard


问:
Is it a good idea to include extra libraries in jars?
When creating executable jars for a java project, it is possible to create jar bundle which includes all the external libraries used. It is also possible to create a jar without those external dependencies and provide the dependency path on run-time instead.

What I am wondering is which one is better? Is there a favorable way of doing it?

答:
It depends.

You need to think about how your product will be used by consumers. For example, if you are creating a library that will be used by others inside Maven, then you should not include the external dependencies in the jar - let Maven handle it by providing a proper pom.

However, if instead you are deploying a completed application for non-technical users, then you absolutely do want to keep everything as simple as possible for them, and you should provide the dependencies inside the Jar.

In short, think about who your users are and what their use case would be, and then decide accordingly.


问:
How to solve the Lava flow anti-pattern?
In this blog post, the author describes an anti-pattern called the "lava flow"

In a nutshell, the lava flow anti-pattern happens when many programmers lead the development of an application, each of them trying to gradually change the technology the said application is using.

Here's a summary of the situation the blog post describes:

Laurence starts the development of the application with the technology A

Laurence finds another job, Bruce comes in. He tries to convince the management that technology B is better. He asks for time to be allocated for refactoring. But due to budget and time constraints imposed by the management, he ends up writing new code with technology B, and tries to refactor – bits by bits – the old code from technology A to B.

Bruce finds another job, Ina comes in. She recommends technology C, ...

and this goes on over and over again.

At the end, the application is using technologies A, B, C, D, E, F. Because each programmer added their new technology, and tried to refactor the legacy code, but not all of it.

My question is the following, imagine what should have Bruce (the second programmer done) ? What is the best practice here? I understand that this depends on the situation, the technologies involved, and other factors... But is there a good rule of thumb?

Should you embrace legacy code?
Should you block the development process, and say "I can't do anything without any refactoring"?
Is the lava flow anti-pattern not so bad after all?

答:
First of all, you have a human resources problem.  If you want your experienced developers to stay, you need to give them a certain amount of greenfield work.  Programmers can handle quite a bit of maintenance work if they also have a separate outlet for their creative urge to work on something new.  Many programmers handle this on their own with hobby projects, but employers should be supportive.  My company recently started doing hackathon contests once every 10 weeks to give people an outlet for innovation.

On a technical side, the problem isn't so much that the technology is changing.  All code bases evolve, as third-party technologies are only supported for so long.  The bigger problem here is that the changes are not getting completed before the next one starts.  This is a sign of excessive coupling, poor cohesion, and poor testing practices in your code base.  The solution therefore is to fix that first.

In other words, rather than slowly migrating to a new technology, slowly migrate to an architecture that will allow you to quickly migrate to a new technology.  For an example, say you needed to change the operating system your product ran on.  You can't just run part of two separate operating systems during the transition.  What you can do is abstract away the OS-specific stuff little by little, then one day you'll be able to just flip the switch all at once.


问:
What is better for scalability for this specific dataset, MongoDB or MySQL?
I have a web app which has users, forms, and volunteers signed up on those forms.

Currently I am using MongoDB and have it setup with a collection for admins, and a collection for forms with volunteers attached to the forms.

It is not very efficient because I have to render the forms on two pages, so I have form data attached to admins in the user collection, but repeated in the form collection so they can be rendered individually on the form page.

Currently I have one page which needs to render admins and forms, and then the form page which just renders a single form. I am trying to minimize queries, which is why I copied form data to the user objects (admin info is also attached to the form, keeping it to one query for each page).

Volunteer information is attached to the forms, so it is copied in both collections. Obviously this is a terrible waste of space. I'm hoping someone can help me re-design this and recommend whether to stick with NoSQL or move to MySQL/Postgres.

I do not have enough experience to know which is better for this specific setup, or how to set the schemas/architecture to be scalable.

Thank you very much for your time. Any advice is appreciated, including relevant resources that I clearly do not know about.

答:
We can't answer that. It depends on more than just your schema or lack thereof. It depends also on how you hit the service (in code), how your users hit the application, what sort of caching you're prepared to implement, etc.

Use the storage mechanism that is more well suited to how you think and code. Keep interactions with that storage service as isolated and abstracted away as is reasonable for you to do. And if performance becomes a problem, hire a DBA and/or more fully abstract the service so as to compare options with a representative workload.


问:
Should POJOs be abstracted?
My coworker tends to have each POJO implement an interface.
Like Customer would implement ICustomer, with the motivation that we can now have multiple implementations of ICustomer. One example would be a JPA annotated JpaCustomer with the motivation that now we're not tied to JPA. It seems like overkill to me to abstract it that much. What are your opinion on this? Is this common?</p>

答:
The purpose of an Interface is to allow multiple implementations.  If you already require multiple implementations of a particular Interface, well then.

But having one Interface object per POJO on the off-chance that you might need more than one impelementation for each POJO is unnecessary, and creates a lot of extra work for no discernible benefit.

Title: Should POJOs be abstracted?


问:
Mixing REST and websocket in the same API
A bit of background first, I'm working on an application that manages a piece of physical equipment with motors, stuff like that. When I started on the project, there was an existing application, built with Labview and that was in a poor state. The part of the code that manages the hardware, the "drivers" were in a better shape. The goal was to write a new app, in .Net, but reusing as much as possible the existing drivers.

The architecture that was decided was to separate strongly the hardware side, written in Labview, and the management/data treatment side written in C# through the use of a REST web service, since Labview has a relatively good support of them. The Labview hardware part has the role of the server, and the .Net side connects through it, asks for status of the hardware and sends command to move the hardware and so on.

In so far, it works pretty well, the only annoying part is the amount of polling that is needed from the client side. We have some "long commands", for which we send a command that asks the hardware to do a long operation, but we want to have some updates on how it goes. For this, we send the PUT to initiate the action and then, every 500 ms (or slower depending on the action), we send a GET to have the current status of the action, until the action is done (usually defined by a flag).

When I started with the project, a few months ago, I had seen this issue and did some research to see if there was a solution to this problem, like a way to use SignalR for Labview, and didn't find anything. But now, we have found an implementation of a WebSocket server in Labview. I'm now wondering if and how this could be implemented in (or as a replacement of) our solution.

One of the solution I was envisioning was to keep the REST service for most, but create on the fly a WebSocket endpoint for those few long-lasting commands that need updating. For example, send a PUT command to do an action, for which the server would start the action, return the 200 OK and add the address of a WebSocket endpoint where the client could go to get status. As soon as the client connects to the WebSocket, the server would send updates through this. When the action is done, connection is closed, and WebSocket endpoint is closed on the server side.

I've searched a bit to see if someone were doing that kind of "mixed" service, but cannot find anything, so I'm wondering if it's really a good idea. Even though I'm not a huge fan of the amount of polling that happens now, I also really like the REST API that we have created and feel like it would be a bit of a loss to scrap it and go the WebSocket way completely. I think WebSocket is still not as universal as REST (even in .Net 4.5, the ClientWebSocket class is useable only in Windows 8, even though alternatives exists). Using WebSocket also means defining our own communication protocol (how to define commands, etc.) which can be difficult.

In a way, mixing doesn't seem completely "right" either, because I'm not going to use completely the "full-duplex" advantage of WebSocket, mostly using them for communicating back information from the server to the client in a sort of "push" way, rarely sending commands from the client to the server through the web socket.

答:
It's all about discovery: the ability of your API to be understandable and usable by the next developer encountering it.  If the WebSocket methods are easily discoverable, and it is clear that they should be used in conjunction with the ordinary REST methods, then your design is probably sound.

In practice, for this discovery to occur, I think your WebSocket methods need to be defined in close proximity with your ordinary REST methods, along with some clarifying comments suggesting their proper use and coordination.

If the WebSocket methods are meant to be used independently of the REST interface, then you can put them in their own API.


问:
Compute Adjacent Pair
I was given the following problem:

```<code>Integer V lies strictly between integers U and W if U < V < W or if U > V > W.
A non-empty zero-indexed array A consisting of N integers is given.
A pair of indices (P, Q), where 0 ≤ P < Q < N, is said to have adjacent values if no value
in the array lies strictly between values A[P] and A[Q].
For example, in array A such that:
A[0] = 0 A[1] = 3 A[2] = 3
A[3] = 7 A[4] = 5 A[5] = 3
A[6] = 11 A[7] = 1
the following pairs of indices have adjacent values:
(0, 7), (1, 2), (1, 4),
(1, 5), (1, 7), (2, 4),
(2, 5), (2, 7), (3, 4),
(3, 6), (4, 5), (5, 7).
For example, indices 4 and 5 have adjacent values because there is no value in array A that lies
strictly between A[4] = 5 and A[5] = 3; the only such value could be the number 4,
and it is not present in the array.
Write a function that returns number of adjacent values
</code>```

My solution was as follows:

For each pair, check whether there is any other element that is within this range

If not, increment adjacentPair count

Else, proceed to another pair.

This approach takes O(N^3). I wanted to know if there is a better way of solving this?

答:
The input array that you have is:

```<code>0, 3, 3, 7, 5, 3, 11, 1
</code>```

Imagine that the array instead would be this:

```<code>0, 1, 3, 3, 3, 5, 7, 11
</code>```

If the array were organized like that, then you could loop through the array and more easily count pairs.

```<code>0 --> 1
1 --> 3, 3, 3
3 --> 3, 3, 5
3 --> 3, 5
3 --> 5
5 --> 7
7 --> 11
</code>```

That's 1 + 3 + 3 + 2 + 1 + 1 + 1 = 12 pairs. The same number as you found before. Coincidence? I think not.

Now if there just was a way to re-order the array to make it look like this.... Oh, I know!

Time complexity? O(n) for the looping and counting pairs in the sorted array, and O(n log n) for sorting the array. So O(n log n + n) = O(n log n)

Title: Compute Adjacent Pair

Body:
The input array that you have is:

0, 3, 3, 7, 5, 3, 11, 1

Imagine that the array instead would be this:

0, 1, 3, 3, 3, 5, 7, 11

If the array were organized like that, then you could loop through the array and more easily count pairs.

0 --> 1
1 --> 3, 3, 3
3 --> 3, 3, 5
3 --> 3, 5
3 --> 5
5 --> 7
7 --> 11

That's 1 + 3 + 3 + 2 + 1 + 1 + 1 = 12 pairs. The same number as you found before. Coincidence? I think not.

Now if there just was a way to re-order the array to make it look like this.... Oh, I know!

Time complexity? O(n) for the looping and counting pairs in the sorted array, and O(n log n) for sorting the array. So O(n log n + n) = O(n log n)


答:
Based on the data you provided I would say this could be made to work both ways.

However, since you started off with MongoDB, I will highlight that:

First of all, I think you are starting off on the wrong premise: you are trying to cut down on the reads to the database. But MongoDB is designed for fast access to large amounts of data, that's why and when you would use it.

If you were talking about trying to reduce 40 reads to 5 reads that would be one thing. But from what I can tell you are cutting down 2 reads to 1 read. If your MongoDB cannot handle 2 reads per user request, you are doing something wrong. Review your indexes.

And if you actually get too much traffic, you can always add another server to the replica set or shard the collections.

So, I would simply store the admins in one collections and the forms in another. Duplicating data is never good and with the non-transactional nature of MongoDB you are liable to run into them not matching up in some cases.

In order to efficiently be able to cross reference both of these collections, you could set-up your schema like this:

Admins

```<code>{
   "_id" : 12345
   "name" : "Joe"
   "formIds" : [
      1234,
      5678
      9123
   ]
}
</code>```

Forms

```<code>{
   "_id" : 1234,
   "field1" : "bla",
   "field2" : "bla"
   "adminId" : 12345
}
</code>```

This way you can create indexes and lookup the admin by the formId and the form by the adminId. You could also only use one of the methods of cross reference - whichever suits your access patterns better.

Note: Now, we wound up basically with a relational database schema, just executed in MongoDB. And thus it won't make a big difference.

So where MongoDB would come in handy is, if you have forms, that have variable fields or change over time or forms that have nested data, all of which would require a complex schema on MySQL.

Title: What is better for scalability for this specific dataset, MongoDB or MySQL?

Body:
I have a web app which has users, forms, and volunteers signed up on those forms.

Currently I am using MongoDB and have it setup with a collection for admins, and a collection for forms with volunteers attached to the forms.

It is not very efficient because I have to render the forms on two pages, so I have form data attached to admins in the user collection, but repeated in the form collection so they can be rendered individually on the form page.

Currently I have one page which needs to render admins and forms, and then the form page which just renders a single form. I am trying to minimize queries, which is why I copied form data to the user objects (admin info is also attached to the form, keeping it to one query for each page).

Volunteer information is attached to the forms, so it is copied in both collections. Obviously this is a terrible waste of space. I'm hoping someone can help me re-design this and recommend whether to stick with NoSQL or move to MySQL/Postgres.

I do not have enough experience to know which is better for this specific setup, or how to set the schemas/architecture to be scalable.

Thank you very much for your time. Any advice is appreciated, including relevant resources that I clearly do not know about.

Body:
Based on the data you provided I would say this could be made to work both ways.

However, since you started off with MongoDB, I will highlight that:

First of all, I think you are starting off on the wrong premise: you are trying to cut down on the reads to the database. But MongoDB is designed for fast access to large amounts of data, that's why and when you would use it.

If you were talking about trying to reduce 40 reads to 5 reads that would be one thing. But from what I can tell you are cutting down 2 reads to 1 read. If your MongoDB cannot handle 2 reads per user request, you are doing something wrong. Review your indexes.

And if you actually get too much traffic, you can always add another server to the replica set or shard the collections.

So, I would simply store the admins in one collections and the forms in another. Duplicating data is never good and with the non-transactional nature of MongoDB you are liable to run into them not matching up in some cases.

In order to efficiently be able to cross reference both of these collections, you could set-up your schema like this:

Admins

{
   "_id" : 12345
   "name" : "Joe"
   "formIds" : [
      1234,
      5678
      9123
   ]
}

Forms

{
   "_id" : 1234,
   "field1" : "bla",
   "field2" : "bla"
   "adminId" : 12345
}

This way you can create indexes and lookup the admin by the formId and the form by the adminId. You could also only use one of the methods of cross reference - whichever suits your access patterns better.

Note: Now, we wound up basically with a relational database schema, just executed in MongoDB. And thus it won't make a big difference.

So where MongoDB would come in handy is, if you have forms, that have variable fields or change over time or forms that have nested data, all of which would require a complex schema on MySQL.


问:
Paravirtualization and process virtualization: with or without hardware support?
In Tanenbaum's Modern Operating Systems, fourth edition, about virtualization:

Are Virtualization without HW support, Virtualization with HW support, Paravirtualization, and Process virtualization exclusive between each other? (The way how the table is constructed seems to imply that.)

But I guess the first two are exclusive to each other, but each may overlap with the latter two (but I am not sure)?

How shall we understand the difference and relation between the four? Thanks.

答:
Paravirtualization means that the virtualized system knows that it is being virtualized and thus behaves differently than it would on real hardware, e.g. calling into the hypervisor instead of using some emulated device.

This is completely orthogonal to whether or not the (para-)virtualization is assisted by hardware. For example, Hyper-V with a normal guest is hardware-accelerated virtualization, Hyper-V with an "enlightened" guest is hardware-assisted paravirtualization.

Personally, I would not call Wine a virtualizer. Wine is an emulator. A virtualizer virtualizes something which is there, an emulator emulates something which is not there. Wine emulates the Windows ABI and API on Unix, where it does not exist. In fact, Wine orginally stood for "Windows Emulator", the meaning was later changed to "Wine is not an emulator" to highlight the fact that it does not emulate the x86 ISA (unlike QEmu, for example), but it obviously still does emulate the Windows ABI and API.


答:
In practice it is a good idea to wait until you have at least two concrete implementations before you abstract them into an Interface or Abstract Class.  Trying to "abstract" from a single implementation is unnecessary, and, even worse, it is almost certain to be wrong or incomplete because you would miss something.

For example, imagine that your first Mammal you implement is a Dog.  Create IMammal.  How well will IMammal work for a Bat, a Whale, and a Kangaroo?

Title: Should POJOs be abstracted?

Body:
My coworker tends to have each POJO implement an interface.
Like Customer would implement ICustomer, with the motivation that we can now have multiple implementations of ICustomer. One example would be a JPA annotated JpaCustomer with the motivation that now we're not tied to JPA. It seems like overkill to me to abstract it that much. What are your opinion on this? Is this common?</p>


答:
As other answers have said, you can write static methods that construct an object. This gets round the lack of named constructors in Java (and many other languages. Delphi does support named constructors). You can play with the types and order of parameters but this can lead to unclear and fragile code.

For instance, we could invent a scenario where your object can be constructed from an XML string or a JSON string. You could write methods like:

```<code>static MyObject createFromXml(String xml);
static MyObject createFromJson(String json);
</code>```

I've used this very occasionally as an alternative to a parameterless constructor with named initialisation methods:

```<code>MyObject myObject = new MyObject();
myObject.loadXml(xml).
</code>```

You could look upon a static create method as implementing the builder pattern inside your class.

Title: Working with static constructor in Java

Body: I didn't get a complete understanding of static constructors in Java. If it is allowed, why it is allowed? In what scenarios would you use it? What purpose would it serve? Can someone give me a simple example please?</p>

Body:
As other answers have said, you can write static methods that construct an object. This gets round the lack of named constructors in Java (and many other languages. Delphi does support named constructors). You can play with the types and order of parameters but this can lead to unclear and fragile code.

For instance, we could invent a scenario where your object can be constructed from an XML string or a JSON string. You could write methods like:

static MyObject createFromXml(String xml);
static MyObject createFromJson(String json);

I've used this very occasionally as an alternative to a parameterless constructor with named initialisation methods:

MyObject myObject = new MyObject();
myObject.loadXml(xml).

You could look upon a static create method as implementing the builder pattern inside your class.