答:
Interesting. In Delphi you can declare variables as threadvar which ensures that every thread has its own copy. However, these are global vars and thus have their drawbacks. So a colleague came up with "thread-stance" data. Data that is both thread and instance specific. Very similar to your option 2. It worked and works beautifully.

Given the choice today, I would go for option 1.

While option 2 may make things completely transparent for your fellow developers, I don't think that is necessarily a good thing. It comes at the cost of obscuring the "thread-dependent" nature of that class. Something a developer should always be aware of.

Option 1 makes everything much more explicit, and me, I like explicit.


问:
Threads: the difference of concurrency between many-to-one model and one-to-one model
I am studying "Threads" part with a textbook, Operating system concepts written by Abraham Silberschatz, Peter, Greg.

First, I'm going to say something in the textbook related to my question, and then to ask the question. If someone already knows the following theory, skip to my question, please.

The book defined parallelism and concurrency like the following:

Concurrency supports more than one task making progress.

Concurrent execution on single-core system:

Parallelism implies a system can perform more than one task simultaneously.

Parallelism on a multi-core system:

Many-to-one model: true concurrency is not gained because kernel can schedule only one thread at a time.

One-to-one model: provides more concurrency than many-to-one model."

My question is why concurrency is not gained in many-to-one model and why one-to-one model provides more concurrency than many-to-one model.

I think that many-to-one model's performance is not gained, but I think concurrency is 4 times greater than single thread. In addition, one-to-one model provides 4 times more concurrency than single thread (same as many-to-one model). Moreover, parallelism is 4 times better than many-to-one model in multi-processor architectures.

My conclusion is the textbook wrote wrongly. So it should be changed like the following

Many-to-one model: concurrency is improved up to the number of user threads, but performance is not gained because kernel can schedule only one thread at a time.

One-to-one model: concurrency is improved up to the number of user threads, and performance is also improved up to the number of processors.

Is my thought right or wrong? Thank you for reading.

答:
Your textbook isn't wrong, but it is using the term 'concurrency' a bit loosely at times.

Concurrency means that there is the appearance that multiple tasks are being done at the same time.

True concurrency  means that multiple tasks are actually been done at the same time. This is also referred to as Parallelism. Your textbook appears to be using these terms interchangeably, which isn't wrong but can be misleading if you overlook the word 'true'.

In the many-to-one model, you get concurrency (the appearance that tasks run at the same time) but you can't get parallelism. There is only one kernel thread and that can't be spread over multiple processors.

In the on-to-one model, each user thread has a corresponding kernel thread, which gives the kernel more options to provide concurrency or even parallelism.

ContentLicense: CC BY-SA 3.0


问:
How can we only include ready-to-be-released features in our production releases every other week?
I'm a software developer on a fairly large agile team (we have eight developers actively making changes to a single code repository).  Every two weeks, we push a new version of our software to production.  Here's our current workflow:

When starting a new task, developers create a "feature branch" off of the main development branch (we use git) and work off this new branch

Once a developer has finished work on their task, they merge their feature branch back into the development branch

The developer merges the development branch into the QA branch.

A build is triggered off the QA branch.  The output of this build is deployed into our QA environment to allow the testers to begin their testing.

It's quite common for our testers to find issues with these new features that have been merged into the QA branch.  This means that at any given time, the QA environment likely contains several new features - some tested and bug-free, and some broken.  This makes releasing difficult because it's rare that the QA build is in a production-ready state.

To mitigate this, we've been trying to initiate a "QA freeze" which means developers don't merge our development branch into the QA branch a couple days before the release.  Bug fixes to the QA environment are made directly on the QA branch and merged down to the development branch.  Theoretically, this keeps new, broken features out of QA while still allowing us to fix issues already in QA.

While this "QA freeze" concept has been partially successful, it's hard to coordinate and people are often confused about whether they are allowed to merge to QA.  It's also been hard to set a "QA freeze" deadline - everyone likes the idea of some breathing room in between the freeze and the release, but in practice, they'd rather have their feature in the next release than respect the deadline.

Is there a better way to ensure that we have a clean build for our releases every other week?

答:
There are a few problems floating around in this that are causing issues that you are experiencing.

The first is the long running QA branch.  Having a long running branch that is parallel to the development mainline may as a source of confusion because there are different efforts that need to be replicated in both the QA branch and the mainline.  This means that either you are checking in fixes to the QA branch that need to be merged to the mainline (not a bad thing), or you are checking in to the mainline that gets merged into the QA branch (a source of possible bugs).

The other problem with the long running parallel branch is that it is possible for files to become perpetually out of sync. A code fix that never gets merged back, or a configuration needed for production builds that is never tested and part of the development mainline.

Next, you've got roles that are getting impinged on. This means that the packaging role (more on this later) is not getting sufficiently isolated.

In the git-flow model, the release branch is branched from development (not development merged to QA) and all fixes are checked into the release branch and then merged back to the development branch.

Some of the philosophy of branching can be found in Advanced SCM Branching Strategies (I consider to be an excellent read).  This focuses on the roles that each branch may take on.  The release branch takes on the packing role.

The packaging role is often confused with the accumulation or, more commonly, mainline roles. Once the intended development and maintenance have been performed and any accumulation has been done, it is time to prepare the code for release. Such an effort may not be trivial, requiring a team of release engineers and additional fixes beyond those already performed. The policy on a packaging branch is significantly different from that on a maintenance branch, as the packaging role suggests, only the changes necessary to make the product releasable should be addressed.

Branch from the development point to the release branch. The release branch that QA builds from gets one branch and no merges from development.

If you want to go down that road, with consistent naming and hooks, it is possible to prevent a merge from being done into a release branch.

Fix everything that needs to be fixed in the release branch and merge those changes back to the mainline.

At the end of the release effort, merge the release branch into the "releases go here" branch and tag it as such.

Some sites don't have a "releases go here" branch and just leave the end of the release branch dangling with a tag.

One should seriously consider applying the entirety of git-flow in place. This isn't too far from what is being done currently and puts some discipline and consistency into what each branch means and how each branch interacts with others.


答:
The problem seems to be to me that you have a single QA branch.

For each release, make a separate QA branch from the primary development trunk/master. Then merge in only fixes for bugs for features on that branch - never new features. Have QA test that branch.

This way, the "freeze" is quite evident- it's in the branch name. You could use something like, I dunno, release/26/10/2015. Then it's obvious that nobody should be merging in new features after this.

It's especially helpful if you don't even fork the branch until the freeze. People can merge in to master at any time, it just won't be part of this release if it's not done in time for it to be tested.

Do not have a single long-running QA branch, that's just begging for trouble. Fork from the main development branch for each release and QA that branch.

Title: How can we only include ready-to-be-released features in our production releases every other week?

Body:
I'm a software developer on a fairly large agile team (we have eight developers actively making changes to a single code repository).  Every two weeks, we push a new version of our software to production.  Here's our current workflow:

When starting a new task, developers create a "feature branch" off of the main development branch (we use git) and work off this new branch

Once a developer has finished work on their task, they merge their feature branch back into the development branch

The developer merges the development branch into the QA branch.

A build is triggered off the QA branch.  The output of this build is deployed into our QA environment to allow the testers to begin their testing.

It's quite common for our testers to find issues with these new features that have been merged into the QA branch.  This means that at any given time, the QA environment likely contains several new features - some tested and bug-free, and some broken.  This makes releasing difficult because it's rare that the QA build is in a production-ready state.

To mitigate this, we've been trying to initiate a "QA freeze" which means developers don't merge our development branch into the QA branch a couple days before the release.  Bug fixes to the QA environment are made directly on the QA branch and merged down to the development branch.  Theoretically, this keeps new, broken features out of QA while still allowing us to fix issues already in QA.

While this "QA freeze" concept has been partially successful, it's hard to coordinate and people are often confused about whether they are allowed to merge to QA.  It's also been hard to set a "QA freeze" deadline - everyone likes the idea of some breathing room in between the freeze and the release, but in practice, they'd rather have their feature in the next release than respect the deadline.

Is there a better way to ensure that we have a clean build for our releases every other week?


问:
Exposing nodes in a generic binary search tree implementation to visitor pattern
It's common to implement binary search trees with an internal Node class

```<code>public class BinarySearchTree<TKey, TVal>
{
    class Node
    {
        public readonly TKey Key;
        public readonly TVal Val;

        public Node Left, Right;

        public Node(TKey key, TVal val, Node left = null, Node right = null)
        {
            Key = key; Val = val; Left = left; Right = right;
        }
    }

    private Node treeRoot;
}
</code>```

This is nice because it hides client code from being able to directly modify the tree.

It might be the case, however, that we want to expose traversal of the tree (e.g. for printing). In this sense, it might make sense to pull the Node class out of BinarySearchTree, and redesign Node to use the visitor design pattern.

```<code>interface ITreeVisitor<TKey, TVal>
{
    void Visit(Node<TKey, TVal> node);
}

class InOrderTreeVisitor<TKey, TVal> : ITreeVisitor<TKey, TVal>
{
    public void Visit(Node<TKey, TVal> node)
    {
        if (node == null) return;

        node.Left.Accept(this);
        // do something to node
        node.Right.Accept(this);
    }
}

public class Node<TKey, TVal>
{
    public Node<TKey, TVal> Left
    {
        get;
        internal set;
    }

    public Node<TKey, TVal> Right
    {
        get;
        internal set;
    }

    public readonly TKey Key;
    public readonly TVal Val;

    public Node(TKey key, TVal val, Node<TKey, TVal> left = null, Node<TKey, TVal> right = null)
    {
        Key = key; Val = val; Left = left; Right = right;
    }

    public void Accept(ITreeVisitor<TKey, TVal> v)
    {
        v.Visit(this);
    }
}

public class BinarySearchTree<TKey, TVal>
{
    public Node<TKey, TVal> Root
    {
        get;
        private set;
    }
}
</code>```

The trouble with this is that the visitors have to be generic. This doesn't really make sense. A visitor isn't a container, and doesn't really need to know anything about keys or values.

Is there any way to make ITreeVisitor non-generic?

答:
In your case the visitor does not need to be concerned with the generic type because it is dealing directly with the node and not invoking any type-specific logic (i.e. ToString() should be sufficient).

You have two options:

Stick with a generic type and use the proper key and value types each time you create your visitor object.

Create a second visitor interface and implementation that are non-generic. You would then inherit from one or the other depending on whether the specific visitor deals with node's data or just the node.

The tradeoff is being more verbose when creating objects, or being more verbose with redundant interfaces.


答: Override the ToString() method in your Node class, and then use a non-generic Visitor to gather the results of calling ToString() on each Node.

Title: Exposing nodes in a generic binary search tree implementation to visitor pattern

Body:
It's common to implement binary search trees with an internal Node class

```<code>public class BinarySearchTree<TKey, TVal>
{
    class Node
    {
        public readonly TKey Key;
        public readonly TVal Val;

        public Node Left, Right;

        public Node(TKey key, TVal val, Node left = null, Node right = null)
        {
            Key = key; Val = val; Left = left; Right = right;
        }
    }

    private Node treeRoot;
}
</code>```

This is nice because it hides client code from being able to directly modify the tree.

It might be the case, however, that we want to expose traversal of the tree (e.g. for printing). In this sense, it might make sense to pull the Node class out of BinarySearchTree, and redesign Node to use the visitor design pattern.

```<code>interface ITreeVisitor<TKey, TVal>
{
    void Visit(Node<TKey, TVal> node);
}

class InOrderTreeVisitor<TKey, TVal> : ITreeVisitor<TKey, TVal>
{
    public void Visit(Node<TKey, TVal> node)
    {
        if (node == null) return;

        node.Left.Accept(this);
        // do something to node
        node.Right.Accept(this);
    }
}

public class Node<TKey, TVal>
{
    public Node<TKey, TVal> Left
    {
        get;
        internal set;
    }

    public Node<TKey, TVal> Right
    {
        get;
        internal set;
    }

    public readonly TKey Key;
    public readonly TVal Val;

    public Node(TKey key, TVal val, Node<TKey, TVal> left = null, Node<TKey, TVal> right = null)
    {
        Key = key; Val = val; Left = left; Right = right;
    }

    public void Accept(ITreeVisitor<TKey, TVal> v)
    {
        v.Visit(this);
    }
}

public class BinarySearchTree<TKey, TVal>
{
    public Node<TKey, TVal> Root
    {
        get;
        private set;
    }
}
</code>```

The trouble with this is that the visitors have to be generic. This doesn't really make sense. A visitor isn't a container, and doesn't really need to know anything about keys or values.

Is there any way to make ITreeVisitor non-generic?


问:
How to deal with long running transactions?
I'm developing a Content Management System (CMS) and I would like to include a "Save Changes" button. I mean: a user performs several changes in the database, but those changes are still not available. Just when the user presses the "Save Changes" button, those changes are "visible" for the website.

I have thinking in "SQL transactions". But I have understood that "SQL transaction" were designed to be used in a short space of time. And in this particular case the user may keep the transaction open for some time (one hour, two hours...).

How can deal with this kind of issues? I'm using PHP and MySQL?

答:
If you're storing a history of changes (drafts) with a flag to mark the publicly viewable state then your submit changes button can just set all the state on the page to be the publicly viewable state. You can use a transaction for this since it would serialize all the changes. This is especially useful if you implement a system for rolling back such state changes to previous configurations.

A more verbose explanation would be that if you had tables like:

articles(id, url)

article_titles(id, article, text, timestamp)

article_body(id, article, text, timestamp)

article_history(id, article, title, body, timestamp)

Then when the title is changed it just inserts a new record. When the body is changed or saved periodically it just inserts a new body record. Now when you hit publish it inserts into article_history and when displaying publicly to the user the renderer grabs the most recent article_history record and the corresponding title and body.

(Note, this is just an example to try to relate to what you described. I'm not saying this is a correct design for a CMS or good practice).


问:
Can I check the existence of an annotation in an unit test?
I have a java class hierarchy that are formed by an Abstract class and N extensions of it.
In the abstract class I have a method that is annotated with a @Remove annotation. While we won't get any exceptions of won't fail fast if this annotation is removed, we may get out of memory exceptions, so I would like to be sure that we notice as fast as possible if this annotation disappears in some refactoring.

I am trying to create GUTS (good unit tests), so I thought I could document this "technical requirement" in my tests, with a test case that states it.

But this is not a feature, it as an implementation detail and it is not linked to the behavior of the method (the method could be empty, but it has to exist and has to be annotated).

Is it ok to create a test for that or is there any other way to check the existence of this annotation?

答: When a critical function is implemented using a declarative technique like this, I tend to prefer using an integration test that includes the part of the framework that recognises the declaration. This protects you from changes in the frameworks behaviour, misunderstandings of the effect of the declaration, and so on. Simply testing the presence of the annotation does not guarantee any specific behaviour.</p>


问:
develop crossplatform GUI based DESKTOP application with HTML5/CSS
I'm experienced wed developer doing stuff for web for a several years. But now my customer need to build crossplatform ETL tool which he want to ship to his clients. And will be much easier if it will be desktop application.

However I don't have good expertize in this field and in general don't feel great about desktop approach used in WinForms(or similar technologies) with button handlers, etc.

So in mobile application it's whole bunch of tools which allow developers write mobile app with HTML5/CSS like Apache Cordova for example.

Is there is something similar for desktop applications? If yes, does gui based on that still have similar response time as normal desktop apps?

答:
Yeah there are a lot of cross-platform applications written using HTML5. You'll often see them using containers like nw.js, Electron, or others. They run node.js generally and you can use npm just like you might be familiar with on the server. This also allows you to access the filesystem, networking, and many other OS features in a cross-platform way.

Depends a lot on your requirements though. Just like with the web you'd need a UI framework that fits your client's goals.

Does gui based on that still have similar response time as normal desktop apps

From my experience, since they all use Blink, the performance is comparable to Windows Forms/WPF.


问:
Better To Call In Dive Into Submethods Or Pass Around a result

I have a service that does fairly complicated business logic when it receives a request. I have most the functionality isolated into private methods which dive a couple levels down from the method that receives the request. Basically receive request -> private method for subprocessing -> private method for processing different action -> method that creates a result -> method that verifies result.

I can either call each of these methods sequentially and pass around the various results between each private method or I can call one method from inside of the next method and keep passing along the data between steps the other way

//either passing around as returns or class variables
public onRequest(Request request){
        method1(request) // Returns two things for method 2
        method2(thing1, thing2) //Modifies and thing1 and thing2
        method3(thing1Mod, thing2Mod) //Returns a result
        verify(result)
        return result
}
```

<p>Option 2</p>

<pre class="lang-java prettyprint-override"><code>public onRequest(Request request{
    Result result = method1(request)
}

method1(request){
    //logic that makes thing1 thing2
    return method2(thing1, thing2)
}

method2 (thing1, thing2)
    //logic to modify thing1 and thing2
    return method3(thing1, thing2)

method3 (thing1, thing2) {
    //logic that gets a result from thing1, thing2
    verify(result)
    return result
}
</code>```

Each method contains discrete functionality.

The reason I am concerned is that I am trying to write test cases and I want to only leave onRequest public but I still wanna test methods 1-3 and verify individually.

Project is in Java

答:
Its the wrong question

Of course you should "pass around a result." Not only the points @Ewan makes about testing, but passing parameters makes code more maintainable generally. And as a bonus you can say "I'm using dependency injection." ooohhh.

The above says nothing about the code structure!

... or I can call one method from inside of the next method and keep passing along the data between steps the other way

You need to decide which steps - the afore mentioned methods - are co-equal, sequential steps of a given process and which truly are sub-steps of their containing method. This gives your program a foundational structure. It essentially defines the processing layers, and I promise you, has an effect on how the program is understood, hence where change should be made, and how the code evolves in the long run.

Encapsulation and Testability

Ideally a layer (one method or a hierarchy of methods) will not expose its guts to the outside, and parameters helps in this regard.

As for testability, sometimes my test class will inherit the class I'm testing and then I can test protected methods. Which means I rarely make methods private just for that reason.

And sometimes it is ok to simply infer the correctness of inner methods - select test parameter values carefully.

And finally, I'll be honest here - I've made inner methods public for testing purposes - because code structure/design comes first.


问:
Objects with boolean data type
I have a collection of objects, and for each of them I need to know if a specific condition has been met. That is a ternary condition, it could be not yet tested, tested and failed, or tested and passed. Currently I have a map where the objects are keys, and the values are Booleans. The value is null until tested, and true or false thereafter. However, while the objects should never change during this process, they are not immutable and could theoretically change. I feel like there must be a better way to implement this, but I don't know what it is. Any ideas?

答: You can use Collections.unmodifiableMap(myMap); to return an immutable view of your map, but I'm not sure how this would fit into your current code - you can't add new objects to an unmodifiable map.

Title: Objects with boolean data type


答:
You have several options:

Rather than using Boolean in your current code, create an enum with values UNTESTED, PASSED, and FAILED. That is more descriptive than a ternary Boolean value. Enumerations have advantages beyond readability, such as being able to add methods to do stuff.

If the test is computationally inexpensive, simply add a method on the object being tested to return the test result. If the test is computationally expensive and the method to do the test may be called a lot this may do more harm than good.

Store the test result on the object itself. If any of the test inputs change, the object can blank out the test result, effectively invalidating the test result.

In all cases I would still apply the change in option 1. You really should be using a descriptive enumeration rather than a Boolean.

See Also

Why use a bool over more domain specific abstractions - this question talks about the tradeoffs of a primitive vs. enum. Since you effectively have three options, this backs up my assertion of using an enum.

Title: Objects with boolean data type

Body: I have a collection of objects, and for each of them I need to know if a specific condition has been met. That is a ternary condition, it could be not yet tested, tested and failed, or tested and passed. Currently I have a map where the objects are keys, and the values are Booleans. The value is null until tested, and true or false thereafter. However, while the objects should never change during this process, they are not immutable and could theoretically change. I feel like there must be a better way to implement this, but I don't know what it is. Any ideas?


问:
What's a schrödinbug?
This wiki page tells :

A schrödinbug is a bug that manifests only after someone reading
  source code or using the program in an unusual way notices that it
  never should have worked in the first place, at which point the
  program promptly stops working for everybody until fixed. The Jargon
  File adds: "Though... this sounds impossible, it happens; some
  programs have harbored latent schrödinbugs for years."

What is being talked about is very vague..

Can someone provide an example of how a schrödinbug is like (like with a fictional / real-life situation)?

答:
I've seen a few Schödinbugs and always for the same reason:

Company policy required that everyone was supposed to use a program.

Nobody really used it (mostly because there was no training for it.)

But they couldn't tell management this. So everyone had to say "I've been using this program for 2 years and never encountered this bug until today."

The program never really worked, except for a minority of users (including the developers who wrote it.)

In one case, the program had been subject to plenty of testing, but not on the real database (which was deemed too sensitive, so a fake version was used.)

Title: What's a schrödinbug?


问:
Dealing with unreliable data source
I have been assigned the task of automating entering of supplier prices and inventory based on our master google sheet.

I have limited programming knowledge, but so far I have made code that can create an order sheet and send it via E-mail.

The problem I'm facing now is that the prices are based on pdf/xlsx files we receive from our suppliers, and each file has its own way of naming the same item, not to mention the format.

Right now I'm having to manually convert pdf tables to excel, then copy the data into a google sheet, then run a code I made for each supplier that searches and copy the price to the proper location on our spreadsheet. It's definitely not optimal but still a lot quicker than hand typing them in.

Is there a better way to update the prices?

答:
First, I would try to ask your suppliers if they are able to send you the data in a standardized, machine-readable format. An Excel sheet may be fine as long as you can identify the columns correctly. There are dozens of ways to automate the reading of data from Excel sheets, so that should be a good starting point for automatization. Note that your suppliers will most probably generate their price table PDFs from a spreadsheet document by themselves, so I guess most of them could you send the data in a better format if they just want to.

If your suppliers do not cooperate and insist on sending you PDFs , someone has to do the hard work and convert the PDFs into a spreadsheet (again). OCR software might be of use here, but that still will be a semi-automatic process.

Title: Dealing with unreliable data source


问:
C# Abstract math classes from libraries
I'm currently writing a library that abstracts 3D rendering and uses SharpDX and OpenTK as graphics libraries. The problem is that OpenTK and SharpDX have their own implementations of Vector2, Matrix, Quaternion and so on.

I came up with 3 possible ways to deal with this.

My API has to have function overloads for both math types. If I want to extend the basic rendering code with more higher level features (like a Transform class that handles position, rotation and scale) I need to either favor one over the other or provide code for both math types which is not optimal.

Roll my own math type that allows conversions between the SharpDX and OpenTK types. Not optimal either since the math code was already written twice I shouldn't invent the wheel again.

Flat out use only one on the API level and convert only if needed. With this approach I would bind myself to one library which means if I only ever want to use the OpenTK renderer but the API is using the SharpDX math types I still need to have the SharpDX library around without ever using the "graphics" part of it.

I feel like option 2. would result in the nicest usage code but is the most work required. I'm looking for possible solutions to this problem other then the 3 options I have mentioned above.

答:
You could implement your "higher level features" in terms of abstract interfaces like IVector2, IMatrix, IQuaternion, and maybe some abstract factories like IVector2Factory. Then you provide two adapters for each of that interfaces one based on SharpDX types, and one on OpenTK types. That way, you do not bind your new classes to the one or the other library.

Of course, on some level you have to make a decision which of the two libs or adapters you are going to use in your final program.

Title: C# Abstract math classes from libraries


答:
You could use yet another vector library, instead of writing your own. Then convert to the library specific representations where needed.

Microsoft is working on an implementation called System.Numerics.Vectors which can even get SIMD acceleration.

Title: C# Abstract math classes from libraries

Body:
I'm currently writing a library that abstracts 3D rendering and uses SharpDX and OpenTK as graphics libraries. The problem is that OpenTK and SharpDX have their own implementations of Vector2, Matrix, Quaternion and so on.

I came up with 3 possible ways to deal with this.

My API has to have function overloads for both math types. If I want to extend the basic rendering code with more higher level features (like a Transform class that handles position, rotation and scale) I need to either favor one over the other or provide code for both math types which is not optimal.

Roll my own math type that allows conversions between the SharpDX and OpenTK types. Not optimal either since the math code was already written twice I shouldn't invent the wheel again.

Flat out use only one on the API level and convert only if needed. With this approach I would bind myself to one library which means if I only ever want to use the OpenTK renderer but the API is using the SharpDX math types I still need to have the SharpDX library around without ever using the "graphics" part of it.

I feel like option 2. would result in the nicest usage code but is the most work required. I'm looking for possible solutions to this problem other then the 3 options I have mentioned above.


问:
What is the difference between a function and a component?
I just listened to Software engineering Radio podcast on components. Their description of components were very vague, they made them sound like lower level versions of functions. I am trying to figure out what components mean in the context of the composite pattern.

What is the difference in purpose between a function and a component?

What does a component have to do with the composite pattern?

Can you describe what a component is by using a funny metaphor? For example, explain how  creating a component like baking an apple pie.

答:
I think, in a nutshell:

A component has state information.

like:

controls

connection classes

A function doesn't have state information.

like:

matrix calculations

string parsers


问:
What are the drawbacks of Python?
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)

答:
I hate that Python can’t distinguish between declaration and usage of a variable. You don’t need static typing to make that happen. It would just be nice to have a way to say “this is a variable that I deliberately declare, and I intend to introduce a new name, this is not a typo”.

Furthermore, I usually use Python variables in a write-once style, that is, I treat variables as being immutable and don’t modify them after their first assignment. Thanks to features such as list comprehension, this is actually incredibly easy and makes the code flow more easy to follow.

However, I can’t document that fact. Nothing in Python prevents me form overwriting or reusing variables.

In summary, I’d like to have two keywords in the language: var and let. If I write to a variable not declared by either of those, Python should raise an error. Furthermore, let declares variables as read-only, while var variables are “normal”.

Consider this example:

```<code>x = 42    # Error: Variable `x` undeclared

var x = 1 # OK: Declares `x` and assigns a value.
x = 42    # OK: `x` is declared and mutable.

var x = 2 # Error: Redeclaration of existing variable `x`

let y     # Error: Declaration of read-only variable `y` without value
let y = 5 # OK: Declares `y` as read-only and assigns a value.

y = 23    # Error: Variable `y` is read-only
</code>```

Notice that the types are still implicit (but let variables are for all intents and purposes statically typed since they cannot be rebound to a new value, while var variables may still be dynamically typed).

Finally, all method arguments should automatically be let, i.e. they should be read-only. There’s in general no good reason to modify a parameter, except for the following idiom:

```<code>def foo(bar = None):
    if bar == None: bar = [1, 2, 3]
</code>```

This could be replaced by a slightly different idiom:

```<code>def foo(bar = None):
    let mybar = bar or [1, 2, 3]
</code>```

Title: What are the drawbacks of Python?

Body:
I hate that Python can’t distinguish between declaration and usage of a variable. You don’t need static typing to make that happen. It would just be nice to have a way to say “this is a variable that I deliberately declare, and I intend to introduce a new name, this is not a typo”.

Furthermore, I usually use Python variables in a write-once style, that is, I treat variables as being immutable and don’t modify them after their first assignment. Thanks to features such as list comprehension, this is actually incredibly easy and makes the code flow more easy to follow.

However, I can’t document that fact. Nothing in Python prevents me form overwriting or reusing variables.

In summary, I’d like to have two keywords in the language: var and let. If I write to a variable not declared by either of those, Python should raise an error. Furthermore, let declares variables as read-only, while var variables are “normal”.

Consider this example:

x = 42    # Error: Variable `x` undeclared

var x = 1 # OK: Declares `x` and assigns a value.
x = 42    # OK: `x` is declared and mutable.

var x = 2 # Error: Redeclaration of existing variable `x`

let y     # Error: Declaration of read-only variable `y` without value
let y = 5 # OK: Declares `y` as read-only and assigns a value.

y = 23    # Error: Variable `y` is read-only

Notice that the types are still implicit (but let variables are for all intents and purposes statically typed since they cannot be rebound to a new value, while var variables may still be dynamically typed).

Finally, all method arguments should automatically be let, i.e. they should be read-only. There’s in general no good reason to modify a parameter, except for the following idiom:

def foo(bar = None):
    if bar == None: bar = [1, 2, 3]

This could be replaced by a slightly different idiom:

def foo(bar = None):
    let mybar = bar or [1, 2, 3]


问:
Speed up my delivery pipeline
I have a solution with many components with different deploy iter:

WebAPI backend (on IIS)

AngularJS frontend (on IIS)

A process manager (as Windows service)

A projection engine (as Windows service)

A command handler (as Windows service)

I develop all of this things. At the end of the day when something valuable is ready I need to push the updated component to the server (a local server) for testing. This usually means:

Build the component (remember to switch test/release environment)

Copy the bin

Open a remote desktop connection

Paste it on the server (after crossing the right path)

replace the old package (for IIS) OR reinstall the service

if the test succeds, redo this for a production environment.
How can I speed up this process, and go in the direction of one click deployment?
Can a tool like Vagrant be a good company?
I know that this question could produce descriptive and opinion based answers but I'm stuck!

答:
Firstly you need a continuous integration server - I recommend Jenkins, its really easy to manage and is very well designed.

Once you have that set up to automatically look at your repository for changes, check them out and build them you can start looking at automating the deployment (to the test environment) mechanism.

Generally this means copying the files, but as you have services, you'll have to (at least) stop them. So I would recommend writing a script to stop the services, copy the files from a 'package' of all the files that were built and then restart the services. This script can be just a simple batch file that uses sc.exe (or net stop). If you want to get slightly more complicated, use Wix to create a msi installer and run that on the remote server in an unattended (i.e. silent) mode to upgrade the deployed installation.

I found things like One-Click to be a pain in the butt, especially when dealing with deploying to different environments - i.e. whatever deployment method you use, you want to be able to run the exact same thing on both Test and Production in turn.

Title: Speed up my delivery pipeline


问:
Is it a good practice to run unit tests in version control hooks?
From the technical point of view it is possible to add some pre/post push hooks which will run unit tests before allowing some specific commit to be merged to remote default branch.

My question is - is it better to keep unit tests in build pipeline (thus, introducing broken commits to repo) or it's better just not to allow "bad" commits to happen.

I do realize that I'm not limited with this two options. For instance, I can allow all commits to branched and tests before pushing merge commit to repo. But if you have to choose between exactly this two solutions, which one you'll choose and for what exactly reasons?

答:
I prefer "passed unit tests" to be a gate for submitting code. However, to make that work, you will need a few things.

You will need a build framework that caches artefacts.

You will need a test framework that caches test status from (successful) test runs, with any given artefact(s).

That way, check-ins with passing unit tests will be quick (cross-check from the source to the artefact that was built when the developer checked the tests prior to check-in), those with failing unit tests will be blocked and developers who conveniently forget to check the builds prior to commit will be encouraged to remember doing so next time, because the compile-and-test cycle is lengthy.


答:
One very simple solution which I've seen work on a team a little larger than yours is to have everyone work and deploy from a single branch.

You say the team is agile but it's not clear if you're working in sprints (ie Scrum) or a more continuous flow (ie Kanban) approach. Assuming you are doing sprints the aim for the team is to have the code releasable at the end of each sprint, for your fortnightly release. There is no confusion as to whether one feature will break another as they have all been developed together. Testers may be able to get access to features in smaller chunks as the overhead on developers to deliver to them is lower. And you don't really need a QA-Freeze, instead everyone knows when the end of the sprint is and shouldn't take on work they can't finish, or leave in a deployable (ie disabled) state.

Obviously there are pros and cons to any approach, I present this as an option not necessarily the 'best way'.


问:
Lookup Tables: Are they a leak in the domain model?
You are building a system that keeps track of Companies. Those companies have Contacts. Those contacts are often specialists that only answer certain types of questions, such as Billing/Payment, Sales, Ordering, and Customer Support.

Using Domain Driven Design and an Onion Architecture, I've modeled this with the
following types:

Company

Has Contacts

Contact

Has Contact Types

ContactType (enum)

CompanyRepository (interface)

EFCompanyRepository (defined in an external assembly, uses EntityFramework, implements CompanyRepository)

Our team has a split opinion on how to model the database for this application.

Side A: The Lean DDDers:

It's the job of the Domain to define which ContactTypes are valid for a Contact. Adding a table to the database to validate that unknown ContactTypes are not saved is a sign of a leaky domain. It spreads logic too far out.

Adding a static table to the database and corresponding code is wasteful. In this application the database solves one problem: persist the thing and give it back to me. Writing an extra table and corresponding CRUD code is wasteful.

Changing the strategy for persistence should be as easy as possible. It is more likely to change that business rules. If I decide that SQL Server costs too much I don't want to have to rebuild all the validation I put in my schema.

Side B: The Traditionalists [that's probably not a fair name. The DBCentrists?]:

It's a bad idea to have data in the database that doesn't make sense without reading code. Reports and other consumers have to repeat the list of values themselves.

It's not that much code to load your db type dictionaries on demand. Don't worry about it.

If the source of this is code and not data I will have to deploy bits instead of a simple SQL script when it changes.

Neither side is right or wrong, but one of them is probably more efficient in the long run, counting development time for initial development, bugs, etc. Which side is it - or is there a better compromise? What do other teams writing this style of code do?

答:
I have found it best to store enums as their string representation in the database and not include a lookup table.

Obviously the downside to this is that it uses more disk space and is not normalised.

The plus side is that the field retains its meaning in the db, you dont end up with magic numbers corrosponding to the int value of the enum for example and you dont have to manage versioning a lookup table when the enum changes.

Not sure I would characterise this as a DDD vs Trad difference though. Its more a database-centralist vs code is best in my view


答:
The performance is not good, but is improving with pypy,

The GIL prevents the use of threading to speed up code, (although this is usually a premature optimization),

It's only useful for application programming,

But it has some great redeeming features:

It's perfect for RAD,

It's easy to interface with C (and for C to embed a python interpreter),

It's very readable,

It's easy to learn,

It's well documented,

Batteries really are included, it's standard library is huge and pypi contains modules for practically everything,

It has a healthy community.

Title: What are the drawbacks of Python?

Body:
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)

ContentLicense: CC BY-SA 2.5


问:
Are colons ok in a REST API?
I see many REST API examples with URIs like http://<whatever>/widgets or http://<whatever>/widget/123, for a specific thing. For most things I would just stick with the front slash, but when requesting a specific id I'd rather use a colon, like http://<whatever>/widget:123.

According to what I found here about best practices, there wasn't much about using the colon, specifically. It sounds like it's acceptable, but is it/what might be some pitfalls to using them instead of the slash?

Express.js seems fine with them (as far as code is concerned):

app.get('/widgets::id', function(req, res){ <...> });

Update: I just stumbled on this. It's sounding like colons are perfectly fine for this use.

答:
While it would in most cases work because you use the colon behind the first slashes, I would not advice to use it.
As you can see here the colon is a reserved token, it is being used to specify the port number just after the domain name (before any slashes). So using it might give you weird errors.

It is better to stick with either / or by using ?foo=1&bar=2.

Title: Are colons ok in a REST API?


问:
Am I overusing Inheritance or this is exactly what it is here for?
I have a class called BagItem and another class called EquipmentItem both classes are exact the same in methods, etc, with the exception of 1 property.

BagItem have:

```<code>public InventoryBagType BagType { get; private set; }
</code>```

EquipmentItem have:

```<code>public InventoryEquipmentType EquipmentType { get; private set; }
</code>```

I guess I should mention, BagItem refer to items that are in the character's bag while EquipmentItem I should have probably named it EquippedItem which refer to item currently equipped by the character.

From those 2 classes I have other classes that inherit from one or another.

Then from EquipmentItem for example I have CombatEquipmentItem which inherits from EquipmentItem and CombatEquipmentItem only have one extra property.

```<code>public CombatEquipmentType SlotType { get; private set; }
</code>```

At this point I don't know if CombatEquipmentItem will have or not more properties or methods, neither if either BagItem or EquipmentItem will either.

I was considering creating yet another class InventoryItem that would keep all the common entries from BagItem and EquipmentItem and they would inherit from it and by its turn CombatEquipmentItem from it.

Should I eliminate BagItem and EquipmentItem for InventoryItem and keep both the properties there and either set one or another as null based on the item and inherit anything else from it or should I move forward with yet another class or my design is bad from the begin and how it should have been written as?

答:
When I take an item from a bag and hold it in my hand (equipping it) ... do I change the type of the item? Do I change the properties of the item?

No, so this doesn't make sense in the real world (or a game, from the player's POV), which means you're not modelling anything in the problem domain.

Maybe we're modelling something in the solution domain instead? There are problems here too, though:

your BagItem doesn't know what kind of slot it can be equipped to. So how can you take something out of the bag and equip it?

why does your item need to know what sort of bag it's stored in anyway? Surely you know which actual bag it's in, because you found it somehow, presumably by looking in a bag. So, that information is already available in the context outside the item.

Summary: none of these types seem to be modelling anything useful, but they omit some things you clearly do need. Just use a single type and add features as you actually need them.


问:
Best freeware license for my closed-source application
I have no experience in software licensing so far. I am releasing my first application but I am not familiar with any licenses. Most of the the summeries found that I can understand (http://opensource.org/licenses/category) are open source but I want my application to stay closed-source. I am a little lost among all these choices.

My application:

uses a DLL created from a project version licensed under GNU LGPL (no code changes made)

uses a statically linked class licensed under "GNU GPL v2 or any later" (modified by adding a few properties (just getters, a couple of lines))

uses 2 small classes found in stackoverflow discussions which code was published under no license, I guess

implements a possibility to donate funds

I need a license that states:

It is free to use for everyone

Everyone can redistribute it on their repositories. I guess I want basic information about the author and my website included.

It is forbidden to modify and sell it in any way

The license does not obligate me to distribute the source code

The author gives no warranty

The author can change the license to one of a non-commercial license any time in the future (not required)

My questions:

What license matches the above statements? (provide a link to the body and the summery, please)

I am going to include information about third-party licensed code and its authors. Should I also mention authors of classes found at stackoverflow?

Have I modified the GNU GPL class enough to be obligated to release this modified class?

The project I use a DLL from changed the license from GNU LGPL to MIT in the newer version. Can I update this library used in my project with no influence on the license I choose?

Is it possible in the future to license this project under a non-commercial license combined with an implemented donating feature as well? Is it acceptable in the community or is it a bad manner? I've been just wondering if I can receive donations and ask non-commercial users at the same time to consider buying a commercial license, that's all. It is my thinking in case it gets attention from commercial users in the future very unlikely.

If a non-commercial license using LGPL, GPL or MIT components is possible, what would it be? (provide a link to the body and the summery, please).

EDIT (annotation to the users' replies) 2015-10-27 19:20

greyfade: Let's say I get permissions from stackoverflow users to use their classes freely following BartvanIngenSchenau's advice. I understand the only obstacle left for releasing under a closed-source freeware license would be GPL?

2.1. Do LGPL and MIT licensed components included in my app permit using closed-source freeware license too?

2.2. I cannot get rid of GPL licensed part in my project. Let's say I release my project under GPLv3 (obtained permissions for CC-BY-SA 3.0 licensed classes at stackoverflow, using the DLL under LGPL or MIT - whatever) and I distribute the source code beside the binaries. Did I understand correctly? GPL permits any form of collecting voluntary donations? I am not about to require a donation to download, install nor use my application, it is user's good will. Still no?

2.3. Am I obligated under GPLv3 to distribute the source code at the server or only at user X's individual request by sending it to him/her?

2.4. Let's imagine I get a permission from the author and GPL is converted to LGPL. My application's got third-party components under LGPL (MIT), LGPL, 2xLGPL. Is it all right then to license my app under a closed-source freeware license letting donations? If yes, what'd be this license? If no, what license would the components need to be released under to match my wishes?

答:
uses a statically linked class licensed under "GNU GPL v2 or any later" (modified by adding a few properties (just getters, a couple of lines))

By using a GPL licensed class/library your code must also be published under the GPL license.

See also: https://stackoverflow.com/questions/10130143/gpl-lgpl-and-static-linking#10179181

A note on your 2.:

In my opinion if there isn't a explicit license stated you must ask the original author for permission so you can use the code.


答:
You are out of luck.

The GPL license is written in such a way that if even the tiniest part of your code was provided to you under the GPL license, then you are required to use the GPL license as well when distributing your code.

Content posted on Stack Overflow is licensed under the CC-BY-SA 3.0 license (as stated in the Terms of Service). Unfortunately, that license is not particularly suited for code and has similar requirements as the GPL that work derived from content under the CC-BY-SA license must also be distributed under the CC-BY-SA license.

From a purely legal standpoint, this makes it impossible to distribute your software, because two parts require that the entire project is released under different terms.

In practical terms, contributers to Stack Overflow often don't know about the effects of the license that StackExchange uses for the user-content and are probably likely willing to grant you a license to those classes under different terms.

This leaves the matter of using GPL code in your project, which means that you must use version 2 or later of the GPL license for your code as well.

Title: Best freeware license for my closed-source application

Body:
I have no experience in software licensing so far. I am releasing my first application but I am not familiar with any licenses. Most of the the summeries found that I can understand (http://opensource.org/licenses/category) are open source but I want my application to stay closed-source. I am a little lost among all these choices.

My application:

uses a DLL created from a project version licensed under GNU LGPL (no code changes made)

uses a statically linked class licensed under "GNU GPL v2 or any later" (modified by adding a few properties (just getters, a couple of lines))

uses 2 small classes found in stackoverflow discussions which code was published under no license, I guess

implements a possibility to donate funds

I need a license that states:

It is free to use for everyone

Everyone can redistribute it on their repositories. I guess I want basic information about the author and my website included.

It is forbidden to modify and sell it in any way

The license does not obligate me to distribute the source code

The author gives no warranty

The author can change the license to one of a non-commercial license any time in the future (not required)

My questions:

What license matches the above statements? (provide a link to the body and the summery, please)

I am going to include information about third-party licensed code and its authors. Should I also mention authors of classes found at stackoverflow?

Have I modified the GNU GPL class enough to be obligated to release this modified class?

The project I use a DLL from changed the license from GNU LGPL to MIT in the newer version. Can I update this library used in my project with no influence on the license I choose?

Is it possible in the future to license this project under a non-commercial license combined with an implemented donating feature as well? Is it acceptable in the community or is it a bad manner? I've been just wondering if I can receive donations and ask non-commercial users at the same time to consider buying a commercial license, that's all. It is my thinking in case it gets attention from commercial users in the future very unlikely.

If a non-commercial license using LGPL, GPL or MIT components is possible, what would it be? (provide a link to the body and the summery, please).

EDIT (annotation to the users' replies) 2015-10-27 19:20

greyfade: Let's say I get permissions from stackoverflow users to use their classes freely following BartvanIngenSchenau's advice. I understand the only obstacle left for releasing under a closed-source freeware license would be GPL?

2.1. Do LGPL and MIT licensed components included in my app permit using closed-source freeware license too?

2.2. I cannot get rid of GPL licensed part in my project. Let's say I release my project under GPLv3 (obtained permissions for CC-BY-SA 3.0 licensed classes at stackoverflow, using the DLL under LGPL or MIT - whatever) and I distribute the source code beside the binaries. Did I understand correctly? GPL permits any form of collecting voluntary donations? I am not about to require a donation to download, install nor use my application, it is user's good will. Still no?

2.3. Am I obligated under GPLv3 to distribute the source code at the server or only at user X's individual request by sending it to him/her?

2.4. Let's imagine I get a permission from the author and GPL is converted to LGPL. My application's got third-party components under LGPL (MIT), LGPL, 2xLGPL. Is it all right then to license my app under a closed-source freeware license letting donations? If yes, what'd be this license? If no, what license would the components need to be released under to match my wishes?


问:
Declaring JS Functions in Two Ways : What's the Benefit?
I've come across JS code in which I see functions being declared in two different styles:

Method 1

```<code>function doSomething(){

   alert('This is one way of declaring a function');

}
</code>```

Method 2

```<code>doSomething = function() {

    alert('And this is another way of declaring the same function');

}
</code>```

So what is the difference between the two and is there a case scenario where it would make sense to follow one method over the other?

PS: Sorry if the title seems vague. I didn't know the technical term used to describe the way the above two functions are declared.

答:
Method 1 is a type of function declaration, and Method 2 is a type of function expression. Knowing the names of the these two types of methods may help you in the future. There are several other stackExchanges and stackOverflows available if you still need help. </p>

<p>ex: https://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip </p>

Body:
Method 1 is a type of function declaration, and Method 2 is a type of function expression. Knowing the names of the these two types of methods may help you in the future. There are several other stackExchanges and stackOverflows available if you still need help.

ex: https://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip


答:
I am not a lawyer and this is not legal advice. Consult your copyright attorney if you want clarification on any of these issues.

uses a statically linked class licensed under "GNU GPL v2 or any later" (modified by adding a few properties (just getters, a couple of lines))

The GPL requires that you re-release the source code for any changes you've made in some usable form, including the rest of your project.

If you do not release all of the source code for your entire project, you are in violation of the GPL.

uses 2 small classes found in stackoverflow discussions which code was published under no license, I guess

The legal status of these code snippets is unclear, but based on the licensing of the content of StackExchange as a whole, it's probably licensed under Creative Commons Attribution-Sharealike license, which has terms similar to the GPL and requires attribution of the source.

What license matches the above statements? (provide a link to the body and the summery, please)

The GPL. Due to your use of GPL-licensed code, you must license your source code under the same or less restrictive terms. This means, further, that you are not permitted to distribute your program as closed-source freeware.

I am going to include information about third-party licensed code and its authors. Should I also mention authors of classes found at stackoverflow?

Yes. This is required by the Creative Commons Attribution license.

Have I modified the GNU GPL class enough to be obligated to release this modified class?

You are obligated to release it, no matter how much or how little you've changed. You are also obligated to release any code that links with it.

The project I use a DLL from changed the license from GNU LGPL to MIT in the newer version. Can I update this library used in my project with no influence on the license I choose?

Yes, so long as its license is not more restrictive (i.e., incompatible) with the GPL.

Is it possible in the future to license this project under a non-commercial license combined with an implemented donating feature as well? Is it acceptable in the community or is it a bad manner? I've been just wondering if I can receive donations and ask non-commercial users at the same time to consider buying a commercial license, that's all. It is my thinking in case it gets attention from commercial users in the future very unlikely.

Donations are irrelevant, so long as you are not charging for the software itself. The terms of the GPL apply, and they permit donations and charging for "conveyance."

If a non-commercial license using LGPL, GPL or MIT components is possible, what would it be? (provide a link to the body and the summery, please).

Only GPL and GPL-compatible licenses are permitted for such software, due to the use specifically of the GPL.

2.1. Do LGPL and MIT licensed components included in my app permit using closed-source freeware license too?

MIT permits relicensing, provided you include the Copyright notice and a copy of the license in your code.

LGPL permits linking to a closed-source application, but only in a form that allows end-users to replace the LGPL-licensed portions of your program. In general, that means that dynamically-linking is permitted.

Read the FSF's GPL FAQ, which explains this and related issues.

2.2. I cannot get rid of GPL licensed part in my project. Let's say I release my project under GPLv3 (obtained permissions for CC-BY-SA 3.0 licensed classes at stackoverflow, using the DLL under LGPL or MIT - whatever) and I distribute the source code beside the binaries. Did I understand correctly? GPL permits any form of collecting voluntary donations? I am not about to require a donation to download, install nor use my application, it is user's good will. Still no?

If the code you're using under the GPL is licensed "GPLv2 or later" or "GPLv3" or "GPLv3 or later," then yes, you can release your project under the GPLv3. If the project is licensed under GPLv2, but not "GPLv2 or later," then you can't license your code under GPLv3, because the two licenses are mutually-incompatible unless the v2 license has the "or later" clause.

You should also be aware that CC-BY-SA 3.0 is not compatible with the GPL. However, CC-BY-SA 4.0 is compatible with GPLv3.

Donations are irrelevant.

2.3. Am I obligated under GPLv3 to distribute the source code at the server or only at user X's individual request by sending it to him/her?

You are required to provide the source on request, but the most convenient and simplest way to comply with this requirement is to publish the modified source alongside the binary distribution.

2.4. Let's imagine I get a permission from the author and GPL is converted to LGPL. My application's got third-party components under LGPL (MIT), LGPL, 2xLGPL. Is it all right then to license my app under a closed-source freeware license letting donations? If yes, what'd be this license? If no, what license would the components need to be released under to match my wishes?

You may distribute your code under any license you wish as long as you are in compliance with the LGPL terms.

To comply with the LGPL, end-users must be able to modify and replace all LGPL-licensed components without violating your license and without needing special tools to do so.

In principle, this means that your code must either be licensed under the LGPL, or some other GPL-compatible license, or the LGPL-licensed portions must be dynamically linked.

Again, you should read the FSF's GPL FAQ, as it explains these issues in detail.


答:
First, get rid of the statically-linked class licensed under GPL, since it will conflict with your goal of releasing it as closed-source freeware. If you know how that class works, you can easily write your own implementation. Or find an MIT/BSD licensed version of it.

Then, give credit to the places where you got the code snippets from. According to Jeff Atwood it should be okay to use the StackOverflow code snippets under the doctrine of fair use, but it's better to just give credit to those who written your code...just in case.

Finally, release the program under a Creative Commons license (as this answer suggest). While it is not encouraged to use them for software licenses, it would still be valid. In this case, you are not really licensing the code, but the program that you are releasing to the general public.

This specific license meets all the criteria you desire (http://creativecommons.org/licenses/by-nc-nd/4.0/).


问:
Does extending a ruby class violate the LSP?
I am reading about SOLID principles. In Ruby tutorials and code samples, I often see subclass extensions like:

```<code>class House
  attr_reader :items
end

class Room < House
  attr_reader :chair
end

p House.chair = 'baroque_style'# => NoMethodError
</code>```

Of course the examples are useful to show how easily classes are manipulate in ruby, but isn't this a violation of the Liskov Substitution Principle?

答:
No, LSP states that if S is a subtype of T, you should be able to use an S whenever a T is expected.

In your example, Room is a subtype of House, so we should be able to pass an instance of Room to anything expecting a House. What you then do is to pass a House into code expecting a Room (so you are using a T, where an S is expected).


问:
usage of interface.super.print() in java8
In java8, we are using interface.super.

Considering the below points

There are 2 interfaces but none of the interfaces inherit to another.

There is implementation class which is inheriting both of those 2 interfaces.

Each interface has a default method but the name is same for both of those methods.

Now in this scenario, in the implementation class it is forcing me to override the default print() method. And in the body I need to use either

Interface_one.super.print();

or

Interface_two.super.print();

I am new to Java8, I would like to understand the strange behaviours of using the interface.super. Also the implementation of print() method forcing the statements Interface_one.super.print(); or Interface_two.super.print();

 public interface Interface_one {
    public void method1();

    default void print(){
        System.out.println("this is default print in first interface");
    }
}

public interface Interface_two {
public void method2();

    default void print(){
        System.out.println("this is default print in second interface");
    }
}

public class ImplementedClass implements Interface_one, Interface_two{

    @Override
    public void method1() {
        System.out.println("Implemented Method 1");

    }

    @Override
    public void method2() {
        print();
        System.out.println("Implemented Method 2");
    }

    @Override
    public void print() {
        Interface_one.super.print();
    }

    public static void main(String[] args) {
        new ImplementedClass().method2();
    }
}
```

答:
If you inherit from two interfaces A and B, then A.super.foo() calls the foo (default) method of the A interface.

When you implement two interfaces which each have default methods with the same name, it's ambiguous.  You need to resolve that ambiguity by explicitly stating which of the two default methods you'd like your implementation to use.  You do this by overriding the method in question and calling the "parent" interface's implementation directly.  You do this with the new syntax: ParentInterfaceName.super.methodName();


问:
Why is deletion usually much harder to implement than insertion in many data structures?
Can you think of any specific reason why deletion is usually significantly harder to implement than insertion for many (most?) data structures?

Quick example: linked lists. Insertion is trivial, but deletion has a few special cases that make it significantly harder. Self-balancing binary search trees such as AVL and Red-black are classic examples of painful delete implementation.

I would like to say it has to do with the way most people think: it is easier for us to define things constructively, which leads nicely to easy insertions.

答:
It's more than just a state of mind; there are physical (i.e. digital) reasons why deletion is harder.

When you delete, you leave a hole where something used to be.  The technical term for the resulting entropy is "fragmentation." In a linked list, this requires you to "patch around" the removed node and deallocate the memory it is using.  In binary trees, it causes unbalancing of the tree.  In memory systems, it causes memory to go unused for awhile if newly-allocated blocks are larger than the blocks left behind by deletion.

In short, insertion is easier because you get to choose where you are going to insert.  Deletion is harder because you can't predict in advance which item is going to get deleted.


问:
When returning from a period of not programming, do you find you've improved?
It seems as though whenever I take an extended break from programming—whether to pursue other interests or simply because I fall out of the habit for a while—I invariably find that when I return to a project and set to coding, I come with an abundance of new ideas, novel approaches, and just plain better code. It may be because I have a lot of other creative interests besides programming, and my mind likes to find correlation and crossover between them, so while I'm doing one thing, in the back of my mind I'm usually also applying it to another.

So what's your experience? Do you ever return from a break (whether intentional or not) feeling not only refreshed, but also somehow noticeably improved? Is it actually the norm?

答:
My experience is that the basic mechanics of programming - or to be really explicit coding are something you need to practice continuously to keep you sharp.

In a large chunk of time mostly spent dealing with development at a higher level than the IDE I found that when doing anything other than bug hunts or quick hacky fixes I did not perform at a level I know myself to be capable of mostly because I'm not remembering the trivial almost automatic things without concious effort.

At a higher level, in terms of "inspiration", don't know... but certainly I'd never assert that any absence I've had has left me noticeably improved (though I don't know if, in, erm, about 30 years now, I have a really extended time - more than 3 weeks - genuinely 100% away from programming!)


答:
In term of run-time, looking at the data structure operations time complexity comparison on Wikipedia, note the insert and delete operations have the same complexity. The delete operation profiled there is deletion by index, where you have a reference to the structure element to be deleted; insertion is by item. The longer running time for deletion in practice is because you usually have an item to delete and not its index, so you also need a find operation. Most data structures in the table don't require an additional find for an insert because the placement position isn't dependent on the item, or the position is determined implicitly during the insertion.

As for cognitive complexity, there's an answer in the question: edge cases. Deletion may have more of them than insertion (this has yet to be established in the general case). However, at least some of these edge cases can be avoided in certain designs (e.g. have a sentinel node in a linked list).

Title: Why is deletion usually much harder to implement than insertion in many data structures?

Body:
Can you think of any specific reason why deletion is usually significantly harder to implement than insertion for many (most?) data structures?

Quick example: linked lists. Insertion is trivial, but deletion has a few special cases that make it significantly harder. Self-balancing binary search trees such as AVL and Red-black are classic examples of painful delete implementation.

I would like to say it has to do with the way most people think: it is easier for us to define things constructively, which leads nicely to easy insertions.


问:
Is HTTP 426 acceptable for "Your request should have been HTTPS"
I have an HTTP serving an API which works either anonymously or with a secret key in a header, like so:

```<code>GET /profile?authenticationKey
Authorization: 1234567890
</code>```

I want to reject any request coming in over HTTP that uses an Authorization header, since those headers would come across in plain text. But I'm not sure what the appropriate response is.

I've considered 400 Bad Request with a note explaining why what they did was stupid and suggesting that they immediately invalidate their key.

But I'm wondering whether 426 Upgrade Required might be better or worse. It's a code specific to the idea that an HTTP request needs to be an HTTPS request, but reading RFC 2817 makes me think that it is designed to help switch to HTTPS from the same port. Can I use it in this case as well? If so, do I need to include an Upgrade: TLS/1.0 header as well?

答:
The situation you are trying to avoid here is that of API users sending their credentials over the wire in a form easily sniffed by third parties.

If you either redirect to HTTPS or serve any HTTP error, you don't avoid this situation; the credentials are already sent before you have a chance to respond.

The only really proper thing to do is to not serve the API on HTTP at all, not even for anonymous requests. For your API server, ideally there should not be a server listening on port 80 at all. If you must have that IP address listening on port 80 (e.g. because you don't have any spare IP addresses), then you should return 403 Forbidden or 404 Not Found for API requests. Optionally you could capture and invalidate such credentials as were sent mistakenly over HTTP, but it's best to simply not listen on HTTP at all.

OwnerDisplayName: Bob


问:
How to deal with long running transactions?
I'm developing a Content Management System (CMS) and I would like to include a "Save Changes" button. I mean: a user performs several changes in the database, but those changes are still not available. Just when the user presses the "Save Changes" button, those changes are "visible" for the website.

I have thinking in "SQL transactions". But I have understood that "SQL transaction" were designed to be used in a short space of time. And in this particular case the user may keep the transaction open for some time (one hour, two hours...).

How can deal with this kind of issues? I'm using PHP and MySQL?

答:
There are lots of content management systems and I have only used a couple, but I think what content management systems frequently do is maintain two databases or filesystems, one for you to edit content and the other for what the users see.  I know the content management system I used to use a lot (Vignette, now OpenText) did that.  There are two separate parts, Management/Preview and Delivery.  Management is where you do your editing, and when you want to let users see the content, you publish to Delivery.  Publishing involves copying from the Management database to the Delivery database.

This means that you could save changes many times before publishing, or never publish at all.  For the content admins, it is much easier to use a system that lets you save and come back to your work later and publish when you are ready.


答:
It is not harder.

With doubly linked lists, when you insert, you will be allocating memory, and then you will be linking with either the head or the previous node, and with either the tail or the next node. When you delete, you will be unlinking from exactly the same, and then freeing memory.  All these operations are symmetric.

This assumes that in both cases you have the node to insert/delete.  (And in the case of insertion, that you also have the node to insert before, so in a way, insertion could be thought of as slightly more complicated.)  If you are trying to delete having not the node to delete, but the payload of the node, then of course you are going to have to first search the list for the payload, but that's not a shortcoming of deletion, is it?

With balanced trees, the same applies: a tree generally needs balancing immediately after an insertion and also immediately after a deletion. It is a good idea to try and have only one balancing routine, and apply it after each operation, regardless of whether it was an insertion or a deletion.  If you are trying to implement an insertion which always leaves the tree balanced, and also a deletion which always leaves the tree balanced, without having the two share the same balancing routine, you are unnecessarily complicating your life.

In short, there is no reason why one should be harder than the other, and if you are finding that it is, then it is in fact possible that you are a victim of the (very human) tendency of finding it more natural to think constructively than subtractively, meaning that you might be implementing deletion in a way which is more complicated than it needs to be.  But that's a human issue.  From a mathematical standpoint, there is no issue.


答:
Why does it tend to be harder to delete than to insert? Data structures are designed more with insertion in mind than deletion, and rightfully so.

Consider this - in order to delete something from a data structure, it has to be there in the first place. So you need to add it first, meaning that at most you have as many deletions as you have insertions. If you optimize a data structure for insertion, you're guaranteed to get at least as much benefit as if it had been optimized for deletion.

Additionally, what use is there in sequentially deleting each element? Why not just call some function that clears it out all at once (possibly by just creating a new one)? Also, data structures are most useful when they actually contain something. So the case of having as many deletions as insertions is, in practice, not going to be very common.

When you optimize something, you want to optimize the things that it does the most and that take the most time. In normal usage, deletion of elements of a data structure happens less frequently than insertion.


问:
Separation of retrieving data and business objects between DAL and BLL Layers
I did some research before posting this question. Among other questions or post, one of those is provided below. I could not get a clear mind how to determine..

Business Objects within a Data Access Layer

I have a Repository and the Business Layers call the repository to retrieve the data. For example, say I have the following classes for BLL and DAL:

```<code>class BllCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public BllAddress Address {get; set;}
}

class BllAddress
{
     public int AddressId {get; set;}
     public String Street {get; set;}
     public String City {get; set;}
     public String ZipCode {get; set; }
}

class DalCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public int AddressID {get; set;}
}

class DalAddress
{
     public int AddressId {get; set;}
     public String Street {get; set;}
     public String City {get; set;}
     public String ZipCode {get; set; }
}
</code>```

If the BLL wants to retrieve a Customer object, it would call GetCustomerById(customerId) in DAL.

The following are my concerns I could not get a clear mind:

I cannot see how to determine what object the GetCustomerById in DAL should return? Should it return BllCustomer or DalCustomer?

Where should be the retrieving (and/or converting to Business object) of the address associated with the customer?

If the DAL returns Dal objects then, the logic to retrieve and fill in the Address can only be in the BLL. If the DAL returns BLL objects, then the logic to retrieve and fill in the Address can be either in the BLL or DAL. Currently the DAL is returning the Business Objects and the logic to fill it in is in the DAL.

From what I read, I guess there is no right or wrong. From the link included above, there are people saying one way and the others are saying the other way. But how do I determine which would works best for my case?

Any help would be appreciated.

答:
Your repository should return the BLL or domain object. chances are you don't need a DAL object at all.</p>

```<code>public class Customer
{
    public string Name {get; private set;}
    public Customer(string name)
    {
        this.Name = name;
    }
}

public class Repository
{
    public Customer GetCustomer(string id)
    {
        //get data from db
        return new Customer(datarow["name"]);
    }
}
</code>```

Body:
Your repository should return the BLL or domain object. chances are you don't need a DAL object at all.

public class Customer
{
    public string Name {get; private set;}
    public Customer(string name)
    {
        this.Name = name;
    }
}

public class Repository
{
    public Customer GetCustomer(string id)
    {
        //get data from db
        return new Customer(datarow["name"]);
    }
}


问:
Algorithm for creating a looping 3D path that complete fills a cube

I'm creating a game world that consists of a 16 x 16 x 16 rubix cube (pictured), where the individual cubes are floating in space. The cubes continuously move along a single set path that links up with itself at the end. It might be helpful to think of them as traversing a 3D maze. Are there any algorithms or solutions that could help me generate this path?

答:
As I mentioned in a comment, one possible way to solve this is to weave a path back & forth across a face using 2 pencils.  One pencil draws the beginning of the path, and the other draws the end.

Here's an example for one face:

```<code>+----------------+
|abcdefghijklmnop|
|ZYXWVUTSRQPONMLq|
|****ABCDEFGHIJKr|
|*###3210zyxwvuts|
|*###############|
|***************#|
|***************#|
|*###############|
|*###############|
|***************#|
|***************#|
|*###############|
|*###############|
|***************#|
|***************#|
|*###############|
+----------------+
</code>```

One pencil starts in the top row, left column, "abcd..."

The other pencil starts in the 2nd row, left column, "ZYXWV..."

As you can see, both paths end in the left column, bottom 2 rows.  At that point you move to the next face & repeat the process.

When you've finished you have to "parallel" paths.  Just tie the ends together & you have your loop that visits each node.

a limitation

This only works because the number of rows (or columns) is a multiple of 2.  If your grid was 15x15x15, you'd have a problem.

Body:
As I mentioned in a comment, one possible way to solve this is to weave a path back & forth across a face using 2 pencils.  One pencil draws the beginning of the path, and the other draws the end.

Here's an example for one face:

+----------------+
|abcdefghijklmnop|
|ZYXWVUTSRQPONMLq|
|****ABCDEFGHIJKr|
|*###3210zyxwvuts|
|*###############|
|***************#|
|***************#|
|*###############|
|*###############|
|***************#|
|***************#|
|*###############|
|*###############|
|***************#|
|***************#|
|*###############|
+----------------+

One pencil starts in the top row, left column, "abcd..."

The other pencil starts in the 2nd row, left column, "ZYXWV..."

As you can see, both paths end in the left column, bottom 2 rows.  At that point you move to the next face & repeat the process.

When you've finished you have to "parallel" paths.  Just tie the ends together & you have your loop that visits each node.

a limitation

This only works because the number of rows (or columns) is a multiple of 2.  If your grid was 15x15x15, you'd have a problem.


答:
Think of SQL transactions as groups of SQL queries ran together in one connection to maintain database consistency, eg. when removing data, remove also any linked entries from relation tables to keep the database clean. If a problem occurs, you can use ROLLBACK to revert the changes in current SQL transaction.
PostgreSQL can take care of consistency by itself and can do a lot more with larger projects.

You can log a history of changes or you can add another column to the table (text _draft). Visitors would still see original text, but while you would be logged as admin, you could check for any data in this column and display this instead of original text. By opening the two regularly and in anonymous window you could easily see the changes.

Title: How to deal with long running transactions?

Body:
I'm developing a Content Management System (CMS) and I would like to include a "Save Changes" button. I mean: a user performs several changes in the database, but those changes are still not available. Just when the user presses the "Save Changes" button, those changes are "visible" for the website.

I have thinking in "SQL transactions". But I have understood that "SQL transaction" were designed to be used in a short space of time. And in this particular case the user may keep the transaction open for some time (one hour, two hours...).

How can deal with this kind of issues? I'm using PHP and MySQL?


问:
Starting on Web Project now - Do we choose HTML5/JS over Silverlight?
we are about to start on a Web Development project (the planning starts early 2011).

Do we choose HTML5/JS over Silverlight?

Are there any applications which now run on HTML5? Samples?

A simple Google Search led me here. Those look great (especially the Star Wars one!), but they are not what you call proper applications as such.

答:
You have a notebook or desktop machine with Windows, am I right? But there are some other sort of machines:

netbooks, wich runs non-Windows operating sytem, see Chrome OS,

Android or iOS tablets,

smartphones (iPhone, Android, Palm webOS).

If you choose SilverLight, your program will never run on these machines.


问:
Is the Perl default variable like an FP monad?
I have been getting my head around monads in functional programming and seem to see some commonality between Perl's default variable $_ and FP monads.

Is this true?  Are there similarities, if not why not - perhaps this'll allow me to grok monads once and for all by understanding why the use of $_ is not monad like!

My (at this stage vague) understanding of a monad is that one aspect is that it can be used to chain commands together so that the output of one is magically the input of the next.

So for example this perl:

```<code>while (<STDIN>) {
   chomp;
   s/Hello/Goodbye/;
   print;
}
</code>```

Takes from the stdin, removes white space (chomp) replaces "Hello" with "Goodbye" and prints out the result.  Each of those commands uses the value in the implied variable $_ and outputs the result into it.

The same code but showing the implied variable use:

```<code>while ($_ = <STDIN>){
    chomp $_;
    $_ =~ s/Hello/Goodbye/;
    print $_;
}
</code>```

So correct me if I'm wrong but that feels very much like one aspect of monads.

答:
I understand why you see a similarity between monads and the $_ variable:

a monad encapsulates a value in some context, and allows operations to be performed on that value.

the $_ variable refers to the current context. Operations can use this context.

So the common part is that there is some value, some context, and some operations. Unfortunately, this could describe all programming. The $_ variable is not monad like because it does not actually have any properties of a monad. Most importantly, using the $_ variable does not compose.

One aspect of monads is that they can be defined by two operations: one to wrap a value in a context (sometimes called a constructor, or a return operation), and one bind operation to apply an action to a value. The action given to bind takes an unwrapped value, and returns a monad of the expected kind again. It is really important that bind does not return a naked value, but a monad. The monad is responsible for deciding whether, how often, and in which order the bind action is applied to its wrapped value, if any. This flexibility allows monads to model collections with any number of elements, and also control flow constructs such as conditionals.

In Perl, lists have mostly monad-like behaviour. Their construction is implicitly tracked through list context, and their bind operation is the map builtin. The special context of a list is that all values in the list are ordered. Examples:

# the empty list
() #=> ()
# a list of one element
(1) #=> (1)
# a longer list
(1, 2, 3, 4) #=> (1, 2, 3, 4)
# identity
map { ($_) } (1, 2, 3) #=> (1, 2, 3)
# double each item
map { ($_, $_) } (1, 2, 3) #=> (1, 1, 2, 2, 3, 3)
```

<p>We can show that this satisfies the monad laws:</p>

<ul>
<li><p>the constructor is the neutral operation for bind: Given a list <code>@list</code>, <code>map { ($_) } @list</code> is always the same as <code>@list</code>, and wrapping a value <code>$x</code> in a list <code>($x)</code> and then mapping a function <code>f</code> over it <code>map { f($_) } ($x)</code> has the same effect as <code>f($x)</code>.</p></li>
<li><p>binding actions satisfies a specific equivalence. For a given <code>@list</code> and all (pure) functions <code>f</code> and <code>g</code>, these two expressions must be equivalent:</p>

<pre class="lang-perl prettyprint-override"><code>map { g($_) } map { f($_) } @list
map { map { g($_) } f($_) } @list
</code>```

Now let's contrast this with operations such as s/foo/bar/ that operate on $_ by default. We clearly have a kind of constructor for $_, e.g. for loops place the value in $_ by default. And we have a kind of binding mechanism that allows $_ to be used by some operation. These operations take the value from $_ and usually modify it in-place. However, in-place modifications are fundamentally at odds with monadic behaviour – the bind operation expects an action that takes an unwrapped value and returns a monad. With in-place modification, we must return exactly one value. There's no wrapping/unwrapping taking place either explicitly or implicitly.

The point that the result of each computation is used by the next step may look monadic, but it's just imperative programming. Being a stateful variable is all that $_ is. Of course, you can model imperative stateful computations with a state monad, but that is more about the ; operator than the $_ variable.

By the way, the only special aspect of $_ is that the *_ variables are super-global and always resolve to the main package. The general syntax of your example code could be mirrored with any other implicit variable, e.g. $::florp:

sub florpyreadwhile {
  my ($fh, $body) = @_;
  while ($::florp = <$fh>) {
    $body->();
  }
}

sub florpychomp {
  return chomp $_[0] if @_;
  return chomp $::florp;
}

sub florpysubstitute {
   my ($re, $sub) = @_;
   my $str_ref = (@_ >= 3) ? \$_[2] : \$::florp;
   return $$str_ref =~ s/$re/$sub/;
}

sub florpyprint {
  return print @_ if @_;
  return print $::florp;
}

# using florpy sugar

florpyreadwhile \*STDIN => sub {
  florpychomp;
  florpysubstitute qr/Hello/ => 'Goodbye';
  florpyprint;
};

# without florpy sugar

florpyreadwhile \*STDIN => sub {
  florpychomp $::florp;
  florpysubstitute qr/Hello/ => 'Goodbye', $::florp;
  florpyprint $::florp;
};
```

Body:
I understand why you see a similarity between monads and the $_ variable:

a monad encapsulates a value in some context, and allows operations to be performed on that value.

the $_ variable refers to the current context. Operations can use this context.

So the common part is that there is some value, some context, and some operations. Unfortunately, this could describe all programming. The $_ variable is not monad like because it does not actually have any properties of a monad. Most importantly, using the $_ variable does not compose.

One aspect of monads is that they can be defined by two operations: one to wrap a value in a context (sometimes called a constructor, or a return operation), and one bind operation to apply an action to a value. The action given to bind takes an unwrapped value, and returns a monad of the expected kind again. It is really important that bind does not return a naked value, but a monad. The monad is responsible for deciding whether, how often, and in which order the bind action is applied to its wrapped value, if any. This flexibility allows monads to model collections with any number of elements, and also control flow constructs such as conditionals.

In Perl, lists have mostly monad-like behaviour. Their construction is implicitly tracked through list context, and their bind operation is the map builtin. The special context of a list is that all values in the list are ordered. Examples:

# the empty list
() #=> ()
# a list of one element
(1) #=> (1)
# a longer list
(1, 2, 3, 4) #=> (1, 2, 3, 4)
# identity
map { ($_) } (1, 2, 3) #=> (1, 2, 3)
# double each item
map { ($_, $_) } (1, 2, 3) #=> (1, 1, 2, 2, 3, 3)

We can show that this satisfies the monad laws:

the constructor is the neutral operation for bind: Given a list @list, map { ($_) } @list is always the same as @list, and wrapping a value $x in a list ($x) and then mapping a function f over it map { f($_) } ($x) has the same effect as f($x).

binding actions satisfies a specific equivalence. For a given @list and all (pure) functions f and g, these two expressions must be equivalent:

map { g($_) } map { f($_) } @list
map { map { g($_) } f($_) } @list

Now let's contrast this with operations such as s/foo/bar/ that operate on $_ by default. We clearly have a kind of constructor for $_, e.g. for loops place the value in $_ by default. And we have a kind of binding mechanism that allows $_ to be used by some operation. These operations take the value from $_ and usually modify it in-place. However, in-place modifications are fundamentally at odds with monadic behaviour – the bind operation expects an action that takes an unwrapped value and returns a monad. With in-place modification, we must return exactly one value. There's no wrapping/unwrapping taking place either explicitly or implicitly.

The point that the result of each computation is used by the next step may look monadic, but it's just imperative programming. Being a stateful variable is all that $_ is. Of course, you can model imperative stateful computations with a state monad, but that is more about the ; operator than the $_ variable.

By the way, the only special aspect of $_ is that the *_ variables are super-global and always resolve to the main package. The general syntax of your example code could be mirrored with any other implicit variable, e.g. $::florp:

sub florpyreadwhile {
  my ($fh, $body) = @_;
  while ($::florp = <$fh>) {
    $body->();
  }
}

sub florpychomp {
  return chomp $_[0] if @_;
  return chomp $::florp;
}

sub florpysubstitute {
   my ($re, $sub) = @_;
   my $str_ref = (@_ >= 3) ? \$_[2] : \$::florp;
   return $$str_ref =~ s/$re/$sub/;
}

sub florpyprint {
  return print @_ if @_;
  return print $::florp;
}

# using florpy sugar

florpyreadwhile \*STDIN => sub {
  florpychomp;
  florpysubstitute qr/Hello/ => 'Goodbye';
  florpyprint;
};

# without florpy sugar

florpyreadwhile \*STDIN => sub {
  florpychomp $::florp;
  florpysubstitute qr/Hello/ => 'Goodbye', $::florp;
  florpyprint $::florp;
};


问:
Is it advisable to force your web server to parse HTML files for PHP code?
I can't remember what site I glanced over and picked up that tidbit, but someone suggested that you should keep PHP parsing to .PHP files, and not modify one's webserver's htaccess to include PHP parsing within .HTML files.

Is this true? Is there any generally agreed upon reason as to doing it one way or the other?

答:
I'd say don't change it, use .php.

Creating unnecessary overhead for the server is not the main problem. Maintenance could well be a problem if another guy manages the server upgrades and has no idea to check if .html files have by accident stopped working - everyone assumes it's static.

The core of the problem is security. This little exception in .htaccess could become broken by simply changing level of commands allowed in .htaccess or by AllowOverride None directive anywhere in folders above. If anything like that happens and the php file is not parsed, all your code is instantly visible. All your includes and eventually all passwords could become visible publicly to everyone.. and also it could become cached by search engines.