答:
With the constrints you having (unable to use a common interface) for ModelA and for ModelB, there isn't a lot of things you can do from the Models. However you could generalize the helper class.

One way to do is,

```<code>public class RequestDTO
{
   string xyz_blah;
}

public class ResultDTO.
{
   string ProductCheckField;
}

public class HelperClass
{
    public static ResultDTO ProductCheckMethod(RequestDTO request)
    {
        //do something
        ResultDTO result = performXUsingRequestData(model);
        checkYUsingRequestData(model,result);
        return result;
    }
}
</code>```

Here the data you currently sending to the methods performX,checkY are added to the RequestDTO and whatever the data you want to update on the model are added to the ResultDTO.

In your model you could call the helper class like this,

```<code>public class ModelA
{
   string blah..
   int blah
   .....
   string ProductCheckField

   public void ProductCheckMethod()
   {
       RequestDTO dto = new RequestDTO { xyz_blah = blah; }
       ResultDTO result = HelperClass.ProductCheckMethod(dto);
       ProductCheckField = result.ProductCheckField;
   }
}
</code>```

Same goes for the ModelB

Title: What is the efficient way to eliminate duplication? Design patterns?

Body:
I have a helper class which has a method that perform some checks against a field in a model. I have two models, ModelA and ModelB, they have some similarities but not all. One of them is they both have a field, lets say string ProductCheckField. The ProductCheckMethod returns back the Model, because of that it has created duplication of methods which does the same thing but returns a different model. Even the extracted methods are duplicates. Is there a good design pattern or any other good practice/technique I can use to eliminate duplication of having to create two methods?

N.B I can't use a shared Interface as the models are not the same.

Currently I have..

```<code>public class ModelA
   string blah..
   int blah
   .....
   string ProductCheckField

public class ModelB
   string xyz
   int xyz
   .....
   string ProductCheckField

public class HelperClass
{

    public ModelA ProductCheckMethod(ModelA model)
    {
       /// do somthing
       performX(model);
       checkY(model);
       return model;
    }

    public ModelB ProductCheckMethod(ModelB model)
    {
       /// do somthing
       performXDuplicate(model);
       checkYDuplicate(model);
       return model;
    }
}
</code>```

Body:
With the constrints you having (unable to use a common interface) for ModelA and for ModelB, there isn't a lot of things you can do from the Models. However you could generalize the helper class.

One way to do is,

public class RequestDTO
{
   string xyz_blah;
}

public class ResultDTO.
{
   string ProductCheckField;
}

public class HelperClass
{
    public static ResultDTO ProductCheckMethod(RequestDTO request)
    {
        //do something
        ResultDTO result = performXUsingRequestData(model);
        checkYUsingRequestData(model,result);
        return result;
    }
}

Here the data you currently sending to the methods performX,checkY are added to the RequestDTO and whatever the data you want to update on the model are added to the ResultDTO.

In your model you could call the helper class like this,

public class ModelA
{
   string blah..
   int blah
   .....
   string ProductCheckField

   public void ProductCheckMethod()
   {
       RequestDTO dto = new RequestDTO { xyz_blah = blah; }
       ResultDTO result = HelperClass.ProductCheckMethod(dto);
       ProductCheckField = result.ProductCheckField;
   }
}

Same goes for the ModelB


问:
Architectural / Application Practices to guard against 'breaking changes'
We have an application where the customer has changed their mind about a large area of functionality and this area requires a large amount of re-work.

Whilst the re-work itself is not an issue, it has introduced a situation where the impact of the changes is wide ranging including:

Data

Query Logic / Table structure

Business logic

Display / Presentation

Ideally we'd like to incorporate these changes at the same time as several other development streams, but we're worried that the impact of the changes will have a negative impact on how frequently we can deliver. We can cater for some of this through branches, but it made me wonder what the possibilities are for guarding against this kind of thing from an application architecture or development practice point of view.

Things we currently do:

Abstract query logic into repositories - This is great for small changes, but when the overall logic in an area changes, e.g. instead of getting a list of users which meet a certain criteria, we now need to get a list of organisations which joined to locations.

Abstract business logic into services - This is exactly the same as the repositories in that we can't really guard against entire logic shifts, but small changes can be accommodated with limited impact.

Ensure configuration is kept out of code which needs re-deployment, a combination of database rows or web.config values.

Other patterns which promote aspects of flexibility like factories where appropriate etc.

Feature flagging for selection of functionality if two approaches were developed originally. etc

Are there any other current best practices to guard against changes, without incorporating branches etc?

答:
Unit tests and Integration tests can be used to protect your logic from code changes.

If you currently have a good code coverage, and you need to re-work a section, then the approach would be easier, you can change your tests to reflect the result after the re-work and once you have done the change you can  re-run the test cases, to make sure it's all working. (In practice it would be a good idea to use a continuous integration server to run tests after each commit, and with this you can do smaller changes at a time and make sure all the logic is intact with the CI server status)

If you do not have tests, then it would be a good idea to create some. If you are under tight deadline, you could start with integration tests where the tests will verify the output of the given input from the presentation level. For each place where change is needed you can start with creating tests for the expected output after the changes, and do the changes so and make sure tests are green.

ContentLicense: CC BY-SA 3.0


问:
What was the worst piece of code you fixed that you are proud of?
I have had a few that I am proud of and some of them were written by myself few years ago. It doesn't have to be necessarily buggy, just bad code. </p>

答: I took a cursor out of a trigger and reduced the time to insert 40,000 new records from an hour to less than a minute. Eventually this resulted in me being able to insert 21 million records in something less than glacial time but we never tried the 20 million record import til after the fix, so I don't have stats on how much time we saved.</p>

ContentLicense: CC BY-SA 2.5


问:
Is there a standard project metadata / dependency file for Python?
In my Node.JS projects, I save my project metadata into package.json: dependencies, version number, author, description, and so on.  This makes it so anyone can clone my project and run npm install to create a virtually identical local environment.

Is there a such thing for Python?  Some sort of standard file where I can save project metadata, including a version number and PIP dependencies?

答:
Python setuptools is a module that you use to write a script, called setup.py in the main directory of your Python project. For distribution purposes, you can use your setup.py to make a Python egg. 9000's link goes into more detail about how to make the egg.

The first link contains detailed documentation on how to write the perfect setup.py, but below is a complete example modified for a Python project I wrote some time ago.

```<code>from setuptools import setup

def readme():
    """
    This is a function I wrote to read my README file and return it.
    """
    with open('README.rst') as f:
        return f.read()

setup(name='stackexample',
      version='0.1',
      description='An answer to a question on StackOverflow',
      long_description=readme(), # Get that README.rst
      classifiers=[
          'Development Status :: 3 - Alpha',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3.0'
      ],
      keywords='questions answers programming',
      url='http://stackexchange.com/',
      author_email='bob@example.com',
      license='MIT',
      entry_points = {
          'console_scripts' :
          ['stackex=stackexample.command_line:main']
      },
      packages=['stackexample'],
      install_requires=[
          "requests",
          "something_on_pip",
      ],
      test_suite='nose.collector',
      test_requires=['nose', 'nose-cover3'], # Requirements for the test suite
      include_package_data=True,
      zip_safe=False)
</code>```

You can also use a requirements.txt file to list dependencies. This blog post goes into pretty good detail about the difference between requirements.txt and setup.py.

Body:
Python setuptools is a module that you use to write a script, called setup.py in the main directory of your Python project. For distribution purposes, you can use your setup.py to make a Python egg. 9000's link goes into more detail about how to make the egg.

The first link contains detailed documentation on how to write the perfect setup.py, but below is a complete example modified for a Python project I wrote some time ago.

from setuptools import setup

def readme():
    """
    This is a function I wrote to read my README file and return it.
    """
    with open('README.rst') as f:
        return f.read()

setup(name='stackexample',
      version='0.1',
      description='An answer to a question on StackOverflow',
      long_description=readme(), # Get that README.rst
      classifiers=[
          'Development Status :: 3 - Alpha',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3.0'
      ],
      keywords='questions answers programming',
      url='http://stackexchange.com/',
      author_email='bob@example.com',
      license='MIT',
      entry_points = {
          'console_scripts' :
          ['stackex=stackexample.command_line:main']
      },
      packages=['stackexample'],
      install_requires=[
          "requests",
          "something_on_pip",
      ],
      test_suite='nose.collector',
      test_requires=['nose', 'nose-cover3'], # Requirements for the test suite
      include_package_data=True,
      zip_safe=False)

You can also use a requirements.txt file to list dependencies. This blog post goes into pretty good detail about the difference between requirements.txt and setup.py.


问:
How handle a chain of Whens or Thens in a Scenario?
I am trying to figure out how to write BDD scenario where it seems like I need a chain of "Then" conditions.  How do I write it?  As one scenario?  As two scenarios?

Here is how I've written as one scenario:

```<code>Scenario: Take user directly to their message on swipe after login
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in
And she is taken directly to the specific message shown in the preview
</code>```

It's the last two lines I'm unsure of.  What I'm trying to say she is taken directly to the specific message shown in the preview should not occur until after she must log in.  They should not co-occur, which is what I suspect an Then containing an And probably means.

Should I separate it into two scenarios like this:

```<code>Scenario: Make user login after swipe
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in

Scenario: Take user to message after logging in
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
And she has swiped the preview
When she logs in
Then she is taken directly to the specific message shown in the preview
</code>```

Thanks in advance for your help.

答:
I guess the first scenario should end with a reference to a specificially named second scenario like

```<code>...
Then she must "log-in-with-message-from-preview"
</code>```

(the name should make clear it is not the "usual login", but a more specific situation).

Now you can describe this 2nd scenario without repeating all the preconditions again:

```<code> Scenario: "log-in-with-message-from-preview"
 Given Dee is at the login
 And she got a message from a preview before
 Then she is taken directly to the specific message shown in the preview
</code>```

(Disclaimer: I have no experience with BDD so far.)

Body:
I guess the first scenario should end with a reference to a specificially named second scenario like

...
Then she must "log-in-with-message-from-preview"

(the name should make clear it is not the "usual login", but a more specific situation).

Now you can describe this 2nd scenario without repeating all the preconditions again:

 Scenario: "log-in-with-message-from-preview"
 Given Dee is at the login
 And she got a message from a preview before
 Then she is taken directly to the specific message shown in the preview

(Disclaimer: I have no experience with BDD so far.)


问:
Converting Fortran 77 code to C#
I'm trying to convert a Fortan77 program to C#. I have a subroutine with about 650 lines of code and horrific GOTO statements all over the place. I'm having a lot of trouble even starting to visualise the flow of the subroutine to figure out what it does.

Is there anybody with experience in this sort of thing who could give me any advice on how to get an overview of this subroutine? Are there some tools available to speed up or facilitate this type of conversion?

答:
To convert any old FORTRAN code to a new language somebody should go through some basic steps in your legacy code
 (1) for static type checking convert the code to "IMPLICIT NONE"
 (2) convert all truncated common to full common
 (3) Remove equivalence
 (4) convert common to Module of FORTRAN 90

Then you can try to convert to other languages.

Title: Converting Fortran 77 code to C#


问:
Why don't we see (more) widespread adoption of lock-free dynamic memory allocators?
In a multithreaded programming environment, lock contention on the heap is often enough a performance bottleneck.

Theoretically at least, the cream-of-the-crop solution for this problem is to have the scalable/parallel[izing] allocator be entirely lock-free. However, it seems to me that besides a few research papers (e.g. [1][2][5]), which do contain promising experimental results, entirely lock-free allocators haven't trickled down to production environments. I'd be glad if you could prove me wrong with counter-examples though. So what are the practical reasons for this slow (or non-existent) adoption of lock-free allocators? Note that more widely used scalable allocators like the one from Intel's TBB are not lock-free although they use fine-grained locks (cf p. 315 in [3]).

For what's worth, I also found a CMU student project/paper[4], claiming to have implemented a lock-free allocator that is "slightly better than [Google's] tcmalloc" on up to 64-cores. Another interesting point in that paper is that "llalloc in these tests is Lockless Inc.'s LockLess allocator, which isn't 100% lockfree (it has a lock around the global heap)". jemalloc and ptmalloc are also benchmarked in there.

References:

[1] Michael, Maged M. "Scalable lock-free dynamic memory allocation." ACM Sigplan Notices 39.6 (2004): 35-46. I found an independent [re]implementation of Michael's algorithm at http://people.cs.vt.edu/~scschnei/streamflow/

[2] Huang, Xiaohuang, et al. "Xmalloc: A scalable lock-free dynamic memory allocator for many-core machines." Computer and Information Technology (CIT), 2010 IEEE 10th International Conference on. IEEE, 2010. Free version of the paper as MS thesis.

[3] Kukanov, Alexey, and Michael J. Voss. "The Foundations for Scalable Multi-core Software in Intel Threading Building Blocks." Intel Technology Journal 11.4 (2007).

[4] Alex Podolsky, Nah Lock: A Lock-Free Memory Allocator; apparently written in 2013 based on parent directory timestamps and the "S13" suffix in the course name.

[5] Gidenstam, Anders, Marina Papatriantafilou, and Philippas Tsigas. "NBmalloc: Allocating memory in a lock-free manner." Algorithmica 58.2 (2010): 304-338. Source code available for this one.

As a footnote, I see there are 4 pending close votes for this question, but I see none for Why have hardware-accelerated vector graphics not taken off?. It would be interesting if someone could explain why a question that could potentially be answered by somewhat objective performance numbers is more opinion based than one where the main factor is the market orientation of 2-3 big companies.

答:
Here are some possible answers:

IBM has patented their lock-free allocator... But then they also support Linux etc., so they might have an incentive to at least provide an implementation. And the XMalloc guys also filed for a patent on theirs. But I haven't [yet] found any patents (or patent applications) for NBmalloc.

A more a localized issue is that M. Michael appears to have ceased publishing at IBM right after that paper. I'm not sure if he's still with IBM, but having him leave or switch focus might be a reason why IBM didn't try to productize his allocator, as IBM did with prior Watson/Watson2 allocators that made it into AIX. The other lock-free allocators don't seem to have connections with a big company that could push them into a product.

Finally, a more general reason would be the relative ratio of code complexity vs. performance benefits. Quoting from "Proving That Non-Blocking Algorithms Don’t Block"
by A. Gotsman et al.

Non-blocking data structures are generally much more complex than their lock-based counterparts, but can provide better performance in the presence of high contention between threads.

So, the code complexity would have to be justified by significant payoffs in performance. While some lock-free allocator papers have claimed these... other papers have come up with contrary or wish-wash results. In particular, the Streamflow paper, whose authors reimplemented Michael's algorithm, claim to have beaten it soundly using an allocator that wasn't lock-free. Podolsky's course paper came up only with relatively marginal improvements. So I'm guessing the jury is still out if the lock-free allocators are worth the extra effort.


问:
Kernel mode web servers: A clever optimization or a security nightmare?
I was reading a Hacker News thread where one user posts a link from 2011 explaining that IIS is much faster than most other (*nix) web servers. Another user replies, explaining that IIS gets that advantage by having a kernel module called HTTP.sys. To my knowledge, most other popular web servers in 2015 do not do this.

I would never want to write a kernel mode web server, because I could never trust myself to make it free of security exploits (which would be less serious running in a lower protection ring).

From the perspective of the software engineer (as opposed to a customer for web servers), is running in kernel mode a smart performance decision? Can security concerns be mitigated in application development to the point of making a kernel mode server a net profit for the consumer?

答:
Http.sys is not so much a web server as a proxy-forwarder. Its designed to allow many web servers co-exist on a Windows box, so you can have IIS running a web site, but also several WCF services running with http/REST or SOAP interfaces, all on standard port 80. (this is why you can't run Apache on Windows without a bit of jiggling, Apache hasn't been modified to work with this registration system, shame it wasn't made more transparent to applications and require some quite complex modifications to hook into it).

The way it works is that you register a URL with it and the corresponding application, ans when a http request is made on port 80, http.sys accepts it but then passes the request on to whichever application is registered to handle that URL target.

I doubt a kernel mode webserver makes any sense - even if socket performance can be improved in this way, in order to perform any useful work, the application logic is still going to be executed in user space, so there's always a transition - you've just shifted it along the callstack a little.


答: How do you know that lock-free allocators / deallocators are not used? For example, take malloc on MacOS X and iOS. Do you know it's lock free or not? (Their documentation says that calling malloc and free on the same thread in short sequence is very fast, and that's the case that you worry about). </p>

Title: Why don't we see (more) widespread adoption of lock-free dynamic memory allocators?

Body:
In a multithreaded programming environment, lock contention on the heap is often enough a performance bottleneck.

Theoretically at least, the cream-of-the-crop solution for this problem is to have the scalable/parallel[izing] allocator be entirely lock-free. However, it seems to me that besides a few research papers (e.g. [1][2][5]), which do contain promising experimental results, entirely lock-free allocators haven't trickled down to production environments. I'd be glad if you could prove me wrong with counter-examples though. So what are the practical reasons for this slow (or non-existent) adoption of lock-free allocators? Note that more widely used scalable allocators like the one from Intel's TBB are not lock-free although they use fine-grained locks (cf p. 315 in [3]).

For what's worth, I also found a CMU student project/paper[4], claiming to have implemented a lock-free allocator that is "slightly better than [Google's] tcmalloc" on up to 64-cores. Another interesting point in that paper is that "llalloc in these tests is Lockless Inc.'s LockLess allocator, which isn't 100% lockfree (it has a lock around the global heap)". jemalloc and ptmalloc are also benchmarked in there.

References:

[1] Michael, Maged M. "Scalable lock-free dynamic memory allocation." ACM Sigplan Notices 39.6 (2004): 35-46. I found an independent [re]implementation of Michael's algorithm at http://people.cs.vt.edu/~scschnei/streamflow/

[2] Huang, Xiaohuang, et al. "Xmalloc: A scalable lock-free dynamic memory allocator for many-core machines." Computer and Information Technology (CIT), 2010 IEEE 10th International Conference on. IEEE, 2010. Free version of the paper as MS thesis.

[3] Kukanov, Alexey, and Michael J. Voss. "The Foundations for Scalable Multi-core Software in Intel Threading Building Blocks." Intel Technology Journal 11.4 (2007).

[4] Alex Podolsky, Nah Lock: A Lock-Free Memory Allocator; apparently written in 2013 based on parent directory timestamps and the "S13" suffix in the course name.

[5] Gidenstam, Anders, Marina Papatriantafilou, and Philippas Tsigas. "NBmalloc: Allocating memory in a lock-free manner." Algorithmica 58.2 (2010): 304-338. Source code available for this one.

As a footnote, I see there are 4 pending close votes for this question, but I see none for Why have hardware-accelerated vector graphics not taken off?. It would be interesting if someone could explain why a question that could potentially be answered by somewhat objective performance numbers is more opinion based than one where the main factor is the market orientation of 2-3 big companies.


答:
Http.sys is not the only kernel-mode web server available: under Linux there is also tux. As you have correctly identified, security is a concern with these kinds of servers, which has lead to tux not being included in the mainline linux kernel (and I believe not updated for more recent kernel versions).

A better solution would be the use of an operating system that does not rely on hardware protection to enforce process security, e.g. Microsoft's singularity: such a system would allow the efficiency gains of a kernel mode server without the security risks. Unfortunately, no production ready operating systems based on this principle are available as of 2015, and AFAIK nobody is seriously working on one either (the Singularity project was canceled).

Title: Kernel mode web servers: A clever optimization or a security nightmare?

Body:
I was reading a Hacker News thread where one user posts a link from 2011 explaining that IIS is much faster than most other (*nix) web servers. Another user replies, explaining that IIS gets that advantage by having a kernel module called HTTP.sys. To my knowledge, most other popular web servers in 2015 do not do this.

I would never want to write a kernel mode web server, because I could never trust myself to make it free of security exploits (which would be less serious running in a lower protection ring).

From the perspective of the software engineer (as opposed to a customer for web servers), is running in kernel mode a smart performance decision? Can security concerns be mitigated in application development to the point of making a kernel mode server a net profit for the consumer?


问:
What type of neural network is suitable for simulating brain of virtual organism?
A while ago I was experimenting with evolving virtual creatures using neural network + genetic algorithm, but that didnt go well (simulation speed was too slow, mainly because bad programming habbits of creatures, not neural network).
I used Feedforward neural network and now I can see it isnt exactly right choice for this kind of application (creatures have no memory, etc.)

I would like to try again, start from scratch, and I would like to perform better than before. However, I dont know what neural network architecture to select.

What I need:

Possibility of memory: Should I study more about memory cells, or is using correct NN architecture (like Reccurent NN) enough? What will be main differencies?

Possibility of mutations: I would like to not only mutate weihts in network, but also possibility of adding weights / neurons into "black box". I plan to use genetic algorithm, so cross mutations + random mutations.

Easy programming: I plan on not using any assets and to write my NN from ground in order to learn. I would preffer more easy neural networks than others. (While Im writing this, I realize there might not be difference)

What I dont need:

Quick computation: I think that 90% of CPU time will be used on other things of controling my creatures, than on computing NN. (as I am terrible programmer)

Training: I will use genetic algorithm to train, so I dont need typical training methods to train NN. I can use types of NN where training part is very CPU intense, as I will drop this part out.

I am looking at possible types of NN and I think some type of Recurrent network would be suitable, but cant really pick a winner, since I only ever worked with Feedforward type, and I will need to learn about the type you will reccomend before I start writing it. I would like to learn just the one you will suggest instead of learn pros/cons of all, since I think It would set me back for too long.

The task for is to surive. I dont have any objective aside than observing interesting patterns of behaviour that can evolve. Basically I would like to "seed" the world with some properties with creatures that can exploit those (food, temperature, danger) and such. Everything very basically modeled, in flat 2D.

Question is:
What is the type of NN that you think would suit this best?

答:
What you are looking for is Neuro Evolution. According to this paper you could be in a position to create a trainable feed forward Neural Network (some extra information might also be found here).

My recommendation would be to start small, maybe first start by making your character move and stop in the presence of danger. Neural networks can be rather difficult to debug, so start slowly to make sure that you have a solid base.


问:
In 'branch by abstraction', how would one do code review?
My manager recommended I consider the technique of 'branching by abstraction', in which, rather than creating feature branches, multiple developers work in the same version control branch, and abstract the functionality they are working on e.g. using feature toggles.

I'm sceptical about this approach, but feel obliged to consider with at least a semblance of fairness. One of my major concerns regards code review. The developers in my team use pull requests to review each other's code. Without branches, this approach would be unavailable.

My question is, if one were to apply this technique, how could code review be accomplished (easily)?

答:
Our team uses the Gerrit code review system, where reviews are based on commits, instead of branches. The learning curve of Gerrit is higher than pull requests, but it creates a much cleaner commit history and allows for fine-grained commenting on code.

Our local repositories still contain branches, but 95% of our commits end up directly on the 'develop' branch.

For larger features, where considerate change in database structure or impactful refactors are necessary, we still use feature branches.


问:
How do you take advantage of your whiteboard in your development team?
Today we got our own website design. The theme is the "whiteboard".

I'm a big fan of them. I would like you to share with me how you use it. I'm sure I don't exploit its potential enough.

I will really enjoy answers that will come with pictures of your own whiteboard as an illustration ;)

I use it as an information radiator to support a light version of scrum.

How do you use this essential development tool?

Please note that I'm also interested in people using a virtual whiteboard or even big touchscreen whiteboard emulator.

答:
1. Big ones to scribble out design ideas

Whenever our team has a meeting we break out the big whiteboard and pens and start sketching out our thoughts. We don't use any formal notation (UML on a whiteboard?!), just intuitive scribbles that help people less familiar with the work rapidly grasp what we're talking about.

2. Medium ones to keep track of tasks

Each team has a whiteboard at the end of their group of desks (pod). This is used to stick user story cards on a grid to show progress (sort of Scrum-Ban or Kan-Rum). As other team members stroll on by they can see what we're working on and often suggest commonality that can be brought in from other projects. Several times we've been stopped from re-implementing code that has already been written for something else but not widely disseminated.

Having the white boards available was an immediate hit with the teams and has definitely helped us to communicate more effectively with each other.

3. A single big one with the overall server map

We run a fairly large collection of clustered servers covering many application tiers, and having a whiteboard dedicated to showing the server and application interlinks is very handy, especially as it's near the water cooler. It gets regularly updated with changes to application deployments (version numbers etc) and helps us all to keep in touch in a way that wouldn't be as effective through a wiki or email.

Sorry no picture available.


答:
You are actually testing two requirements here:

A user who is not logged in should log in when swiping a message preview

When swiping a message preview, the user should be taken directly to the message

If I was testing this, I would perform the first test as part of a login-feature (which groups the different login/logout scenario's)

```<code> Scenario: Log in an unauthenticated user opening the application
 Scenario: Log in an unauthenticated user swiping a preview
 Scenario: Log in an unauthenticated user tapping a notification in the bar
 add more here...
</code>```

And I would test the message preview scenario without dealing with the login or the notification (the origin of the notification, push message, is irrelevant here)

```<code> Scenario: Take user directly to their message on swipe
 Given Dee receives a message preview on her locked phone screen
 When she swipes the preview
 Then she is taken directly to the specific message shown in the preview
</code>```

This strips both features down to their essentials.

Title: How handle a chain of Whens or Thens in a Scenario?

Body:
I am trying to figure out how to write BDD scenario where it seems like I need a chain of "Then" conditions.  How do I write it?  As one scenario?  As two scenarios?

Here is how I've written as one scenario:

```<code>Scenario: Take user directly to their message on swipe after login
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in
And she is taken directly to the specific message shown in the preview
</code>```

It's the last two lines I'm unsure of.  What I'm trying to say she is taken directly to the specific message shown in the preview should not occur until after she must log in.  They should not co-occur, which is what I suspect an Then containing an And probably means.

Should I separate it into two scenarios like this:

```<code>Scenario: Make user login after swipe
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in

Scenario: Take user to message after logging in
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
And she has swiped the preview
When she logs in
Then she is taken directly to the specific message shown in the preview
</code>```

Thanks in advance for your help.

Body:
You are actually testing two requirements here:

A user who is not logged in should log in when swiping a message preview

When swiping a message preview, the user should be taken directly to the message

If I was testing this, I would perform the first test as part of a login-feature (which groups the different login/logout scenario's)

 Scenario: Log in an unauthenticated user opening the application
 Scenario: Log in an unauthenticated user swiping a preview
 Scenario: Log in an unauthenticated user tapping a notification in the bar
 add more here...

And I would test the message preview scenario without dealing with the login or the notification (the origin of the notification, push message, is irrelevant here)

 Scenario: Take user directly to their message on swipe
 Given Dee receives a message preview on her locked phone screen
 When she swipes the preview
 Then she is taken directly to the specific message shown in the preview

This strips both features down to their essentials.


问:
Best approach to develop / distribute proprietary module
I've been brainstorming for a while regarding the best approach to distribute closed-source modules. I'd like to mention that I have found similar question(s) on SE sites but don't think this is exactly the same scenario.

Let's say I wrote a set of well-tested PHP classes which I used as a core for multiple projects (copyright is mine). It has EntityManager, ACL, ORM, Configurable Cacheing, Action logging Admin panel functionalities etc which can be very handy in any database driven projects. (Let's not start argument regarding the integrity of the project itself ;)

My plan is to implement SAAS with the current set of functionalities, but the problem is most of the people I discussed would like it hosted in their servers and wouldn't mind paying a small recurrent loyalty fee. That leads to the ultimate question of choosing the best way of distributing such module / micro-framework.

I found following options to consider:

PHP Extension:
First solution that'll come to anyone's head is to develop and distribute as a standard php extension (Which will check for valid license-code in the cache once in a while and a cronjob will update license from license server periodically). I checked php-cpp.com regarding this and it seemed pretty impressing. One major difficulty is that the extension should be able to talk to mysql / redis etc (based on the configs passed to instantiate the object) by itself. At the moment, current php classes utilise MySQL and PHPRedis extension. I'd like to be able to add Mongodb, Cassandra/ElasticSearch functionality in near future. I'm not sure how it could be achieved. If anyone can possibly shed a light about how an extension can perform mySQL query internally that would be a great help.

Zephir:
I've seen some performance benchmark and Phalcon is one of the top competitors. The major advantage for me is that Zephir is php-like and it'll take considerably less time than writing C++ extension. But looking at the discussion boards, it appears that Zephir is a bit undercooked. By the time it'll be ready for production, php itself will introduce PHP7/NG. Also, same difficulty in the extension writing is present here.

HHVM:
Arguably, the best solution as it converts everything to byte-code and I wont't have to worry about the extension-difficulty here. But I have a new problem: I won't be able to allow users to attach their function (anonymous function) to the events triggered in my module (e.g: OnDuplicate() or OnPost()).

Any idea, resource or comment is greatly appreciated. Thanks.

答:
I honestly think you need to give up on not distributing code in your case. Closed source does not mean you don't/can't distribute code, it means that they are not allowed to distribute it.

I think you should really evaluate your goals. If you want to stop people from looking at your code, then use an obfuscateor, if you want to bill per install then use a licence checker of some kind. If you can't trust your clients, then get new clients.

Besides (and I mean this in a nice way), your code is "worthless" in this type of scenario, it's your idea and implementation that has value. Even if someone never gets your source code, they can just copy the idea.


答:
Http.sys is low risk, as it can’t run any code provided by a third-party.

Http.sys does a few tasks:

It acts as a proxy-forwarder, so allowing multiple processes to respond to request to different parts of the HTTP name space. @gbjbaanb's answer covers this well.

It serves static files, directly from the Windows files cache.   This provides a great speedup for small files static files, as there are no context switches.

It will cache the output from any application it forward a HTTP request to, and return the cashed result.    The application is in complete control over how long (if any) the caching lasts.

Http.sys is designed to do the simple tasks VERY fast, while passing everything else to a process in user space.

In response to the comment

"low risk, as it can’t run any code provided by a 3rd party" - That's
what they always say, and it's almost never true.

The issue is that you must trust Microsoft to write complex kernel code to be asking this question, otherwise you decide not to use Windows for web hosting at all.     Http.sys adds very little to the risk of kernel bugs, given how complex the kernel is anyway.

If anything Http.sys reduces the risk, as there is such a clear separation below “low level” web serving and application code.

In a well designed setup, the machine (or virtual server) that runs the web server has very limited access to the rest of the network, as it is a high risk target.    It makes very little different if the kernel or a user mode web server is hacked, as the server should not have any more “rights” on the network, then the web-server user mode process needs to do its work.

ContentLicense: CC BY-SA 4.0


问:
Understanding the concept of "arguments" and "parameters"
In the third last paragraph at page number 26 of the ebook "The C Programming Language" the author(s) say,

"We will generally use parameter for a variable named in the parenthesized list in a function. The terms formal argument and actual argument are sometimes used for the same distinction."

And in the hard copy of the book that I am having, on the second last paragraph of page number 25 the author(s) say,

"We will generally use parameter for a variable named in the parenthesized list in a function definition, and argument for the value used in a call of the function. The terms formal argument and actual argument are sometimes used for the same distinction."

If I understand it correctly, it means whatever the value(or variable) is used in the call of a function, that is called argument. And whatever is written in the paranthesis of the definition of a function, that is called parameter. E.g. in the following code:

```<code>#include<stdio.h>

int func(int j)
{
    return j;
}

main()
{
    int k=5;
    printf("The argument = %d", func(k));
}
</code>```

the parameters are declared by the line int func(int j). The argument given, through which main() and func(int j) communicate is k.

Now, on the page number 30 of the book(both, the ebook and the hard copy) the authors state,

"main and getline communicate through a pair of arguments and a returned value. In
  getline, the arguments are declared by the line

int getline(char s[], int lim);"

As I understand, char s[] and int lim are parameters, because they are written in the definition of the function getline, not in the call of that function, so my question is,

Why have the authors used the word argument in the second paragraph of page number 30?

答:
The term "argument" is often used rather loosely to refer to either actual arguments or formal arguments without giving the actual or formal adjective. Most often, the context makes it clear if actual arguments or formal arguments/parameters is meant.

In this case, it should be clear that the authors meant formal arguments or parameters. As to why they didn't use parameters is pure speculation. It can be a simple oversight or a deliberate choice because it made the text flow better.


问:
Where should I put (wrapper) scripts in my source tree?
I have this software package which installs itself to /usr/local/mypackge, with a bunch of subdirs. In bin/ I have linked code, as ELF executables, in /share/doc I have documents, etc. Now suppose I've written some wrapper script(s) calling binaries from bin/, and I want it to be part of the package. Where should it be placed?

On typical Linux systems, you find shell scripts in /usr/bin and /usr/sbin, same as the actual linked binaries - should I do the same? Should I create a scripts/ subdir? Something else?

答:
On a typical Linux system, there are two kinds of scripts:

Scripts that are meant to be regularly used by the end-user. For these scripts it is customary that you can't easily tell if you are invoking a script or a ELF executable. They are located in the /bin, /usr/bin or /usr/local/bin folders and don't have an extension to their name, just like all executables.

Internal scripts for a larger package. These scripts are typically not meant to be used by the end-user, so they are located outside the typical paths with executables, often in /var/lib/<package>.

Where to install your scripts depends on the category that they fall in.


答:
First, let's recap:

"parameter = the variable's name"

"argument = the expression we pass to the function"

Note too that "argument" isn't the variable's name. Therefore, it is everything else. Figuratively speaking, you can think of "argument" as a pipe/line. A line that connects the text in the source code holding the "actual argument" with the text in the source code naming the "formal argument".

This pipe has a type. It represent a C cast. A cast is defined by the source type and the destination type.

When they tell you that "the arguments are declared by the line int getline(char s[], int lim)" they tell you that here's the definition of the pipe (which is "argument"): its target type is "char []" (and source type can be anything).

Title: Understanding the concept of "arguments" and "parameters"

Body:
In the third last paragraph at page number 26 of the ebook "The C Programming Language" the author(s) say,

"We will generally use parameter for a variable named in the parenthesized list in a function. The terms formal argument and actual argument are sometimes used for the same distinction."

And in the hard copy of the book that I am having, on the second last paragraph of page number 25 the author(s) say,

"We will generally use parameter for a variable named in the parenthesized list in a function definition, and argument for the value used in a call of the function. The terms formal argument and actual argument are sometimes used for the same distinction."

If I understand it correctly, it means whatever the value(or variable) is used in the call of a function, that is called argument. And whatever is written in the paranthesis of the definition of a function, that is called parameter. E.g. in the following code:

```<code>#include<stdio.h>

int func(int j)
{
    return j;
}

main()
{
    int k=5;
    printf("The argument = %d", func(k));
}
</code>```

the parameters are declared by the line int func(int j). The argument given, through which main() and func(int j) communicate is k.

Now, on the page number 30 of the book(both, the ebook and the hard copy) the authors state,

"main and getline communicate through a pair of arguments and a returned value. In
  getline, the arguments are declared by the line

int getline(char s[], int lim);"

As I understand, char s[] and int lim are parameters, because they are written in the definition of the function getline, not in the call of that function, so my question is,

Why have the authors used the word argument in the second paragraph of page number 30?


答:
English (and I presume other languages as well) has a lot of words which can be used in a generic sense, but are no longer correct in a context which requires more distinction.  For example, you can use the word "goose" to refer to a goose of any gender or age when speaking in the more common generic sense, but if a distinction must be made, a male goose is properly called a gander, and a baby goose is properly called a gosling.

"Argument" and "parameter" are two such words.  You can use "argument" in a more loose context to refer to either an argument or a parameter, but in certain circumstances it's helpful to be able to distinguish between them precisely.  Those circumstances are rare enough that many programmers don't learn the distinction for years, if ever.

Don't ask me why English is that way.  It wasn't designed for ease of parsing.


问:
Mathematically correct A* heuristic / distance estimator for a latitude / longitude graph
I have a graph in which each node is a geographical point on the surface of the earth, defined by it's latitude / longitude coordinates.

Correct ways to calculate the distance between two such points could be the Haversine Formula for spherical earth models, or Vincenty's inverse problem for spheroidal earth models.

But these are very costly in terms of computational resources, and in A* basically you don't need the absolute values of those results, you only need them for comparison purposes.

In my A* algorithm the heuristic function is the shortest distance between 2 points (defined as the length of the smaller great circle arc between the 2 points in a spherical model), and the actual path between two nodes is a linestring, whose length is calculated basically in the same way, just that you sum distances between consecutive vertices.

So, if d(A, B) is the actual geographical distance between A and B (as latitude / longitude points), the problem basically is to find the most computationally efficient distance estimator d*(A, B) that satisfies conditions needed for A* to work properly, such as:

if d(A, B) < d(C, D) then d*(A, B) < d*(C, D).

if d(A, B) + d(E, F) < d(C, D) then d*(A, B) + d*(E, F) < d*(C, D)

I even saw in some places that people recommend Euclidean distance for such a case, even though latitude / longitude are angles. It may be the case, but I'm interested if it's "mathematically correct" to assume that it satisfies conditions such as above.

答:
If the area where the nodes can be is small (relatively, the size of half the US is small enough) and away from the poles then you can reasonably approach the problem using just the longitude and latitude as X/Y coordinates. Near the poles you can treat them as polar coordinates with the 90°-latitude as the distance from center and the longitude as the angle from the x-axis.

If you are working across the globe you can transform the lat/lon into a point on a 3D unit sphere, then take the euclidean distance between them. The length of the chord between the 2 points. (2 sin and cos for each coordinate (precomputed), plus a square root). This is however poorly conditioned when the points are close together. Another option instead of the euclid distance is to get the dot product between them and find the acos of it. This will result in the angle between the points.


问:
Do web applications use HTTP as a transport layer, or do they count as an integral part of the HTTP server?
Given an HTTP server (e.g. Apache, IIS) and a web application (user code running in the server using PHP, ASP.NET and the likes), which of those can decide which HTTP status code to return for any request?

Or rather, is a "web application" to be interpreted as an integral part of "server" as used in the HTTP RFCs? The latter (RFC 7230) is pretty short on that:

An HTTP "server" is a program that accepts connections in order to service HTTP requests by sending HTTP responses.

Since the actual response is generated by a web application (excluding static resources), I'd say the web application is actual part of the server.

However, apart from the eternal "which HTTP status code to use in [arbitrary situation]?" discussions, there also is the discussion "Should web applications even use HTTP status codes?", which I'd like a normative answer to.

See for example the Google Maps REST API. They return 200 for every repsonse, which can be interpreted as "The request ended up at the HTTP server, so that part went OK (200)". Any application error that happens that is returned in the message body as a JSON status, up till the point of NOT_FOUND.

Is this correct? Shouldn't a request for GET /Clients/123 return a 404 when that client doesn't exist? Then what about GET /clients.php?id=123, assuming clients.php exists?

Or does 404 really and only mean "I don't know what you're trying to do, but I'm not going to serve you a resource as there is no resource at (a part of) that URI", "resource" meaning "a (routed) file or directory", which should only be returned by the server when someone forgot to deploy the ClientService application?

Do status code only work for the HTTP part of things, or is a web application part of the server, allowing it to utilize the appropriate status codes where they fit, using HTTP status codes as API response codes?

答:
404 means "the resource you asked for doesn't exist."  It's up to the server to decide when that response is appropriate.  Google has apparently interpreted it to mean "your API request was malformed."  Other REST APIs might also interpret it to mean "your request was well-formed, but you are asking for something which does not exist."  This is why you need to read the API docs.

The "server," in turn, is (as your RFC quote indicates) anything that responds to HTTP requests appropriately.  If you build a server out of a gigantic web application framework, that's your business.  The only requirement is that the client gets the semantically-correct response in any given situation.  It will often be the case that the web application is better suited to make that decision than (say) Apache's out-of-the-box behavior, but you can and should set this up in whatever way makes the most sense for your situation.


问:
Injecting dependencies (DI) in c++ applications
I am playing with dependency injection, but i am not sure I am doing it right.
Especially, I am not sure what should be the correct way to build classes with injected dependencies.

Say I have a class A that creates class B. Class B depends on class C and class C depends on class D. Who should be responsible for creating class D?

It could be class A. However, in a large system, class A might end up creating and assembling a very large number of objects.

A separate builder class that will create D, C and B. A will use this builder class.

Some other option.

In addition, I read a lot about DI containers. However, it seems that there are no major frameworks for C++. Also, if I understand correctly, DI can be performed well even without containers. Am I correct?

答:
There is a DI framework for C++ (still under development AFAIK): Boost.DI.

There are some useful comments about the framework on reddit.


问:
Do I need use really INNER JOIN?
Imagine a coiffeur, with his services:

```<code>+----+-----------------+--------+
| id |      name       | amount |
+----+-----------------+--------+
|  1 | hair cut        |     40 |
|  2 | shampoo         |     10 |
|  3 | french manicure |     90 |
+----+-----------------+--------+
</code>```

Imagine a table of transactions:

```<code>+----+------------+------------------+
| id | id_service | date_transaction |
+----+------------+------------------+
|  1 |          1 | 01/01/2015       |
|  2 |          1 | 02/01/2015       |
|  3 |          1 | 02/01/2015       |
|  4 |          2 | 02/01/2015       |
|  5 |          2 | 02/01/2015       |
|  6 |          1 | 06/01/2015       |
|  7 |          1 | 06/01/2015       |
|  8 |          3 | 06/01/2015       |
|  9 |          2 | 06/01/2015       |
| 10 |          2 | 10/01/2015       |
| 11 |          1 | 10/01/2015       |
| 12 |          3 | 10/01/2015       |
| 13 |          1 | 10/01/2015       |
| 14 |          2 | 10/01/2015       |
| 15 |          2 | 11/01/2015       |
| 16 |          1 | 16/01/2015       |
+----+------------+------------------+
</code>```

With a simple INNER JOIN we can read, for example, the SUM of a specific day.

But our coiffeur is no technology addicted and tomorrow he will change every service.

So, to prevent this drama, how I must setup my webapp?

1) I repeat service.name and amount.name every time in the table of transactions? So, I don't use the INNER JOIN?

1a) I could lose also the possibility to GROUP BY, without numerics ID. And I cannot use them from service table because service change (or, worst) is deleted...

2) I need to block the user to edit/delete his service(s)?

3) What your consideration?

答:
The question should not be whether or not you need to use inner joins.

The design is flawed. The flaw is that the transaction entity is missing a property, i.e., your transaction table is missing a column to record the amount of the operation. The other flaw is that the "amount" of a service is really its "price".

Add an amount column to the transaction table.

Rename the amount column in the service table to price.

When a transaction is added, you set the amount to the corresponding price value.

User should be allowed to change the price of any service at any time

User should only be allowed to change the name of a service if it has no transactions.

Uses should only be allowed to delete a service if it has no transactions.

Changes in service prices don't affect the amount of old transactions.

Title: Do I need use really INNER JOIN?


问:
Participants in Agile retrospective
Who should be the participants in retrospective? Will it be only the team members OR should the Product manager, all the stakeholders and dependent teams also participate.

I am of the opinion that only the team should meet to discuss in retrospectives, else all team members will not open up. But one of the managers insist that all the stake holders should also be included.

答:
There is no hard and fast rule on who to invite to the retrospective. The right answer will almost certainly change on a retrospective-by-retrospective basis. The right answer also depends on many things:

The relationship between the PO and the team

The relationship between stakeholders and the PO

The relationship between your manager and your team

The current issues that the team faces (are they more technical or more business-oriented?)

And any number of other potential things (sorry to be vague...)

As the facilitator of the Retrospective, it is up to your Scrum Master to structure the Retrospective such that it will lead to continuous improvement. If that means involving key stakeholders, then those stakeholders should be invited. If that means a closed door session for just the core team, then the retrospective should be closed to external participants.

Since Scrum Masters have no hard power, a good Scrum Master would understand the need to seek input from the team, the manager, the PO, and relevant stakeholders in order to build consensus on who to invite each time. A good Scrum Master would build a positive relationship with your manager such that the manager will eventually understand why this flexibility is so important.

OwnerDisplayName: Sushma R

Title: Participants in Agile retrospective


问:
How useful are IT headhunters/recruiters when looking for a new job?
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?

答:
I think they can be helpful, but you have to be aware that their job isn't to find a good place for you, it's to sell you on a place that hired them to find people.

I haven't dealt with many recruiters in my career (yet?) but the ones I did come across were fairly non-technical and were just parroting vague job description details to me and making promises about the high salary potential. So I'd say it's pretty hit or miss. I wouldn't ignore recruiters and headhunters entirely -- you never know when a good opportunity might present itself -- but I would definitely be careful to not fall for the optimistic job descriptions.


问:
Story points for bug fixing tasks: Is it suitable for Scrum?
I'm just wondering if we should assign story points to bug fixing tasks or not. JIRA, our issues-tracking software, does not have story point field for Bug type issues (it's only for Storys and Epics).

Should we add the Bug issue type to the applicable issue types of the Story Points field?  What are the pros and cons? Would it be suitable for Scrum?

答:
I have to disagree with the top answer of assigning story points to bugs. Story points should be for new value being delivered. If you are going to assign points to product value and non-value items, you might as well just estimate and track hours.

Bugs are the overhead of what you did yesterday and is not indicative of the velocity of product completion, and they don't create any new product value either (think about it). Bugs are kind of like interrupts and all the other cow pies you need to deal with on a weekly basis. The whole idea of story points is that it tracks/estimates when we will deliver the product (or feature set). Story points are arbitrary and that's how it removes all the non-value overhead from estimation. Generally the non-value work is constant week-to-week, so it is built into the team velocity. The team will accelerate when they remove or reduce this non-value work.

Put another way, why even track points to bugs? So that at the end of the day you know how much "work" each member did? Stop that! Bad manager! :)  Measure the team, not the player. Encourage the team to manage themselves if one person is not pulling their weight. Much more effective. Doing story point items should not make an individual feel better, but the team as a whole should feel better when they make their commitment at the end of the sprint. In sports, is the goal good for the team or the individual? If the individual plays for himself the team loses in the long run.

You know, eventually you want not to use points at all. Estimation is time taken away from real work. When a team reaches maximum chi they don't use points at all yet know exactly how many items they can pull into a sprint. They've mastered the art of breaking up units of work that estimation is process waste.


问:
How to use OO Design to Refactor a Library with Functions that are specific Product-aware
I have a class that acts as a library of functions for various products.  To compute its data, the function currently needs to be aware of all product names.  Depending on which product calls the function, it returns product-specific answers.

The codebase is convoluted enough to where classes are tied to each other in round-about ways and are messy and have no clear immediately-recognizable structure.  So I am refactoring often without a specific purpose in mind, but in this case I want to refactor to

reduce the library's need to rely on product knowledge

maybe I can clean up the code enough to where I can possibly use polymorphism - instantiate a specific product and then have a generic-looking codeblock call product-specific functions

Whether I need to do this type of refactoring, I don't know, as afterall "Things work fine now", except that they are hard to follow and bugs are hard to track down.  Nevertheless, my goal and my question is to "remove reliance on specific product knowledge from calcVar function".

Question:  How do I remove product awareness from calcVar() function below.

Working Example Below:

class Product{}

class Graph{}

class ProductA extends Product
{
    public $calc;

    public function __construct() {
        $this->calc = new CalcLibrary();
        $this->calc->spec->product = "A";
    }
}

class GraphB extends Graph
{
    public $calc;

    public function __construct()    {
        $this->calc = new CalcLibrary();
        $this->calc->spec->product = "B";
    }
}

class Specs
{
    public $var;
    public $product;

    //loads different specs based on product name
    function __construct() {
        if ($this->product == "A") $this->var = 3;
        if ($this->product == "B") $this->var = 4;
        $this->var = 5;
    }
}

class CalcLibrary
{
    public $spec;

    public function __construct() {
        $this->spec = new Specs();
    }

    //problem - library holding formulas for "Var" is product-aware
    //loads different formulas based on product name
    public function calcVar() {
        if ($this->spec->product == "A")
        {
            //somewhat different formulas for different products
            if ($this->spec->var <= 5) return 3 * $this->spec->var;
            else return 0;
        }
        if ($this->spec->product == "B")
        {
            if ($this->spec->var == 0) return 16;
            else return 2 * $this->spec->var;
        }
        return $this->spec->var;
    }

    public function output() {
        echo $this->calcVar() . "\n";
    }
}

// tests should output 15, 10, and 5
(new ProductA())->calc->output();
(new GraphB())->calc->output();
(new CalcLibrary())->output();
```

My Thoughts On Solution

Solution Attempt 1
At first solution was easy I thought -- when I was not aware of family of Graph classes

move calcVar() from CalcLibary into Product class

get rid of if/then/else statements and leave the generic version of calcVar() inside Product class, but move specific ones into ProductA/B/C (classes that extend Product)

and all was well until I found out the hard way that there is a group of classes called GraphA/B/C, which also use CalcLibrary.

Solution 1 Recovery Attempt

Natural solution was to copy CalcVar() into Graph and specialize basically use the same approach as with Product.  But, then the Problem is that I will have multiple CalcVar() functions, generic ones in Product, and in Graph, and specialized ones in each of their subclasses.  As in a problem of duplication, when right now I don't have duplication of calcVar().  I didn't want to trade one problem for another.

Solution 2 Idea

Another way was to make CalcLibrary the top class, and have Graph and Product classes extend CalcLibrary, have CalcLibrary contain calcVar, as it did before, but now CalcLibrary will only have the generic version of calcVar, and then have individual ProductA/B/C and GraphA/B/C classes have product-specific calcVar() versions.  This seems like a good solution as it removes reliance on product knowledge and it takes care of duplication.  But I am not 100% sure that extending this library is a good idea.  It is not really a library, if I don't want it to be.  It's a custom class, so I can make it whatever I need it to be.

Solution 3 Sketch

Maybe all I need is to come up with a better name, so instead of CalcLibrary use ClassThatContainsVariousFunctionsUsefulToGraphAndProductClasses, and then use solution #2.  Maybe later through refactoring I will see clearly enough into my codebase to see a better fit of classes (find a better design), but what are your thoughts now, on refactoring this particular example with my needs in mind? Is "Solution 2" what I should go for?  Since it's not as easy to just move CalcLibrary to the top, with all of its other functions and various other side-effects, maybe I can create a new class with calcVar function there, and then have Product and Graph extend that new class, leave CalcLibrary alone, and remove unused parts of it as I move things into that new class I've created...

Final Thoughts

Because otherwise, I fail to see a way for Plot classes and Graph classes to use functions inside CalcLibrary, without moving those functions inside the respective product-specific classes somehow.  (I mean other than CalcLibrary is being used now, being in a separate class, but with the price of being product-aware)

ALso, ... my 3rd solution sketch with creating Graph/Product extends NewCalcType feels (maybe right) but kind of esoteric.... as in I do not see a meaning other than making existing situation work with an OO design.  I mean another idea is to dismantle the class completely and have each class do their own calcVar computations directly inside the classes.  There will be lots of duplication, but it will feel more "natural".....

答:
Somewhere in your code you have to store the specifics of each product. In your example, the natural place for this seems to be the Specs class, since I guess it is something like the "configuration" of your library. I would extend that class, for example, by an attribute "calcFactor", so your calcVar function will look like this:

```<code>public function calcVar()    {
    return $this->spec->calcFactor * $this->spec->var;
}
</code>```

What you need is a factory for creating Spec objects for each product, something like

```<code>class SpecFactory
{
    public function CreateSpec(productName) {
        spec = new Specs();
        spec->product=productName;
        if (productName == "A")
        {
            spec->calcFactor= 3;
            // ... more parameters for product A here
        }
        else (productName == "B")
        {
            spec->calcFactor= 2;
            // ... more parameters for product B here
        }
        else
        {
           spec->calcFactor= 1; // default
        }
        return spec;
    }
</code>```

then your final code will look like this:

```<code>class ProductA extends Product
{
    public $calc;

    public function __construct() {
        spec = SpecFactory->CreateSpec("A");  // sets spec->calcFactor to 3
        $this->calc = new CalcLibrary(spec);
    }
}
</code>```

or

```<code>class GraphB extends Graph
{
    public $calc;

    public function __construct()    {
        spec = SpecFactory->CreateSpec("A");  // sets spec->calcFactor to 2
        $this->calc = new CalcLibrary(spec);
    }
}
</code>```

The code of your factory will be fairly simple, it will contain the one and only "switch" between different products in your whole program. Your library then gets the spec "injected" (simple dependency injection), and whenever there is something product specific, it will consult the spec to provide the parameters. The spec parameters may be more complicated, maybe a polymorphic object with a derivation for each product, to support more complex scenarios. You probably know already how this is called: it is the well known strategy pattern. As a "lightweight" form of the strategy pattern, you could also try if simple "function objects" suits your needs (AFAIK PHP supports this kind of functional stuff).

In fact, how your spec class has to look like might be different in reality. I don't know how it looks like today, maybe it contains a lot of product independent stuff, if that's the case you might separate the product specific configuration and the product independent configuration into separate "specs" classes, but I hope you get the general idea: separate all product specific things into one piece of configuration which is simple and easy to handle, and let the library use that configuration.

Body:
Somewhere in your code you have to store the specifics of each product. In your example, the natural place for this seems to be the Specs class, since I guess it is something like the "configuration" of your library. I would extend that class, for example, by an attribute "calcFactor", so your calcVar function will look like this:

public function calcVar()    {
    return $this->spec->calcFactor * $this->spec->var;
}

What you need is a factory for creating Spec objects for each product, something like

class SpecFactory
{
    public function CreateSpec(productName) {
        spec = new Specs();
        spec->product=productName;
        if (productName == "A")
        {
            spec->calcFactor= 3;
            // ... more parameters for product A here
        }
        else (productName == "B")
        {
            spec->calcFactor= 2;
            // ... more parameters for product B here
        }
        else
        {
           spec->calcFactor= 1; // default
        }
        return spec;
    }

then your final code will look like this:

class ProductA extends Product
{
    public $calc;

    public function __construct() {
        spec = SpecFactory->CreateSpec("A");  // sets spec->calcFactor to 3
        $this->calc = new CalcLibrary(spec);
    }
}

or

class GraphB extends Graph
{
    public $calc;

    public function __construct()    {
        spec = SpecFactory->CreateSpec("A");  // sets spec->calcFactor to 2
        $this->calc = new CalcLibrary(spec);
    }
}

The code of your factory will be fairly simple, it will contain the one and only "switch" between different products in your whole program. Your library then gets the spec "injected" (simple dependency injection), and whenever there is something product specific, it will consult the spec to provide the parameters. The spec parameters may be more complicated, maybe a polymorphic object with a derivation for each product, to support more complex scenarios. You probably know already how this is called: it is the well known strategy pattern. As a "lightweight" form of the strategy pattern, you could also try if simple "function objects" suits your needs (AFAIK PHP supports this kind of functional stuff).

In fact, how your spec class has to look like might be different in reality. I don't know how it looks like today, maybe it contains a lot of product independent stuff, if that's the case you might separate the product specific configuration and the product independent configuration into separate "specs" classes, but I hope you get the general idea: separate all product specific things into one piece of configuration which is simple and easy to handle, and let the library use that configuration.


问:
How handle a chain of Whens or Thens in a Scenario?
I am trying to figure out how to write BDD scenario where it seems like I need a chain of "Then" conditions.  How do I write it?  As one scenario?  As two scenarios?

Here is how I've written as one scenario:

```<code>Scenario: Take user directly to their message on swipe after login
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in
And she is taken directly to the specific message shown in the preview
</code>```

It's the last two lines I'm unsure of.  What I'm trying to say she is taken directly to the specific message shown in the preview should not occur until after she must log in.  They should not co-occur, which is what I suspect an Then containing an And probably means.

Should I separate it into two scenarios like this:

```<code>Scenario: Make user login after swipe
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in

Scenario: Take user to message after logging in
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
And she has swiped the preview
When she logs in
Then she is taken directly to the specific message shown in the preview
</code>```

Thanks in advance for your help.

答:
To build on the other answers, you could break this down into smaller tests that depend on one another.

Given Dee has received a push notification

This seems to go against the nature of given since receiving is a user interaction. You could write it like this:

Given Dee is sent a push notification

And the first test would be:

```<code>Given Dee is sent a push notification
When she receives the notification
Then the message preview appears on her locked phone screen
</code>```

A second test relies on the first test as a precondition:

```<code>Given she is logged out of Uluvit
When she swipes the preview
Then she is taken to the login screen
</code>```

A third test relies on the second test as a precondition:

```<code>When she logs in
Then she is taken directly to the message shown in the preview
</code>```

There is also an implicit fourth test that relies on the first, but not the second or third:

```<code>Given she is logged in to Uluvit
When she swipes the preview
Then she is taken directly to the message shown in the preview
</code>```

How you rig these tests up to each other will depend on the framework you use. Some frameworks allow nested sections, where the entire scenario is run once for each leaf section, so the entire thing could be written like:

```<code>Scenario: Take user directly to their message on swipe

1.  Given Dee is sent a push notification
    When she receives the notification
    Then the message preview appears on her locked phone screen

    2.  Given she is logged out of Uluvit
        When she swipes the preview
        Then she is taken to the login screen

        3.  When she logs in
            Then she is taken directly to the message shown in the preview

    4.  Given she is logged in to Uluvit
        When she swipes the preview
        Then she is taken directly to the message shown in the preview
</code>```

...and the execution order would be 1, 2, 3 and then 1, 4.

Body:
To build on the other answers, you could break this down into smaller tests that depend on one another.

Given Dee has received a push notification

This seems to go against the nature of given since receiving is a user interaction. You could write it like this:

Given Dee is sent a push notification

And the first test would be:

Given Dee is sent a push notification
When she receives the notification
Then the message preview appears on her locked phone screen

A second test relies on the first test as a precondition:

Given she is logged out of Uluvit
When she swipes the preview
Then she is taken to the login screen

A third test relies on the second test as a precondition:

When she logs in
Then she is taken directly to the message shown in the preview

There is also an implicit fourth test that relies on the first, but not the second or third:

Given she is logged in to Uluvit
When she swipes the preview
Then she is taken directly to the message shown in the preview

How you rig these tests up to each other will depend on the framework you use. Some frameworks allow nested sections, where the entire scenario is run once for each leaf section, so the entire thing could be written like:

Scenario: Take user directly to their message on swipe

1.  Given Dee is sent a push notification
    When she receives the notification
    Then the message preview appears on her locked phone screen

    2.  Given she is logged out of Uluvit
        When she swipes the preview
        Then she is taken to the login screen

        3.  When she logs in
            Then she is taken directly to the message shown in the preview

    4.  Given she is logged in to Uluvit
        When she swipes the preview
        Then she is taken directly to the message shown in the preview

...and the execution order would be 1, 2, 3 and then 1, 4.


问:
How can I program the script on my server to the receive a cname pointed to it?
I am in the final stages of creating a mobile responsive customer relations management platform. Presently it is written in php as a stand-alone self-installing script.

I would like, however, to convert it to being hosted on my server where the client points their domain to my server via the use of the cname and their site is dynamically renders from my server.

Making the conversion to dynamically generate their site is not the issue. My problem lies in how to set up the script on my server to receive the incoming cname showing their domain in the address bar.

The GoMobi platform is an example of what I mean. All sites point to the same url on the GoMobi site, yet the the client's domain/subdomain is rendered.

I am familiar with how to point a cname but as stated not sure how to receive it. I have searched for the answer but the serps always return how to point and not how to receive.

Any assistance with either the solution or a link to the solution is greatly appreciated.

Thanks, Pete

答: The web server sees http requests not any of the dns voodoo involved so it is just a name based virual host like the examples provided at http://httpd.apache.org/docs/2.2/vhosts/examples.html</p>


问:
Using streams to connect programming languages
I'm trying to run a computation-heavy program that creates an image on a website. Is it possible to compute in C++ and have an output stream that connects to an input stream in Node.js to display an image, or alternatively, stream is to the user and display it through JavaScript?

Also, I'm using Monte-Carlo Sampling so the stream would be binary.

答:
Short answer: yes.

A stream in the context of software is simply a sequence of bytes. What those bytes represent is up to you: it could be ASCII text, Unicode characters, a JPEG image, serialized object, anything your heart desires. The important thing is that the producer and consumer of the stream agree on the format.

Furthermore, a stream is not specific to two programs talking to each other. You can use streams inside the same program so two modules can talk to each other in a loosely coupled way.

What you are really looking for is the idea of sockets. A socket is typically used for IPC, or inter-process communication. A high level overview of the process looks like this:

Program A opens a socket to a specific location, normally an IP address and port.

Program B is listening on that IP address and port, and opens the socket on the other end.

Both programs open streams for that socket. Program A can write bytes to its output stream, which show up in Program B's input stream after crossing over the socket. The reverse is also true, allowing bidirectional communication.

When communication is done, one side closes the socket connection.

(If you think about it, this sounds a lot like loading a web page in your browser. This is not coincidental.)

Note that the language, architecture, and physical location of the two programs are not specified. That is the beauty of sockets: they are very low level and simply do not care about those details.

Normally you will use a library to deal with sockets and streams. Some languages have such facilities built-in to the standard libraries, some do not. Regardless, most popular languages will have something available because this is a very common task asked of modern computer systems.


答:
If you want to make sure there is an established list of services (a table to inner join) then you need to manage the changing of this table without breaking your joins for historical records.

Use a soft-delete. Add a field to the list of services called: IsDeleted. Check it off when you no longer offer the service. The ID will remain. I would probably make this a date field to know when the delete occurred for archival purposes.

Use a start date field and an end date field on the service table to indicate when these services were offered. These fields could also be posted for known price changes in the future.

All of this will take more coding to handle the logic of what services are available when.

Title: Do I need use really INNER JOIN?

Body:
Imagine a coiffeur, with his services:

```<code>+----+-----------------+--------+
| id |      name       | amount |
+----+-----------------+--------+
|  1 | hair cut        |     40 |
|  2 | shampoo         |     10 |
|  3 | french manicure |     90 |
+----+-----------------+--------+
</code>```

Imagine a table of transactions:

```<code>+----+------------+------------------+
| id | id_service | date_transaction |
+----+------------+------------------+
|  1 |          1 | 01/01/2015       |
|  2 |          1 | 02/01/2015       |
|  3 |          1 | 02/01/2015       |
|  4 |          2 | 02/01/2015       |
|  5 |          2 | 02/01/2015       |
|  6 |          1 | 06/01/2015       |
|  7 |          1 | 06/01/2015       |
|  8 |          3 | 06/01/2015       |
|  9 |          2 | 06/01/2015       |
| 10 |          2 | 10/01/2015       |
| 11 |          1 | 10/01/2015       |
| 12 |          3 | 10/01/2015       |
| 13 |          1 | 10/01/2015       |
| 14 |          2 | 10/01/2015       |
| 15 |          2 | 11/01/2015       |
| 16 |          1 | 16/01/2015       |
+----+------------+------------------+
</code>```

With a simple INNER JOIN we can read, for example, the SUM of a specific day.

But our coiffeur is no technology addicted and tomorrow he will change every service.

So, to prevent this drama, how I must setup my webapp?

1) I repeat service.name and amount.name every time in the table of transactions? So, I don't use the INNER JOIN?

1a) I could lose also the possibility to GROUP BY, without numerics ID. And I cannot use them from service table because service change (or, worst) is deleted...

2) I need to block the user to edit/delete his service(s)?

3) What your consideration?


问:
SASS placeholders to avoid repeated rules in CSS output
I've got a question for all the frontend guys here. First of all, this is not about placeholders vs mixins as I've already have an idea about, whether to use one or another.

So the question is - do you use SASS placeholders with just one, or perhaps two rules to avoid multiple occurrences in the resulting CSS output?

As an example consider a page, where you need to float many, many, many different elements to the left. Would it be a good idea to create a placeholder with just "float: left" and extend it as needed? That would result in one "float: left" declaration for multiple selectors in the CSS output, instead of being declared all over again for each selector. I could give more situations, for example equal margins/paddings for many elements and so on.
It's not about using variables as that would also result in redeclaration for each selector. It's also not about avoiding "classitis". It's about declaring a rule all over again in the compiled CSS. And, if in the future you would need to add some clearing or just about anything to all floated elements, you could just change the placeholder

Here's a code example (please don't mind the naming, it's just for illustrational purposes):

```<code>// Placeholders
%left {
  float: left;
}

%margin {
  margin: 20px;
}

// Selectors, which use the defined placeholders
.selector-1 {
  @extend %left;
  @extend %margin;
  // Other rules
}

.selector-2 {
  @extend %left;
  // Other rules
}

.selector-n {
  @extend %left;
  @extend %margin;
  // Other rules
}
</code>```

Resulting in the following CSS:

```<code>.selector-1,
.selector-2,
.selector-n {
  float: left;
}

.selector-1,
.selector-n {
  margin: 20px;
}

.selector-1 {
  // Other rules
}

.selector-2 {
  // Other rules
}

.selector-n {
  // Other rules
}
</code>```

Instead of:

```<code>.selector-1 {
  float: left;
  margin: 20px;
  // Other rules
}

.selector-2 {
  float: left;
  // Other rules
}

.selector-n {
  float: left;
  margin: 20px;
  // Other rules
}
</code>```

Would it have an impact on the page performance? Would it lead to more messy and hard to manage code? What would be your approach on this?

I'm definitely not looking for a specific and final answer. Just rather some thoughts, insights and personal experience.

答:
This is a very interesting question and I am very interested in what others think as well.  I have been using sass for a while now and for the most part I tend not to use the @extend functionality at all.  In the case of float left or right everywhere I would probably just make a class .float-left and just add it to the markup that needs to be floated or just have float:left in the selector's rule.

As far as code quality is concerned when you have just one rule in the thing you are extending you aren't really gaining any maintainability.  When it comes to 2 or more rules in an extend that should help from a maintainability aspect.  On the flip side you can still just add both selectors to the markup, I don't have a strong opinion on which is better.

```<code>.float-left-pad {
   float:left;
   padding: 5px;
}

.selector1 {
   @extend:.float-left-pad
   ..
}

div.selector1
</code>```

vs

```<code>.selector1 {
  ...
}

div.selector1.float-lef-pad
</code>```

I really have no clue what your code base it but I would be slightly concerned about using @extends to write maintainable terse css.  When I have commonly used values or markup I tend to put them into mixins or variables to promote code over @extends.  This approach tends to work for the projects of the complexity that I work on but that may not be enough for other's cases.  I can see cases where the using @extends will produce more terse code but I think that comes at the expense of complexity of your sass code.

I highly doubt any approach will impact the page's performance to make it an issue and if it does you can address that issue when it becomes one.  No need to be concerned about performance until you start seeing it degrade.

Body:
This is a very interesting question and I am very interested in what others think as well.  I have been using sass for a while now and for the most part I tend not to use the @extend functionality at all.  In the case of float left or right everywhere I would probably just make a class .float-left and just add it to the markup that needs to be floated or just have float:left in the selector's rule.

As far as code quality is concerned when you have just one rule in the thing you are extending you aren't really gaining any maintainability.  When it comes to 2 or more rules in an extend that should help from a maintainability aspect.  On the flip side you can still just add both selectors to the markup, I don't have a strong opinion on which is better.

.float-left-pad {
   float:left;
   padding: 5px;
}

.selector1 {
   @extend:.float-left-pad
   ..
}

div.selector1

vs

.selector1 {
  ...
}

div.selector1.float-lef-pad

I really have no clue what your code base it but I would be slightly concerned about using @extends to write maintainable terse css.  When I have commonly used values or markup I tend to put them into mixins or variables to promote code over @extends.  This approach tends to work for the projects of the complexity that I work on but that may not be enough for other's cases.  I can see cases where the using @extends will produce more terse code but I think that comes at the expense of complexity of your sass code.

I highly doubt any approach will impact the page's performance to make it an issue and if it does you can address that issue when it becomes one.  No need to be concerned about performance until you start seeing it degrade.


问:
Throw exception or let code fail
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

答:
The benefit is that your "custom" exception has an error message that's meaningful to anyone calling this function without knowing how it's implemented (which in the future might be you!).

Granted, in this case they'd probably be able to guess what the "standard" exception meant, but you're still making it clear that they violated your contract, rather than stumbled across some strange bug in your code.

Title: Throw exception or let code fail


问:
Heuristics on when should one subclass and when not
Are there any good tips, when one should subclass and when should not?

It's clear that we should not subclass when

we want to reuse a single method of some class

we override all methods, changing the behavior of superclass completely.

But in real life, it's more difficult to decide. For example, I have a BasicToolbar class, which has several buttons arranged on a panel. There is a second class ExtendedToolbar, which hould

have some additional buttons

change the ordering of all buttons

on condition hide/remove a couple of buttons from parent class

I tend to subclass to reuse those buttons and override ordering/addition logic, but occasional removing of a button of the parent class seem to be against idea of inheritance.

Any opinion is welcome.

答: It depends on the conventions and guidelines for a specific programming language. In C# it is not easy to delegate methods to an inner object (it requires explicit code). So inheritance can be easier. When creating a public .net based API, inheritance is often recommended, to simplify discovery for the API user.</p>


问:
Are there any design pattern to data binding in event driven architecture?
I develop a browser based game with node.js in back and HTML5 canvas in front-end.
It use WebSockets for communication.

My plan is to generate business events in client side, e.g.: "finishJob".
Client will store all relevant information up to date.

client doesn't have to call server every time it need some data e.g: players money

to achieve this, client will subscribe to players channel

every online player has its own channel, like a chat room

every time something happen with a player, its channel fire an event with players new data

In MVC pattern in here the model is Player, the View is the HTML5 Canvas, but i need 2 type of controllers:

controller to handle business events

controller to handle channels and subscribers

My questions: Is this a viable option?
If yes, are there any design pattern similar for this, or any article about this kind of architecture? Are there any naming conventions ("controllers", "handlers", "channels"...)?

答:
Yes

...see the link below for this pattern...

If you're writing an application which uses Peers -- or any complex app which requires robust Object-Networks I would use an Event-Driven Architecture.

Using a Mediator or EventHub (Event-Aggrigator)

The simplest approach would be to implement the Mediator Pattern designed by Addy Osmoni.

This allows you to write something like:

```<code>// core.js
mediator.subscribe('newMemberAdded', function newMemberAddedHandler(id){
    this.membersModule.add(id);
});
</code>```

...

```<code>// membersUI.js
$('#addMember').click(function(){
    ...
    mediator.publish('newMemberAdded', 998);
    ...
});
</code>```

With this, the only Coupling your modules require is a reference to mediator in order to communicate with other modules.

Using a Mediator is very powerful and will make your modules more Liftable (loose coupling), however, there are some conventions you should consider while developing an EDA:

Modules only publish interests -- not Query+Command events

e.g: eventHub.fire('buttonClicked') NOT eventHub.fire('get:membersList', function(){ ... })

Query+Command Channels Are reserved for Core/Facade interaction (see Osmoni's post)

Work-around those Noun-Verb-Adjective channel-names:

e.g: 'log', 'start', 'change', 'notice' all can be seen as a command or something that happend. You can add the ing conjugate to obviate this ('starting')

Listen Before You Speak! -- Otherwise you may miss events

Visit the link above for more

Additionally, you can bind your Mediator to a WebWorker or SharedWorker to share state between browser tabs (etc) and bind your worker to an EventHub on your server for an even cleaner coupling.

I know this post is somewhat ad hoc, but I hope its enough to get you started!

Body:
Yes

...see the link below for this pattern...

If you're writing an application which uses Peers -- or any complex app which requires robust Object-Networks I would use an Event-Driven Architecture.

Using a Mediator or EventHub (Event-Aggrigator)

The simplest approach would be to implement the Mediator Pattern designed by Addy Osmoni.

This allows you to write something like:

// core.js
mediator.subscribe('newMemberAdded', function newMemberAddedHandler(id){
    this.membersModule.add(id);
});

...

// membersUI.js
$('#addMember').click(function(){
    ...
    mediator.publish('newMemberAdded', 998);
    ...
});

With this, the only Coupling your modules require is a reference to mediator in order to communicate with other modules.

Using a Mediator is very powerful and will make your modules more Liftable (loose coupling), however, there are some conventions you should consider while developing an EDA:

Modules only publish interests -- not Query+Command events

e.g: eventHub.fire('buttonClicked') NOT eventHub.fire('get:membersList', function(){ ... })

Query+Command Channels Are reserved for Core/Facade interaction (see Osmoni's post)

Work-around those Noun-Verb-Adjective channel-names:

e.g: 'log', 'start', 'change', 'notice' all can be seen as a command or something that happend. You can add the ing conjugate to obviate this ('starting')

Listen Before You Speak! -- Otherwise you may miss events

Visit the link above for more

Additionally, you can bind your Mediator to a WebWorker or SharedWorker to share state between browser tabs (etc) and bind your worker to an EventHub on your server for an even cleaner coupling.

I know this post is somewhat ad hoc, but I hope its enough to get you started!


问:
Genetic Algorithm's Tournament Selection limit to be selected
I started working again on a Genetic Algorithm and i'm trying a lot of operators and ways of selection. When I made the Tournament Selection , I noticed that it gets really easy to always get the top individuals to be selected, and the small ones get less chances of being selected. I saw some workaround methods like implementing some "selection probability" to the individual that wins the tournament so that if he doesn't go trough the probability it gives chance to the others that lost.

Other method that I read was to give to each individual a limit of how many times he could be selected, but on that document wasn't any way creating this "limit". So I start thinking of using the % that each individual represent's with his fitness. For example:

ind 1 : 10% 'till 100% goes 10x

ind 2 : 40% 'till 100% goes between 2 to 3x

ind 3 : 8%  'till 100% goes between 10 to 12x

ind 4 : 30% 'till 100% goes between 3 to 4x

or using the inverse %

ind 1 could be selected 90% of number of tournaments (or rounds)

ind 2 could be selected 60% ...

ind 3 could be selected 92% ...

ind 4 could be selected 70% ...

This is just quick ideas nothing complex. What I would like to know is if there is any document that i could find that shows some method create this limits or if you know or have any idea/opinion that could improve this.

答:
First there's a couple of things to keep in mind when implementing genetic algorithms :

Just about everything in GAs is arbitrary. Your solution will depend on :

The way your population individuals represent the potential solutions,

The way you mesure the fitness of your individuals,

The way you implement selection and breeding,

The amount of mutation,

The number of generations and the size of your populations,

What other GA concepts you might choose to implement...

All of these are parameters to your implementation. Typically with GAs you are going to implement a solution, test it over several runs and then you'll tweak it plenty of times.

Also consider what is your search space, and what it might look like :

Your search space is a N-dimensional space that defines the universe of all of your potential population. (N being the number of caracteristics defining your individual solutions).

If you think of it in 3 dimensions (to make it simple) then will you have a landscape which is rather flat, or will it look like a hughe mountain, or will it have lots of hills, mountains and valleys ? This is also important when tweaking your implementation.

Now, if you are worried about having some individuals take over the population too fast then you can review your fitness function to lessen the importance of fit individuals. (Your fitness function may be linear, or it could be linear with a max value, or logarithmic, or something else... ). Also you can increase the mutation rate. Also, as you suggest, you could limit the number of times a individual solution will breed. You can also try out different selection mechanisms to see how it goes (fitness proportionate, tournament, etc...)

Just tweak, test and iterate over and over. Typically that's how you'll refine a GA program.

If you give more detail about what you have already implement I'll be glad to give you some further thoughts on it.

Good luck.