答:
To avoid having to enumerate every sequence, it is enough to observe that in any repeated subsequence the first two elements of each occurrence must be the same. In other words, every repeated pair could be the start of a longer repeated subsequence and every number that does not begin a repeated pair could not.

So in your example, the repeated pairs are 3,6 and 6,17. Each of these could start a longer sequence, and nothing else could.

So, start with a pass looking at each pair (N-1) and keep all of those that repeat. This will form a set of clusters of sequence starting points.

Then within each cluster take two sequences at a time and compare how far the match extends. Remember the shortest and longest. You have your answer.

In your example, first try to extend 3,6 for each occurrence. The maximum length is 2. Then try to extend 6,17. The maximum length is 5. Problem solved.

The data structure for recording the clusters is an interesting design point. I would probably use a dictionary keyed on the first two elements of the sequence and containing a list (or vector) of starting points (indexes into the original data).

This is an outline of an algorithm. It should be enough to provide a starting point if you already understand the problem and are a reasonably good programmer. I'm not sure I can provide much more help without actually writing the code.

Title: Smallest and Largest contiguous repeating sub-sequence in a sequence

Body:
I am trying to solve a outdated quiz problem.

I am tasked to find the smallest and largest contiguous sequence of repeating numbers in a larger sequence.
e.g.

```<code>{1,3,6,17,19,3,6,5,4,2,5,6,17,19,3,6,7,5,78,100,101}
</code>```

For the sequence above, the smallest (non-zero element sequence) and largest non extensible sub sequence would be smallest - 3,6 and largest - 6,17,19,3,6

Could not get started with an algorithm. Any help to get me started would be much appreciated.


问:
Is parsing a submitted JSON object safe?
I have a RESTful API, built in NODE.js that does what you would expect it to: consumes data and then makes it accessible. Currently, data being submitted to my server is nested form data:

```<code>data[0][username]=...
data[0][email]=...
data[0][phone]=...
...
data[12][username]=...
data[12][email]=...
data[12][phone]=...
</code>```

or as a query string

```<code>data[0][username]=...&data[0][email]=...&data[0][phone]=...
</code>```

SO when I parse it on the server, I get a JS array of objects with those particular fields. What I am wondering is, is it safe for me accept a string that I can JSON.parse and the process it?

```<code>data=(some stringified json object)
</code>```

I am unsure if it's possible for malicious code or anything to be included in the JSON object that would blow up my server once run through a parser

Thanks.

答:
JSON representation can be dense, certainly denser than a flat list of properties, so memory exhaustion and denial of service may be slightly easier.

Other than that, assuming your JSON parser is bulletproof, you're left with basically the same attacks that can be directed at a form-data or query-string based entry point, primarily various kinds of string injection attacks: SQL injection, client JavaScript injection, and so forth.

ContentLicense: CC BY-SA 3.0


问:
how and should I 'unit test' an entire package?
I'm still learning to be good about doing unit level testing, as I've always been a little sloppy about only doing functional testing in the past, so I want to double check I'm doing this 'right'.

I have a package which is responsible for auto-magically updating a particular configuration which is expected to change regularly during runtime.  Provide a list of objects to monitor to the constructor of my main package class.  Then at some point call update it will go to all the multiple places that define configuration, detect change, update the appropriate state for the objects it's monitoring, and provide a report of what was changed.  This is all automatic and otherwise transparent to all other packages.

My inclination is to test this as a unit, but it is a pretty 'big' unit, 5-6 classes and fetching from multiple files and a restful interface.  It feels like testing any smaller units would take much longer, be less flexible to refactoring and only provide a slightly higher chance of detecting a defect, but that could just be my laziness talking.  Would it be considered 'better' to test at a lower level?

Assuming it is 'right' to test the package as a unit what is considered appropriate for mocking something like this?  There are methods of classes which are instantiated by my main class (ie, not something I pass in directly so I can't just pass my own mock) that have methods I want to control.  I believe I can use powerMock in the two cases I can think of (or could, after I research PowerMock some more), but I'm not sure if doing so is transparent enough.  Is configuring PowerMock to detect and return a mock file object any time my package tries to open a configuration file, even if it's buried deep in my package logic, acceptable, or is this considered to be abusing my knowledge of implementation specific details?  Would it be 'cleaner' to actually modify configuration files on the file system and let them be read normally without further mocking?  I would need to modify the files regularly for testing...

Edit:
To clarify the question of coupling asked in one of the questions, I don't think that my classes are overly coupled.  Effectively I have three classes that fetch state from A, B, and C, and then a 'main' class which takes the state from the three and decides how to combine it correctly (ie, if A and B don't match use A unless C).  I could easily test A B and C separately and then mock them to test my 'main' class.  However, it seems like the testing of my 'main' class would effectively test the comparatively simple interfaces for A, B, and C anyways if I didn't mock them.  Thus it feels like duplicate work to test them individually.  I may get some slightly better code coverage, maybe, with individual testing, and it's always nice to have one test test only one thing.  But I don't know if it's worth all the overhead for minor benefits.

答:
This is a pretty common question to people starting to learn TDD. I don't know if that's your case, but the logic you can follow is the same.

First, forget the word "unit" for a moment. Think about how you would approach the development of the same package from ground zero and test-first. You can't start by testing "a class only" or "a method only" because you have nothing yet, and you don't know all of the classes and methods that will be necessary.

So you start by specifying the first piece of expected behavior in a test, to then make the test pass, all with the minimum amount of code required for the very specific part of the behavior. You repeat this cycle until all behavior is implemented, while refactoring in between cycles.

During refactor, you may split the logic between different classes, and try out design options. The tests will still be running on the "main" class, or the "public API" of your functionality. This is considered the best practice for the same reason you mentioned, to avoid hindering the freedom to refactor your code.

With this cycle in mind, in your specific case, it would hardly be necessary to mock any of your own collaborators. However, you should indeed mock the external dependencies of your code, such as the configuration files and restful services. Mainly because you should be able to test your code without depending on environment factors such as a file existing in a directory, and also you can increase the flexibility of your functionality if you provide an injection point for such dependencies.

PS: I know you're not going to write the code from scratch, but this was an outline of the process you'd have followed with TDD, just to give you an idea of how the tests would look like.

PS2: By "mock" I mean any kind of test double, such as fakes, dummies, stubs, spies and real mocks.


问:
Pros and Cons of RESTful architecture
The most common discussion I've seen regarding the pros and cons of REST tends to frame that discussion relative to SOAP. I have no experience in either. I am currently faced with a decision which my lack of experience is making hard for me to evaluate.
I am beginning to develop an application that has several components - primarily an administrative aspect that allows the owner to administer several sites - and a public facing user interface that allows the user to interact with data held on the host.
I need to evaluate the implications of allowing the latter part to be hosted anywhere and communicate with the former via a RESTful architecture - or demanding that both components reside on the same host.
What are the key implications of developing RESTful architecture, particularly with regards to it's capacity in the following areas:

1: Security
2: Performance
3: Interface complexity

EDIT: Looking at some of the answers to this question - I should clarify. I'm not looking for a comparison to SOAP - rather an overview of REST applications vs applications where all components reside on one host. (thanks for those answers though!)

答:
I think the biggest advantage of REST is to break from RPC architectures.  REST exposes resources, not processes.  That allows you to create a loosely bound system, where changes, improvements, even failures of one part have limited (negative) impact on other parts.

Unfortunately, a common misuse of REST is to expose your inner data structures (in the worst cases, it's a CRUD of your database, ugh).  That makes it very hard to do it safely.  The 'right' use is to expose high level objects that are relevant to the part of the system you're handling, and liberally return error status codes on any inconsistency.

Another often-overlooked part of REST is the idempotency of most verbs.  Not only GET, but also PUT and DELETE should be exactly the same result if applied once or several times (you're free of returning a 404 if already deleted, or 'no change' if the client is PUTting the same).  That leads to robust systems and less interdependency of exact interpretations of the semantics.

ContentLicense: CC BY-SA 2.5

Title: Pros and Cons of RESTful architecture


问:
Classes in OOP , methods and attributes memory internals
I would assume that instances of the same  class would actually share their methods, and just have save different attributes in their namespace. How often do you arbitrary add methods to a single instance?

Yet for example in Python that's not the case. Instances' methods are all different objects. Even if you decorate them as @classmethods, (or use __slots__) they seem to be different objects in memory.

Can someone give me a definition of what I'm describing here, or even given same details on why this model was chosen? What happens in other languages?

答:
The relevant terms here are dynamic and static typing.

With static typing, all the types are fixed and do not change during the execution time of your program. This is what traditional languages like C/Java/etc are doing. The advantage for compiled languages with static typing is that they know, that each object of your class will have the same methods, and as such they are free to optimize with that in mind. In particular, each  method implementation is only stored once in memory and merely the object attributes are stored per individual object. For an object, you just need to store a single pointer to its class' method table.

On the other hand, languages like Python offer dynamic typing, where a type can change during runtime. For example, in Python it is possible to add a method to a class. Once you start modifying the type though, you are no longer guaranteed, that a once compiled version of your method(s) is still valid, so it's more troublesome to store these methods. If your language even allows you to add methods to an object's class per individual object, than no two objects can share their type.

There are still a lot of optimizations possible with dynamic typing, but as a rule of thumb, statically typed languages have a much easier time for optimizing, because they have a lot of guarantees regarding their type system. On the other hand, the programmer is forced to adhere to the type system just as well, in contrast to the freedom of a dynamically typed language. Both sides have advantages and disadvantages, but these are outside of the scope of your question.


问:
How are virtual methods slower in C#?
I read that virtual calls make the code slower than calling non-virtual ones in C#.
However, the IL instruction for both are the same callvirt except in cases where base.somemethod() is called.

So how does virtual method hurt performance?

答:
You are making single mistake : thinking that IL code has effect on performance. The thing is, the machine code compiler can still do tons of optimizations based on the IL code itself. And it sure can differentiate between call of virtual and nonvirtual method, even if they use same opcode. This then results in different machine code and different performance.

Here is simple performance benchmark I did:

```<code>class ClassA
{
    public int Func1(int a)
    {
        return a + 1;
    }

    public virtual int Func2(int a)
    {
        return a + 2;
    }
}

class ClassB : ClassA
{
    public override int Func2(int a)
    {
        return a + 3;
    }
}

class Program
{
    public static void Main()
    {
        int x = 0;
        ClassA a = new ClassA();
        ClassB b = new ClassB();
        ClassA c = new ClassB();

        Stopwatch watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < 10000000; i++)
        {
            x = x + 1; // no function
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = a.Func1(x); // non virtual
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = a.Func2(x); // virtual on a
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = b.Func2(x); // virtual on b
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = c.Func2(x); // virtual on B typed as A
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        System.Console.WriteLine(x); // so the compiler doesn't optimize it away
    }
}
</code>```

When I run it (Release, without debugging, Any CPU, .NET 4.5, x64 Windows 8.1) I get those results:

```<code>9904
8921
56921
60076
58289
</code>```

First interesting thing is that calling the non-virtual method is no different than not using method at all. This clearly shows the compiler is inlining the method's code in place so there is no function call overhead. Second clearly shows that virtual methods don't have this inlining and add need of additional lookup. Making them much slower than non-virtual method calls.

But don't get the wrong idea. In the grand scheme of things, overhead caused by virtual methods is negligible compared to algorithm overhead and cache misses due to memory access.

ContentLicense: CC BY-SA 4.0

Title: How are virtual methods slower in C#?

Body:
You are making single mistake : thinking that IL code has effect on performance. The thing is, the machine code compiler can still do tons of optimizations based on the IL code itself. And it sure can differentiate between call of virtual and nonvirtual method, even if they use same opcode. This then results in different machine code and different performance.

Here is simple performance benchmark I did:

class ClassA
{
    public int Func1(int a)
    {
        return a + 1;
    }

    public virtual int Func2(int a)
    {
        return a + 2;
    }
}

class ClassB : ClassA
{
    public override int Func2(int a)
    {
        return a + 3;
    }
}

class Program
{
    public static void Main()
    {
        int x = 0;
        ClassA a = new ClassA();
        ClassB b = new ClassB();
        ClassA c = new ClassB();

        Stopwatch watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < 10000000; i++)
        {
            x = x + 1; // no function
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = a.Func1(x); // non virtual
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = a.Func2(x); // virtual on a
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = b.Func2(x); // virtual on b
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        watch.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            x = c.Func2(x); // virtual on B typed as A
        }
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);

        System.Console.WriteLine(x); // so the compiler doesn't optimize it away
    }
}

When I run it (Release, without debugging, Any CPU, .NET 4.5, x64 Windows 8.1) I get those results:

9904
8921
56921
60076
58289

First interesting thing is that calling the non-virtual method is no different than not using method at all. This clearly shows the compiler is inlining the method's code in place so there is no function call overhead. Second clearly shows that virtual methods don't have this inlining and add need of additional lookup. Making them much slower than non-virtual method calls.

But don't get the wrong idea. In the grand scheme of things, overhead caused by virtual methods is negligible compared to algorithm overhead and cache misses due to memory access.


问:
When to use custom collections?
I see a lot of APIs that use custom collections instead of just using strongly-typed packaged generics.

For instance, the API will have a Object1Collection instead of just a List<Object1> (or whatever the appropriate generic would be).

When do you know to use one or the other?  I understand you'd create a custom collection if you want to extend the capabilities of a pre-shipped generic collection, but what if that's not the case?

Is it prudent to create the custom collection from the beginning, with thoughts that in the future that object might scale up and require further capabilities, and it may be easier to just do that initially?  Is that justification enough?

And if you just want to extend functionality, instead of define collection functionality, you would just derive your custom collection from a base generic collection class, otherwise inherit the interface accordingly?  Is that typical?

答:
Custom collections don't really make sense for general programming. Thats why List<T> exists. But they sure make lots of sense in domain modelling. For example, you would like to have special behavior that happens when you add a new item into a collection. The best way to do it is to create custom collection class, derive from Collection<T> and overload the Add method.

Also, there is question of what actually is a "custom collection". Is having Add method and implementing IEnumerable<T> enough or does the class have to derive from Collection<T>?

So as Telastyn said. You are generally not going to implement new collections in a way of creating new ways of storing data. That problem has long been solved. But you sure can (and should) create custom collections as a way of expressing domain behavior on those collections.

Title: When to use custom collections?


答:
OOP concepts do not change if you compare them in different programming languages though the way it gets implemented might vary. I have been working on C++ for 2 years and before that I learnt and worked in Java as well.

Here is how you can look at it.

Classes are the blueprints based on which objects are generated. In other words class can be seen as generic logical entities and objects are physical entity. For example: shape is a generic logical entity and circle is a physical entity.

Every class contains data and methods(function) to manipulate that data.
for ex: shape has length, size etc as data and volume(), Area() etc as methods.

Now as far as I understood your question you are asking about how or when methods get differ for different object/instances. (correct me).

Now to answer that we need to understand Polymorphism which is an OOPs concept.
Polymorphism has two variants static and dynamic.
Static polymorphism is implemented through function/method overloading and
Dynamic polymorphism is implemented through function/method overriding.

Static binding:
Multiple methods, same name, same scope, different parameters.
Gets resolved at compile time.

Dynamic binding:
Multiple methods, same name, different scope, same parameters.
Gets resolved at runtime.

Now if two instances(say O1 O2) work in such a way that they eventually call different methods either through static binding or dynamic binding.
That means instance O1 will call different methods when you compare it with O2.

I hope that makes some sense, post doubts if any.

Title: Classes in OOP , methods and attributes memory internals

Body:
I would assume that instances of the same  class would actually share their methods, and just have save different attributes in their namespace. How often do you arbitrary add methods to a single instance?

Yet for example in Python that's not the case. Instances' methods are all different objects. Even if you decorate them as @classmethods, (or use __slots__) they seem to be different objects in memory.

Can someone give me a definition of what I'm describing here, or even given same details on why this model was chosen? What happens in other languages?


问:
Linked list clarification
This is a pretty simple question but I'm new to java.

The linked list found in java.util.LinkedList.

I saw elsewhere that Java does not use pointers...

When I create a new list and add new elements to it, does the list contain references to the data and to the next/previous elements or does it also contain the object itself.

答:
In Java you have primitives (int, long, etc.) and objects. Objects are references (pointers) to complex data.

Java always passes values; so within your list you will have actual values of what you put in. BUT: Since objects are references to data, the values passed will be the references, not the data itself.

Pragmatic result: You put object A in a list and change its data somewhere in your code. Object A will still be in your list (you didn't change A but its data) but the A in your list will reflect the changes you've made somewhere else.

```<code>Car a = new Car();
List myList = new LinkedList();
myList.add(a);
a.driveHome();
Car carFromList = myList.getFirst();
carFromList.isDrivenHome(); // true
</code>```

Title: Linked list clarification

Body:
In Java you have primitives (int, long, etc.) and objects. Objects are references (pointers) to complex data.

Java always passes values; so within your list you will have actual values of what you put in. BUT: Since objects are references to data, the values passed will be the references, not the data itself.

Pragmatic result: You put object A in a list and change its data somewhere in your code. Object A will still be in your list (you didn't change A but its data) but the A in your list will reflect the changes you've made somewhere else.

Car a = new Car();
List myList = new LinkedList();
myList.add(a);
a.driveHome();
Car carFromList = myList.getFirst();
carFromList.isDrivenHome(); // true


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答:
Register Globals in PHP

Information : http://php.net/manual/en/security.globals.php

This is by far the worst feature to be ever implemented for readability reasons and security reasons. Basicly all the GET parameter received are transformed into variables.

For example with this URL : /index.php?value=foobar

You can do the following :

```<code><?php
echo $value; // return foobar
?>
</code>```

When you are reading code, it is very confusing to know where the variable comes from.

Also if the feature is misused, it can lead to security hole. Here's a code example from php.net that shows how it can be misused :

```<code><?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>
</code>```

Body:
Register Globals in PHP

Information : http://php.net/manual/en/security.globals.php

This is by far the worst feature to be ever implemented for readability reasons and security reasons. Basicly all the GET parameter received are transformed into variables.

For example with this URL : /index.php?value=foobar

You can do the following :

<?php
echo $value; // return foobar
?>

When you are reading code, it is very confusing to know where the variable comes from.

Also if the feature is misused, it can lead to security hole. Here's a code example from php.net that shows how it can be misused :

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>


问:
Issue with My.Settings using Visual Basic
For my A2 Computing project I have created a game using Visual Basic. For the leaderboard section, I have used the My.Settings feature to store the scores when the game closes, but only one or two actually save. My teacher doesn't know and I can't find anything helpful after a google search of the problem</p>

答:
You can force a save of the My.Settings object using My.Settings.Save(), however I'd suggest you look into writing a file to disk and using that to store your high scores. It's much better and it's a good opportunity to teach yourself about File I/O.

Here's a good tutorial on how to do that via MSDN: http://msdn.microsoft.com/en-us/library/6ka1wd3w(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1


问:
Dynamically loading MPL library in closed source application
I am dynamically loading an MPL 2.0 licensed library to use some of its exported functions in a feature. My code does not distribute the library, it simply detects it's presence on the system and uses it if it's available.
I also browsed the library's source code to extract the function and certain type definitions.

What ramifications does this have on my software? Do I have to distribute the MPL, open-source  part of my code that uses the mentioned type definitions, do I have to mention something in my EULA, etc.?

答:
From reading the Wikipedia page on the MPL, it seems to me that you can "link from code with a different license". The license is even marked as such in the summary box.

If you read the actual license, in its 2.0 version, section "Distribution of a Larger Work", you can read that you have to keep the library in question under MPL, regardless if you distribute your own software in source or executable form. That is, you may not keep the source code of that library under a closed, proprietary license; but this does not apply at all to your code. This is true even if the MPL code is marked as "Incompatible with secondary licenses", since that would only apply if you were mixing the library's source with your own.

The LGPL provides a similar case, and it states explicitly that:

If you dynamically link against an LGPL'd library already present on the user's computer, you need not convey the library's source. On the other hand, if you yourself convey the executable LGPL'd library along with your application, whether linked with statically or dynamically, you must also convey the library's sources, in one of the ways for which the LGPL provides.

Substitute "convey the library's source" (LGPL) by "create a Larger Work under terms of Your choice" (MPL) and you have your case, I guess.

This is my opinion, but I am not a legal expert. Furthermore, this is under the assumption that when you say you "extracted a function and certain type definitions", you mean that you browsed the library in order to understand how to use it; you did not copy a relevant piece of code and integrated it with your own source code.


答:
Even in languages that allow dynamic modification of a single instance, like Python or Ruby, the code of methods still only exists in memory once. The main difference between those languages and those where a single instance cannot be changed (like Java or C++) is that in the static languages, each instance conceptually holds a single reference to a list of supported functions that is shared between all instances (in concrete implementations this is often called the vtable), whereas in dynamic languages each instance needs its own table. (As an optimization, unmodified instances could share the table and only create their own versions when they get modified.)

In either case, however, those tables will contain references to the code of the actual methods, and that code will be shared. Unless your language is so dynamic that it can modify the actual code at runtime.


问:
Why doesn't MySQL have an explicit "No Limit" option for queries?
I use SQLyog Community edition and like many other SQL applications out there it puts a 1000 result limit on queries that do not have a limit provided.

I am wondering why MySQL doesn't have an explicit NO LIMIT option when it comes to writing queries.

I'm sure that i'm not the only developer that ends up sticking a large limit on the end (within reason) to get a full display view of the records in the table.

Providing the records in the table is sensible i'd like to be able to do:

SELECT * FROM course NO LIMIT; instead of
SELECT * FROM COURSE LIMIT 2500;

答:
The server was probably started with the --safe-updates or --i-am-a-dummy option which causes MySQL to execute

```<code>SET sql_safe_updates=1, sql_select_limit=1000, max_join_size=1000000;
</code>```

on startup.

See the MySQL reference for details.

Body:
The server was probably started with the --safe-updates or --i-am-a-dummy option which causes MySQL to execute

SET sql_safe_updates=1, sql_select_limit=1000, max_join_size=1000000;

on startup.

See the MySQL reference for details.


问:
What is the best practice for arranging third-party library licenses "paperwork"?
I am developing a small open source project. The application uses many third-party libraries released with a range of licenses: Apache, MIT, BSD, LGPL and CDDL.

Each of these licenses has its own “paperwork” requirements. For example, the Apache License, v2.0 says:

If the Work includes a "NOTICE" text file as part of its distribution,
  then any Derivative Works that You distribute must include a readable
  copy of the attribution notices contained within such NOTICE file.

The MIT license contains a copyright notice and says:

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

The BSD license also contains a copyright notice and says:

Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

LGPL v.3 says:

(You should) give prominent notice with each copy of the Combined Work
  that the Library is used in it and that the Library and its use are
  covered by this License.

LGPL and CDDL licenses also require supplying the source code along with a binary form of a library, so the information on the way in which the source code can be obtained should be provided somewhere.

What is the best practice for arranging all this data? Should I create a text file and copy the content of all NOTICE files, MIT and BSD licenses etc. into that file? ... or should I create a separate directory for each library and put all data related to the library to that directory? … or something else?

It would also be interesting to see any examples of this “paperwork” in published projects.

UPDATE:

I have read Do you have to include a license notice with every source file?, but it does not address my problem. My question is about third-party libraries that are used in a project, and that question is about headers in the project's own source code.

答:
First, the standard disclaimer: IANAL but a random stranger.

I have been packaging an AGPL application(*) recently. It uses third party libraries distributed under jQuery, MIT, BSD (and some other) licenses. Here is how I have proceeded.

My main intents when I designed this were: be compliant and be fair. While the first one should be sufficient, the second one ensures that whoever tries to sue me for not getting it 100% right has to admit I have done things in good faith.

1) Source files: all my files have the AGPL header. All 3rd party files are left (mostly) unmodified, and therefore include their own license header.

2) LICENSE.txt, at the root of the package, contains the AGPL license text (as explained in the "How to Apply These Terms to Your New Programs" section).

3) A secondary license file, which I named LICENSE-3RD-PARTY.txt, also located at the root of the package, contains verbatim copies of ALL licenses. For each license, a header states which license it is, and which part it applies to. I also include the name of the copyright holders here - I reuse them somewhere else afterwards so it's worth the effort.

```<code>-----------------------------------------------------------------------------
                        The MIT License (MIT)
        applies to:
        - AJAX Upload, Copyright (c) Andrew Valums
        - jQuery hashchange event, Copyright (c) 2010 "Cowboy" Ben Alman
        - jquery.hotkeys, Copyright (c) 2010 John Resig
-----------------------------------------------------------------------------

Permission is hereby granted, free of charge [...]
</code>```

4) README.txt, also at the root, explains that the software is AGPL (see LICENSE.txt) and uses third party libraries that are distributed under their own terms (see LICENSE-3RD-PARTY.txt)

5) In the on-line documentation, I have a License page that repeats the information from the readme: my software is AGPL, and it uses 3rd party components that are BSD/MIT/[...]. I have decided to keep this page cleaner and more readable, therefore only the name of the license is provided, with a link to the full text, and the name of the copyright holders with a link to their own website.

```<code>jQuery
    Copyright 2013 jQuery Foundation and other contributors
    http://jquery.com
    MIT License
Data Driven Documents (D3)
    Copyright (c) 2013, Michael Bostock    <-- link to personal website, if any
    http://d3js.org                        <-- link to software website
    BSD-like license                       <-- link to license full text
[...]
</code>```

6) Also in the on-line documentation, I have a Credits page, where I list the direct and indirect main contributors. I have for instance cited the PostgreSQL group, although PostgreSQL is not included in the download, but you need it to run the software. This would be a good place to place all acknowledgements that are either required or desired by the authors of 3rd party tools/libraries/etc.

7) Inside the software itself, the list of libraries along with the license and copyright holders, is repeated in the About dialog box.

To address your specific questions regarding inclusion of source code and file layout:

it is generally accepted to only link to the full source code of 3rd party packages. Consult each specific license to be sure, but IMHO providing the link should be enough. For instance, if you use a minified version of a library, you can provide the link to the standard download and be fine.

unless the 3rd party component explicitly demands that distributions keep the file layout identical, you can re-arrange things as you wish. Imagine you use web libraries, having each a css/ and a js/ directory, you can merge them together into a single lib/ directory, containing merged css/ and js/, or even scatter them all around your source tree - your choice.

And as a final note, I would more than welcome commenters who wave a hand saying "you are doing this wrong" and/or "you should also do that".

(*) This is not intended to be spam linking, but just to answer the "please provide examples" part of the question. Feel free, dear mods, to clear this link if this is against the rules.

Body:
First, the standard disclaimer: IANAL but a random stranger.

I have been packaging an AGPL application(*) recently. It uses third party libraries distributed under jQuery, MIT, BSD (and some other) licenses. Here is how I have proceeded.

My main intents when I designed this were: be compliant and be fair. While the first one should be sufficient, the second one ensures that whoever tries to sue me for not getting it 100% right has to admit I have done things in good faith.

1) Source files: all my files have the AGPL header. All 3rd party files are left (mostly) unmodified, and therefore include their own license header.

2) LICENSE.txt, at the root of the package, contains the AGPL license text (as explained in the "How to Apply These Terms to Your New Programs" section).

3) A secondary license file, which I named LICENSE-3RD-PARTY.txt, also located at the root of the package, contains verbatim copies of ALL licenses. For each license, a header states which license it is, and which part it applies to. I also include the name of the copyright holders here - I reuse them somewhere else afterwards so it's worth the effort.

-----------------------------------------------------------------------------
                        The MIT License (MIT)
        applies to:
        - AJAX Upload, Copyright (c) Andrew Valums
        - jQuery hashchange event, Copyright (c) 2010 "Cowboy" Ben Alman
        - jquery.hotkeys, Copyright (c) 2010 John Resig
-----------------------------------------------------------------------------

Permission is hereby granted, free of charge [...]

4) README.txt, also at the root, explains that the software is AGPL (see LICENSE.txt) and uses third party libraries that are distributed under their own terms (see LICENSE-3RD-PARTY.txt)

5) In the on-line documentation, I have a License page that repeats the information from the readme: my software is AGPL, and it uses 3rd party components that are BSD/MIT/[...]. I have decided to keep this page cleaner and more readable, therefore only the name of the license is provided, with a link to the full text, and the name of the copyright holders with a link to their own website.

jQuery
    Copyright 2013 jQuery Foundation and other contributors
    http://jquery.com
    MIT License
Data Driven Documents (D3)
    Copyright (c) 2013, Michael Bostock    <-- link to personal website, if any
    http://d3js.org                        <-- link to software website
    BSD-like license                       <-- link to license full text
[...]

6) Also in the on-line documentation, I have a Credits page, where I list the direct and indirect main contributors. I have for instance cited the PostgreSQL group, although PostgreSQL is not included in the download, but you need it to run the software. This would be a good place to place all acknowledgements that are either required or desired by the authors of 3rd party tools/libraries/etc.

7) Inside the software itself, the list of libraries along with the license and copyright holders, is repeated in the About dialog box.

To address your specific questions regarding inclusion of source code and file layout:

it is generally accepted to only link to the full source code of 3rd party packages. Consult each specific license to be sure, but IMHO providing the link should be enough. For instance, if you use a minified version of a library, you can provide the link to the standard download and be fine.

unless the 3rd party component explicitly demands that distributions keep the file layout identical, you can re-arrange things as you wish. Imagine you use web libraries, having each a css/ and a js/ directory, you can merge them together into a single lib/ directory, containing merged css/ and js/, or even scatter them all around your source tree - your choice.

And as a final note, I would more than welcome commenters who wave a hand saying "you are doing this wrong" and/or "you should also do that".

(*) This is not intended to be spam linking, but just to answer the "please provide examples" part of the question. Feel free, dear mods, to clear this link if this is against the rules.


问:
Zero behavior objects in OOP - my design dilemma
The basic idea behind OOP is that data and behavior (upon that data) are inseparable and they are coupled by the idea of an object of a class. Object have data and methods that work with that (and other data). Obviously by the principles of OOP, objects that are just data (like C structs) are considered an anti-pattern.

So far so good.

The problem is I have noticed that my code seems to be going more and more in the direction of this anti-pattern lately. Seems to me that the more I try to achieve information hiding between classes and loosely coupled designs, the more my classes get to be a mix of pure data no behavior classes and all behavior no data classes.

I generally design classes in a way which minimizes their awareness of other classes' existence and minimizes their knowledge of other classes' interfaces. I especially enforce this in a top-down fashion, lower level classes don't know about higher level classes. E.g.:

Suppose you have a general card game API. You have a class Card. Now this Card class needs to determine visibility to players.

One way is to have boolean isVisible(Player p) on Card class.

Another is to have boolean isVisible(Card c) on Player class.

I dislike the first approach in particular as it grants knowledge about higher level Player class to a lower level Card class.

Instead I opted for the third option where we have a Viewport class which, given a Player and a list of cards determines which cards are visible.

However this approach robs both Card and Player classes of a possible member function. Once you do this for other stuff than visibility of cards, you are left with Card and Player classes which contain purely data as all functionality is implemented in other classes, which are mostly classes with no data, just methods, like the Viewport above.

This is clearly against the principal idea of OOP.

Which is the correct way? How should I go about the task of minimizing class interdependencies and minimizing assumed knowledge and coupling, but without winding up with weird design where all the low level classes contain data only and high level classes contain all the methods? Does anyone have any third solution or perspective on class design which avoids the whole problem?

P.S. Here's another example:

Suppose you have class DocumentId which is immutable, only has a single BigDecimal id member and a getter for this member. Now you need to have a method somewhere, which given a DocumentId returns Document for this id from a database.

Do you:

Add Document getDocument(SqlSession) method to DocumentId class, suddenly introducing knowledge about your persistence ("we're using a database and this query is used to retrieve document by id"), the API used to access DB and the like. Also this class now requires persistence JAR file just to compile.

Add a some other class with method Document getDocument(DocumentId id), leaving DocumentId class as dead, no behavior, struct-like class.

答:
Obviously by the principles of OOP, objects that are just data (like C structs) are considered an anti-pattern.

No, they aren't. Plain-Old-Data objects are a perfectly valid pattern, and I would expect them in any program that deals with data that needs to be persisted or communicated between distinct areas of your program.

While your data-layer might spool up a full Player class when it reads in from the Players table, it could instead just be a general data library that returns a POD with the fields from the table, which it passes to another area of you program which converts a player POD to your concrete Player class.

Use of data objects, either typed or untyped, may not make sense in your program, but that doesn't make them an anti-pattern.  If they make sense, use them, and if they don't, don't.


答:
You are correct that the coupling of data and behaviour is the central idea of OOP, but there's more to it. For example, encapsulation: OOP/modular programming  allow us to separate a public interface from implementation details. In OOP this means that the data should never be publicly accessible, and should only be used via accessors. By this definition, an object without any methods is indeed useless.

A class that offers no methods beyond accessors is essentially an overcomplicated struct. But this isn't bad, because OOP gives you the flexibility to change internal details, which a struct does not. For example, instead of storing a value in a member field, it could be recomputed each time. Or a backing algorithm is changed, and with it the state that has to be kept track of.

While OOP has some clear advantages (esp. over plain procedural programming), it is naive to strive for “pure” OOP. Some problems do not map well to an object oriented approach, and are solved more easily by other paradigms. When encountering such a problem, do not insist on an inferior approach.

Consider calculating the Fibonacci sequence in an object oriented manner. I can't think of a sane way to do that; simple structured programming offers the best solution to this problem.

Your isVisible relation belongs to both classes, or to neither, or actually: to the context. Behaviourless records are typical of a functional or procedural programming approach, which seems to be the best fit to your problem. There is nothing wrong with

```<code>static boolean isVisible(Card c, Player p);
</code>```

and there is nothing wrong with Card having no methods beyond rank and suit accessors.

Title: Zero behavior objects in OOP - my design dilemma

Body:
The basic idea behind OOP is that data and behavior (upon that data) are inseparable and they are coupled by the idea of an object of a class. Object have data and methods that work with that (and other data). Obviously by the principles of OOP, objects that are just data (like C structs) are considered an anti-pattern.

So far so good.

The problem is I have noticed that my code seems to be going more and more in the direction of this anti-pattern lately. Seems to me that the more I try to achieve information hiding between classes and loosely coupled designs, the more my classes get to be a mix of pure data no behavior classes and all behavior no data classes.

I generally design classes in a way which minimizes their awareness of other classes' existence and minimizes their knowledge of other classes' interfaces. I especially enforce this in a top-down fashion, lower level classes don't know about higher level classes. E.g.:

Suppose you have a general card game API. You have a class Card. Now this Card class needs to determine visibility to players.

One way is to have boolean isVisible(Player p) on Card class.

Another is to have boolean isVisible(Card c) on Player class.

I dislike the first approach in particular as it grants knowledge about higher level Player class to a lower level Card class.

Instead I opted for the third option where we have a Viewport class which, given a Player and a list of cards determines which cards are visible.

However this approach robs both Card and Player classes of a possible member function. Once you do this for other stuff than visibility of cards, you are left with Card and Player classes which contain purely data as all functionality is implemented in other classes, which are mostly classes with no data, just methods, like the Viewport above.

This is clearly against the principal idea of OOP.

Which is the correct way? How should I go about the task of minimizing class interdependencies and minimizing assumed knowledge and coupling, but without winding up with weird design where all the low level classes contain data only and high level classes contain all the methods? Does anyone have any third solution or perspective on class design which avoids the whole problem?

P.S. Here's another example:

Suppose you have class DocumentId which is immutable, only has a single BigDecimal id member and a getter for this member. Now you need to have a method somewhere, which given a DocumentId returns Document for this id from a database.

Do you:

Add Document getDocument(SqlSession) method to DocumentId class, suddenly introducing knowledge about your persistence ("we're using a database and this query is used to retrieve document by id"), the API used to access DB and the like. Also this class now requires persistence JAR file just to compile.

Add a some other class with method Document getDocument(DocumentId id), leaving DocumentId class as dead, no behavior, struct-like class.

Body:
You are correct that the coupling of data and behaviour is the central idea of OOP, but there's more to it. For example, encapsulation: OOP/modular programming  allow us to separate a public interface from implementation details. In OOP this means that the data should never be publicly accessible, and should only be used via accessors. By this definition, an object without any methods is indeed useless.

A class that offers no methods beyond accessors is essentially an overcomplicated struct. But this isn't bad, because OOP gives you the flexibility to change internal details, which a struct does not. For example, instead of storing a value in a member field, it could be recomputed each time. Or a backing algorithm is changed, and with it the state that has to be kept track of.

While OOP has some clear advantages (esp. over plain procedural programming), it is naive to strive for “pure” OOP. Some problems do not map well to an object oriented approach, and are solved more easily by other paradigms. When encountering such a problem, do not insist on an inferior approach.

Consider calculating the Fibonacci sequence in an object oriented manner. I can't think of a sane way to do that; simple structured programming offers the best solution to this problem.

Your isVisible relation belongs to both classes, or to neither, or actually: to the context. Behaviourless records are typical of a functional or procedural programming approach, which seems to be the best fit to your problem. There is nothing wrong with

static boolean isVisible(Card c, Player p);

and there is nothing wrong with Card having no methods beyond rank and suit accessors.


答:
What you describe is known as an anemic domain model. As with many OOP design principles (like Law of Demeter etc.), it's not worth bending over backwards just to satisfy a rule.

Nothing wrong about having bags of values, as long as they don't clutter the entire landscape and don't rely on other objects to do the housekeeping they could be doing for themselves.

It would certainly be a code smell if you had a separate class just for modifying properties of Card - if it could be reasonably expected to take care of them on its own.

But is it really a job of a Card to know which Player it is visible to?

And why implement Card.isVisibleTo(Player p), but not Player.isVisibleTo(Card c)? Or vice versa?

Yes, you can try to come up with some sort of a rule for that as you did - like Player being more high level than a Card (?) - but it's not that straightforward to guess and I'll have to look in more than one place to find the method.

Over time it can lead to a rotten design compromise of implementing isVisibleTo on both Card and Player class, which I believe is a no-no. Why so? Because I already imagine the shameful day when player1.isVisibleTo(card1) will return a different value than card1.isVisibleTo(player1). I think - it's subjective - this should be made impossible by design.

Mutual visibility of cards and players should better be governed by some sort of a context object - be it Viewport, Deal or Game.

It's not equal to having global functions. After all, there may be many concurrent games. Note that the same card can be used simultaneously on many tables. Shall we create many Card instances for each ace of spade?

I might still implement isVisibleTo on Card, but pass a context object to it and make Card delegate the query. Program to interface to avoid high coupling.

As for your second example - if the document ID consists only of a BigDecimal, why create a wrapper class for it at all?

I'd say all you need is a DocumentRepository.getDocument(BigDecimal documentID);

By the way, while absent from Java, there are structs in C#.

See

http://msdn.microsoft.com/en-us/library/ah19swz4.aspx

http://msdn.microsoft.com/en-us/library/0taef578.aspx

for reference. It's a highly object-oriented language, but noone makes a big deal out of it.


答:
The basic idea behind OOP is that data and behavior (upon that data) are inseparable and they are coupled by the idea of an object of a class. Object have data and methods that work with that (and other data). Obviously by the principles of OOP, objects that are just data (like C structs) are considered an anti-pattern. (...) This is clearly against the principal idea of OOP.

This is a tough question because it's based on quite a few faulty premises:

The idea that OOP is the only valid way to write code.

The idea that OOP is a well-defined concept. It's become such a buzzword that it's hard to find two people that can agree on what OOP is about.

The idea that OOP is about bundling data and behavior.

The idea that everything is/should be an abstraction.

I won't touch upon #1-3 much, because each could spawn their own answer, and it invites a lot of opinion-based discussion. But I find the idea of "OOP is about coupling data and behavior" to be especially troubling. Not only does it lead to #4, it also leads to the idea that everything should be a method.

There's a difference between the operations that define a type, and the ways you can use that type. Being able to retrieve the ith element is essential to the concept of an array, but sorting is just one of the many things I can choose to do with one. Sorting doesn't need to be a method any more than "create a new array containing only the even elements" needs to be.

OOP is about using objects. Objects are just one way of achieving abstraction. Abstraction is a means to avoid unnecessary coupling in your code, not an end all unto itself. If your notion of a card is defined solely by the value of its suite and rank, it's fine to implement it as simple tuple or record. There's no non-essential details that any other part of the code could form a dependency on. Sometimes you just don't have anything to hide.

You wouldn't make isVisible a method of the Card type because being visible is likely not essential to your notion of a card (unless you have very special cards that can turn translucent or opaque...). Should it be a method of the Player type? Well, that's probably not a defining quality of players either. Should it be a part of some Viewport type? Once again that depends on what you define a viewport to be and whether the notion of checking the visibility of cards is integral to defining a viewport.

It's very much possible isVisible should just be a free function.


问:
Preference to see if a field's value was changed js or linq object?
We have some requirements to send emails when various field values are changed in our system.

It's an asp.net system using linq to sql with javascript/jquery.

Is it preferred to check if a value is changed via js (hidden field is set if the value is changed) or is it better since we are using linq and I have access to the object in question to check that object's current value with what the user has entered (basically compare the textbox value with the object's field value before it is being updated)?

答:
My opinion is that it's better to make system behavior decisions server-side (in your case linq).

I like to assume that all of my client code could be hacked by an evil person who is up to no good.  If that code is nothing but presentation, then I'm a little safer.

What would happen if evil client code reported that many fields had changed when they hadn't?


问:
Should performance tests be instrumented by build tools?
Should performance tests be instrumented by build tools as part of the build process, or should they live completely outside? If outside, then where in the deployment pipeline should they live?

I currently see performance tests being attached to integration testing lifecycle phases.  While it's fine for now, I know this doesn't seem quite right, and I'm having difficulty finding an actual answer as to where we should be attaching and running these performance tests.

For the sake of the question, we can assume an environment utilizing Jenkins for CI, and Maven as a build tool. We can also assume a scrum SDLC.

答:
Ask yourself: what kind of performance tests do you have, and how often do you need them to be run?

Tests for the "daily use"? Then make them part of your unit tests.

Just in the QA cycle of every release/deployment? Keep them as part of your integration tests (assumed those tests are run for every release/deployment).

Tests for an isolated part of your application, just needed once for optimizing purposes and then never again? Then keep them out of your CI cycle.

Running time of those tests will probably be a factor. If your performance tests need less than 20 minutes, you won't have much trouble to integrate them into your "nightly builds" on your CI server. If they need a week for a complete run, you obviously need a different strategy.

And to my understanding, using an agile model like "Scrum" means to adapt your process to the software you are building, not vice versa. So no decision of "where to place your performance tests" may be final. If you have tests at the beginning which are very fast, and become slower the more you expand them over time, you may have to relocate them in your process, split them up, change them to your needs etc.


问:
What are the consequences of Hash-Life running in O(log n)?
After reading about the HashLife algorithm, I found that it runs in O(log n). The Game of Life is also Turing Complete, so in theory we should be able to run any algorithm on a "computer" constructed in GoL.

As a consequence of HashLife's time complexity, could algorithms run faster? e.g. if an algorithm takes 10 seconds to run on a pc, could it run faster in HashLife on that same pc?

An example: An algorithm running takes a 1000 instructions to run. A certain computer can process 1 instruction per second. So that algorithm takes a 1000 seconds to run.

Now, if we take that same algorithm and run it on the "computer" in GoL. It would, because of HashLife being O(log n) take 3 seconds? (assuming O(log₁₀n))

I'm probably overlooking something, since this would be a very important discovery, but I still thought I'd ask about it here.

答:
Edit 2

I think looking at the math behind big O will help. I will not really do this here.

Suppose we have n cells in game of life.
Now we implement an algorithm that walks though a list of m elements. This algorithm uses O(m) time. So with the ordinairy GoL implementation this runs in O(n*m). With the more effeicient implementation it needs O(m * log(n)).

Edit 1

algorithms that currently run in e.g. O(n), run in O(log n) instead?

Algorithms do not run. They are a model. Implementations of algorithms run.

I would like the question to be stated more clearly.

Here are thoughts.
There are four cases: (without GoL O(log n)) => (with GoL O(log n))

algorithms O(n) => algorithm O(log n) ? Not possible

implementation O(n) => algorithm O(log n) ? Can exist

implementation O(n) => implementation O(log n) ? Exists (GoL)

algorithm O(n) => implementation O(log n) ? Not possible


问:
How to talk a client out of a Flash website?
I have recently been doing a bunch of web side projects through word of mouth recommendations only.  Although I am much more a of a programmer than a designer by any means, my design skills are not terrible, and do not hate dealing with UI like many programmers.  As a result, I find myself lured into a bunch of side projects where aside from a minimal back end for content administration, most of the programming is on front end interfaces (read javascript/css).

By far the biggest frustration I have had is convincing clients that they do not want Flash.  Aside the fact that I really do not enjoy Flash "development", there are many practical reasons why Flash is not desirable (lack of compatibility across devices, decreased client accessibility, plug-in requirements, increased development time, etc.).  Instead of just flat out telling the clients "I will not build you a flash website", I would much rather use tactics to convince/explain to them that this is not what they actually want, ie: meet their requirements any better than standard html/css/js and distract users from their content.

What kind of first hand experience do others have with this?  How do you explain to someone that javascript/css/AJAX is usually a better option for most websites?  Why do people want to use Flash so bad to begin with?

This question pertains to clients who do not have any technical reasons for wanting flash, but just want it because they think it makes pretty websites.

答: There may also be issues with complying with accessibility legislation e.g. for blind users. I don't know how well screen readers cope with Flash - I don't imagine very well.</p>


问:
Colons in internationalized UI
When using gettext or a similar framework, should the translation strings include ':' (like "Label:") for generating labels for UI or should I add ':' in UI code itself?

答:
For many languages, there is no one-to-one translation from English word and phrases, but multiple translations that are context sensitive.

To make the life of translators easier, you should provide as much context for the strings as possible. That includes colons in labels and contextual information where those labels are being used.

As ground rules, in an internationalized UI you should

not modify translated strings, except to fill in parameters with their actual values. So, don't add the colons after the fact.

not cut strings into parts around parameters. Especially if there are multiple parameters to be filled in, you can be sure that there will be at least one language where it would be more natural to have the parameters the other way around.

be really careful with singular/plural forms. There is no common pattern how to create plurals from singulars, or even how many plural forms there are.

Title: Colons in internationalized UI


答:
Personally I think Domain Driven Design helps to bring clarity to this issue.  The question I ask is,  how do I describe the card game to human beings?  In other words, what am I modeling?  If the thing I'm modeling genuinely includes the word "viewport" and a concept that matches its behavior, then I would create the viewport object and have it do what it logically should.

However if I don't have the concept of the viewport on my game,  and it's something I think I need because otherwise the code "feels wrong". I think twice about adding it my domain model.

The word model means that you are building a representation of something. I caution against putting in a class that represents something abstract beyond the thing that you are representing.

I will edit to add that it's possible that you may need the concept of a Viewport in another part of your code, if you need to interface with a display. But in DDD terms this would be an infrastructure concern and would exist outside of the domain model.


答:
One common source of confusion in OOP stems from the fact that many objects encapsulate two aspects of state: the things they know about, and the things that know about them.  Discussions of objects' state frequently ignore the latter aspect, since in frameworks where object references are promiscuous there is no general way to determine what things might know about any object whose reference has ever been exposed to the outside world.

I would suggest that it would probably be helpful to have a CardEntity object which encapsulates those aspects of the card in separate components.  One component would relate to the markings on the card (E.g. "Diamond King" or "Lava Blast; players have AC-3 chance to dodge, or else take 2D6 damage").  One might relate to a unique aspect of state such as position (e.g. it's in the deck, or in Joe's hand, or on the table in front of Larry).  A third might relate to can see it (perhaps nobody, perhaps one player, or perhaps many players).  To ensure that everything is kept in sync, places where a card might be would not be encapsulated as simple fields, but rather CardSpace objects; to move a card to a space, one would give it a reference to the proper CardSpace object; it would then remove itself from the old space and put itself into the new space).

Explicitly encapsulating "who knows about X" separately from "what X knows" should help avoid a lot of confusion.  Care is sometimes needed to avoid memory leaks, especially with many-many associations (e.g. if new cards can come into existence and old cards disappear, one must ensure that cards which should be abandoned aren't left perpetually attached to any long-lived objects) but if the existence of references to an object will form a relevant part of its state, it's entirely proper for the object itself to explicitly encapsulate such information (even if it delegates to some other class the work of actually managing it).


问:
Utilising Promises, Closures and Recursion in Node.js
I have employed a recursive call to a closure in order to mitigate against some race conditions I am getting (That's what I think it is).
I'd like to know if (and why) this is a good solution or a bad solution.

function getResources(activity, resource) {
    var q = when.defer(),
    resourceQuery = constructSelectionQuery(resource),
    timeoutCounter = 0,
    timeoutLimit = 100;
    function queryDatabase() {
        query.getResult({
            query: resourceQuery
        }, function(err, result) {
            if (result.length === 0) {
                if (timeoutCounter > timeoutLimit) {
                    q.reject();
                }
                timeoutCounter++;

                //subsequent call(s)
                queryDatabase();
            } else {
                q.resolve(result);
            }
        });
    }

    //initial call
    queryDatabase();

    return q.promise;

    }
```

What I am trying to ascertain is the validity of using recursion and closure in this combination - is this an acceptable way of approaching the problem of repeating the call to the database?
Without the repeating of the call the result is sometimes empty. This is curious as this function is only called after the record has been saved. However this is in another system so I am assuming the speed of indexing is at fault in MySQL - I don't want to go into that aspect of the system as I'm happy with what I've got - My question is isolated to using this pattern - a recursive call to the closure as a way to repeat the call.

答:
The nesting is a little hard to read.  If you write it as follows, it's easier to tell what's happening.

function queryDatabase() {
    query.getResult({query: resourceQuery}, queryDone);
}

function queryDone(err, result) {
    if (result.length !== 0) {
        q.resolve(result);
    }
    else if (timeoutCounter++ > timeoutLimit) {
        q.reject();
    }
    else {
        queryDatabase();
    }
}
```

<p>Since <code>query.getResult()</code> is asynchronous (I'm assuming, or else you wouldn't need a promise), that means <code>queryDatabase()</code> will return before <code>queryDone()</code> is called.  When <code>queryDatabase()</code> is called inside <code>queryDone()</code>, it will return, causing <code>queryDone()</code> also to return, before it's called again.  So while it's recursive in a semantic sense, the function calls themselves are never nested.  So you shouldn't have issues like keeping 100 copies of a result object in memory at once.</p>

<p>As far as style goes, I don't see how it could be expressed without recursion without adding complexity.  If this pattern is repeated frequently in your code, you could make a more general solution, used something like:</p>

<pre class="lang-js prettyprint-override"><code>var promise =
  repeatQueryUntil(resourceQuery, function(err, result) {return result.length !== 0;})
</code>```

Body:
The nesting is a little hard to read.  If you write it as follows, it's easier to tell what's happening.

function queryDatabase() {
    query.getResult({query: resourceQuery}, queryDone);
}

function queryDone(err, result) {
    if (result.length !== 0) {
        q.resolve(result);
    }
    else if (timeoutCounter++ > timeoutLimit) {
        q.reject();
    }
    else {
        queryDatabase();
    }
}

Since query.getResult() is asynchronous (I'm assuming, or else you wouldn't need a promise), that means queryDatabase() will return before queryDone() is called.  When queryDatabase() is called inside queryDone(), it will return, causing queryDone() also to return, before it's called again.  So while it's recursive in a semantic sense, the function calls themselves are never nested.  So you shouldn't have issues like keeping 100 copies of a result object in memory at once.

As far as style goes, I don't see how it could be expressed without recursion without adding complexity.  If this pattern is repeated frequently in your code, you could make a more general solution, used something like:

var promise =
  repeatQueryUntil(resourceQuery, function(err, result) {return result.length !== 0;})


问:
Multiple remote views of a C# application
I have a C# application (Desktop based application for Windows OS), which I wanted to use from Web browser.

The application is a kind of analyzing tool, which takes some input values and performs set of calculations over it then displays an animation of the results.

Since the application can't be coded again in a new language, Can anyone suggest me, how I can view and interact with this C# application from browser (like the way we interact with Java Applets)? Also the application can be used by more than one user at a time, so there must be multiple views for this web application.

答:
I have made simple demo about output data from .net program to browser using Scot library. Scot library is wrapper for javascript using only html5 capabilities.

Primary reason to create it was to convert Windows application for web browsers.


答:
The basic idea behind OOP is that data and behavior (upon that data) are inseparable and they are coupled by the idea of an object of a class.

You're making the common error of assuming that classes are a fundamental concept in OOP. Classes are just one particularly popular way of achieving encapsulation. But we can allow that to slide.

Suppose you have a general card game API. You have a class Card. Now this Card class needs to determine visibility to players.

GOOD HEAVENS NO.  When you are playing Bridge do you ask the seven of hearts when it is time to change the dummy's hand from a secret known only to the dummy to being known by all?  Of course not.  That's not a concern of the card at all.

One way is to have boolean isVisible(Player p) on Card class.
  Another is to have boolean isVisible(Card c) on Player class.

Both are horrid; don't do either of those. Neither the player nor the card are responsible for implementing the rules of Bridge!

Instead I opted for the third option where we have a Viewport class which, given a Player and a list of cards determines which cards are visible.

I've never played cards with a "viewport" before, so I have no idea what this class is supposed to encapsulate.  I have played cards with a couple decks of cards, some players, a table, and a copy of Hoyle. Which one of those things does Viewport represent?

However this approach robs both Card and Player classes of a possible member function.

Good!

Once you do this for other stuff than visibility of cards, you are left with Card and Player classes which contain purely data as all functionality is implemented in other classes, which are mostly classes with no data, just methods, like the Viewport above. This is clearly against the principal idea of OOP.

No; the basic idea of OOP is that objects encapsulate their concerns. In your system a card isn't concerned about much. Neither is a player.  This is because you are accurately modeling the world. In the real world, the properties are cards that are relevant to a game are exceedingly simple.  We could replace the pictures on the cards with the numbers from 1 to 52 without much changing the play of the game. We could replace the four people with mannequins labeled North, South, East and West without much changing the play of the game.  Players and cards are the simplest things in the world of card games.  The rules are what is complicated, so the class that represents the rules is where the complication should be.

Now, if one of your players is an AI, then its internal state could be extremely complicated.  But that AI doesn't determine whether it can see a card. The rules determine that.

Here's how I'd design your system.

First off, cards are surprisingly complicated if there are games with more than one deck. You have to consider the question: can players distinguish between two cards of the same rank?  If player one plays one of the seven of hearts, and then some stuff happens, and then player two plays one of the seven of hearts, can player three determine that it was the same seven of hearts? Consider this carefully. But aside from that concern, cards should be very simple; they're just data.

Next, what is the nature of a player? A player consumes a sequence of visible actions and produces an action.

The rules object is what coordinates all of this. The rules produce a sequence of visible actions and inform the players:

Player one, the ten of hearts has been handed to you by player three.

Player two, a card has been handed to player one by player three.

And then asks the player for an action.

Player one, what do you want to do?

Player one says: treble the fromp.

Player one, that is an illegal action because a trebled fromp produces an indefensible gambit.

Player one, what do you want to do?

Player one says: discard the queen of spades.

Player two, player one has discarded the queen of spades.

And so on.

Separate your mechanisms from your policies.  The policies of the game should be encapsulated in a policy object, not in the cards. The cards are just a mechanism.


问:
testing: which code layers should I aim to test?
Say I have this code:

```<code>Design
{
    public function load()
    {
        $this->loadProduct();
        $this->loadService();
        ...
    }

    public function loadProduct()
    {
        try
        {
            $this->product = new Product();
            $this->product->spec = $this->product->loadSpecs($this->a, $this->b, $this->c);
        }
        catch (\BadFunctionCallException $e)
        {
            $this->error = true;
            $this->emsg = $e->getMessage();
        }
    }
}
</code>```

Questions:

Do I test loadProduct function only?

Do I test Product class only?

Do I move loadProduct's code into load (thereby removing loadProduct function from existence, and test the larger load function (as part of Design class)?  Say I may want to do this as part of clean up/reorganization of legacy code.

Something else?

答: You should test sufficiently to provide adequate code coverage. Sufficiently (and adequate) vary on the risk associated with an undetected problem in your code. The cost to fix a problem after development (assuming a classic SDLC) is significantly higher then the cost to fix during development, but the risk may be minimal. So, really that is another way of saying that it depends on your context. Another point to remember is that testing does not "prove" correctness, nor does it "prove" your software is bug-free - all testing can do is provide you with information. For more, I recommend the book "Perfect Software: And Other Illusions about Testing" by G. Weinberg.</p>


问:
Pair Rotation in a team for effective pair programming
We follow pair programming in our company and always face the issue of balanced and effective pair rotation within the developers on stories.

We follow a simple metrics in which every developer's name is mapped with every other developer and we mark the respective intersection whenever two developers are pairing.

This is not working out well, we cannot track how much time a pair has spent pairing and people forget to update the metrics many times. Tracking the pair rotation is helpful because we want the project knowledge to be shared across the team, and not just one pair. So usually what happens is, whoever is pairing keeps pairing till the entire story is completed (given they have better context), and no body else knows about what is being done & if the story or a regression/production bug comes back, the same pair has to pick it up (leaving whatever they are currently doing), which is what creates a bottleneck.

Are there any known metrics that can be used for tracking the pair rotations.

答:
Why do you feel the need to track the amount of time developers have paired with each other?  Is it because you want to remove the bottlenecks that you mentioned or want to share knowledge around the team, or because the code you're releasing to production is buggy?

I'd suggest tracking the things that are important to you and leave it up to the team to workout how best to achieve them.

As an example, track whenever a story has to be assigned to a specific pair and try and bring that number to zero over time.


答:
I don't usually do self-promotion, but the fact is I wrote a lot about OOP design issues on my blog. To sum up several pages: you shouldn't start design with classes. Starting with interfaces or APIs and shape code from there have higher chances to provide meaningful abstractions, fit specifications and avoid bloating concrete classes with non-reusable code.

How this apply to Card-Player problem: Creating a ViewPort abstraction makes sense if you think of Card and Player as being two independent libraries (which would imply Player is sometimes used without Card). However, I'm inclined to think a Player holds Cards and should provide a Collection<Card> getVisibleCards () accessor to them. Both these solutions (ViewPort and mine) are better than providing isVisible as a method of Card or Player, in terms of creating understandable code relationships.

An outside-the-class solution is much, much better for the DocumentId. There is little motivation to make (basically, an integer) depend on a complex database library.


问:
How to handle or prevent all Admins and users being removed
I have a website that stores all users in a database. A user can log on to the website and if they have sufficient privileges can add/delete users, as well as change their privileges.

How do I ensure there is always at least one Administrator (to create/edit/delete users) in the system or that an administrator can easily be added to the system.

Surely I can put rules in place so that the Admin can't delete himself, or other rules like that. But what if someone deletes all the users in the SQL table. The passwords are hashed so it's not as if the DBA can just go in and add a new user with Admin rights.

Do I hardcode some special username/password that automatically gets added to the system if no Admin exists?

答:
what if someone deletes all the users in the SQL table. The passwords
  are hashed so it's not as if the DBA can just go in and add a new user
  with Admin rights.

Well, if someone deletes all the users in the SQL table, you load a backup? Why are they doing such things!?

There are various ways to recover an admin account:

Create a regular user, then connect to the DB directly and mark them as an admin.

Manually run whatever SPs are run when an admin is created.

Create a special page (or special version of the admin pages) which can be run without admin privileges (IP restricted, firewalled, etc.), login, and use them to create an admin.

These various strategies have several things in common:

They require you to be a server admin or DB admin.

They're dangerous and hacky.  You won't want to keep them on and you'll want to make sure regular users can't trigger them.  All such functionality should be deleted (not merely disabled) by default.

They're bypassing authentication, but are otherwise leveraging your existing code.

You don't need to code them until the problem actually happens (and in fact, should not do so; unmaintained hacks tend to become obsolete quickly).


问:
How does Google store its PageRank matrix?
I'm curious to know how Google stores the matrix that's used in the PageRank algorithm; and am looking for a data-structure for storing a very-large (not fitting in memory of any one computer) sparse matrix, and efficiently (not sure what that means yet) performing operations on it.

If there's a white-paper available please post a link or a title (I've done some research, and couldn't find one), and if not, it would be great if you could post links or just names of papers or books that would help get me started.

In my initial research I found the sparse row-wise format [1], and I started reading Sparse Matrix Technology [2]; so please let me if I'm on the right track here.

[1] Chang, 1969 Curtis and Reid, 1971 Gustavson, 1972

[2] Pissanetzky, 1984

答:
It really depends on the scale you have in mind. Sparse matrices will only take you that far... For Google and similar very large scale applications, think more along the line of distributed databases.

Just to mention, there are indeed several papers available (via Google Scholar, say) that discuss Google's approach to distributed storage (BigTable), or Amazon's (SimpleDB), etc. There is also an open source system called Hypertable, which can run on top of Apache Hadoop for instance.

If you're really interested in sparse matrices, I think Davis (2006) is a very decent text, and very up-to-date. The book also includes the CSparse package, ready to use. (I don't have direct experience with it so I cannot comment on scalability...) Note that the author's personal web site lists other packages and resources, as well, such as SuiteSparse.


问:
What is the benefit of Continuous Integration over make?
We are evaluating and setting up Continuous Integration for our PHP project. Each of the Continuous Integration tools has their own proprietary "build language" which will run many commands and check the return status of these commands.

Here is an example of a .travis.yml configuration:

```<code>language: php

php:
  - "5.3"
  - "5.4"
  - "5.5"

script: phpunit test

notifications:
  email:
    - sourcespeak@phor.net
</code>```

A Jenkins configuration will be in XML and is too long to paste here.

Here is an example of a circle.yml configuration:

```<code>dependencies:
  override:
    - bundle install:
        timeout: 240
        environment:
          foo: bar
          foo2: bar2
        pwd:
          test_dir
</code>```

My question is: what is the benefit of using all these popular, proprietary configurations languages for CI instead of using a Makefile to set up your test environment and have whatever CI server just run make test?

答:
What proprietary "build language" in Jenkins? Saying that Jenkins's "build language" is an XML file is like saying your makefile's "build language" is machine code. Not quite, but the gist is the same.

You need not concern yourself with how Jenkins stores it's configuration no more than you would concern yourself with the resultant machine code after your makefile runs. You will never be modifying Jenkins's XML by hand.

Jenkins is a web-based GUI (with cli and web APIs to complete it). The "build language" of Jenkins is whatever you want, from Maven to Ant to Shell and many more in between. It is further augmented with a multitude of plugins that allow you to customize the build flow just as you want it.

And at the end of the day, in Jenkins, your build step will be "Execute Shell" where you will write make test just like you did on command line. The benefits of Jenkins is not executing your build (any scheduler can do that), but organizing and putting everything together, and keeping it accessible to your team through the web.

I can go on listing all the great things that Jenkins will keep track of for you (SCM changes, console logs, test results, artifacts, emails, etc, etc), but you will get a far better overview from any Google search on the benefits/features of Jenkins.

Late edit:

A more elaborate answer on the topic

OwnerDisplayName: Full Decent


问:
How Do You Determine Your Hourly Rate?
In pricing a service or product it is general practice to not merely charge for the effort spent and the costs involved + margin but from the value delivered down. As an independent consultant, how do you set the price of your work?

What is the process of determining your hourly rate as an independent software developer? If you have one, what is your hourly rate and how did you arrive at that figure?

What factors would you take into account.  Is the process of setting a hourly rate only based on balancing demand with supply so that supply (you and your time) doesn't get overwhelmed?

When are the good times to raise your rates?

Are there projects in which you have had to charge higher than other projects? If so, please cite examples.

Do you change your hourly rate based on what kind of development you are doing? (for example, .net programming more, and lesser for php programming)

Do you set hourly rates based on what type of business the client is? If so how?

If you know of any relevant articles or material on the topic of charging for programming services, please post the same.

答:
In pricing a service or product it is
  general practice to not merely charge
  for the effort spent and the costs
  involved + margin but from the value
  delivered down. As an independent
  consultant, how do you set the price
  of your work?

A combination of the above + what the market will take.  Some further answers below.

What is the process of determining
  your hourly rate as an independent
  software developer? If you have one,
  what is your hourly rate and how did
  you arrive at that figure?

I actually have a daily rate.  I start at the market rate for a senior Java developer and then added 'chunks' to that rate based on my unique selling points for a particular client if they are relevant.  So for one client my experience in open source community management is a bonus, another client values my contacts in the Java community as a whole (I co-lead the JUG in London) etc.  I also factor who the client is and what sector they are in (financials will pay more if you have relevant business experience for example).

Supply and demand also come into it, as does the length of contract.

What factors would you take into
  account. Is the process of setting a
  hourly rate only based on balancing
  demand with supply so that supply (you
  and your time) doesn't get
  overwhelmed?

No it's not just based on that one factor, it's one of many factors.

When is it a good time to raise your
  rates?

When you have demonstrated over a length of time that you are worth more than your original rate and the market/client can afford it.  Remember as a contractor/consultant they expect to see real value for money, it helps to be able to track your work to a tangible saving/revenue/profit.

Do you change your hourly rate based
  on what kind of development you are
  doing? (for example, .net programming
  more, and lesser for php programming)

Yes, the market will pay differently for different skill sets.

Do you set hourly rates based on what
  type of business the client is? If so
  how?

Yes, as above, investment banks and the like do pay more - but they expect more as well, if you don't deliver you're soon out the door :)

HTH!

Title: How Do You Determine Your Hourly Rate?


答:
What I meant to ask was if a certain algorithm could run faster, because it is executed in an environment that can run at O(log n). I've also updated my question to not imply a better time complexity, just running faster. I think your logic might be a little flawed.

Even if HashLife is O(log n) and Turing Complete, there's no guarantee that a program you write in it's "programming language" is going to run any faster.  The most likely possibility is that it will run slower, because HashLife is optimized for Conway's Game of Life, not general computing algorithms.

Title: What are the consequences of Hash-Life running in O(log n)?

Body:
After reading about the HashLife algorithm, I found that it runs in O(log n). The Game of Life is also Turing Complete, so in theory we should be able to run any algorithm on a "computer" constructed in GoL.

As a consequence of HashLife's time complexity, could algorithms run faster? e.g. if an algorithm takes 10 seconds to run on a pc, could it run faster in HashLife on that same pc?

An example: An algorithm running takes a 1000 instructions to run. A certain computer can process 1 instruction per second. So that algorithm takes a 1000 seconds to run.

Now, if we take that same algorithm and run it on the "computer" in GoL. It would, because of HashLife being O(log n) take 3 seconds? (assuming O(log₁₀n))

I'm probably overlooking something, since this would be a very important discovery, but I still thought I'd ask about it here.


问:
What data structure is suitable for implementing dynamic huffman encoding and decoding on a piece of text?
Some pseudo code or resources will be appreciated.I was thinking if implementing it in form of a BST stored in an array. However,not all operations can be performed easily using this approach. I am open to using STL's for this purpose as well.My main purpose is to implement it in the simplest manner possible.</p>

答: My understanding of adaptive Huffman coding is that its implementation requires a weighted tree, and then weights are being operated on, so a standard binary tree, or binary search tree, or a heap, cannot be used 'as is'. In fact, a BST doesn't seem very appropriate, whereas a heap might be a good start, given that (in Vitter's algorithm at least) nodes must be listed in order of decreasing weight, which is reminiscent of a max heap structure... Also, that one set of slides describing implementation details might be useful.


答:
I have just a rule that an admin user cannot unmake themselves an administrator.  So if Joe and Sue are administrators, Sue can make Joe a regular user, but then she's still left and can't make herself not an administrator.  Similarly an administrator can't delete or disable their own account.

Now if the last administrator forgets their password, that's a problem.

Title: How to handle or prevent all Admins and users being removed

Body:
I have a website that stores all users in a database. A user can log on to the website and if they have sufficient privileges can add/delete users, as well as change their privileges.

How do I ensure there is always at least one Administrator (to create/edit/delete users) in the system or that an administrator can easily be added to the system.

Surely I can put rules in place so that the Admin can't delete himself, or other rules like that. But what if someone deletes all the users in the SQL table. The passwords are hashed so it's not as if the DBA can just go in and add a new user with Admin rights.

Do I hardcode some special username/password that automatically gets added to the system if no Admin exists?


答:
So, you're wondering how to prevent a user of your Application from deleting all of the Application Users, which are stored in your database on a simple Users table?

Implement the exact same strategy you would use for any other data-shape requirement.  Assuming you don't have a framework that can do it better, you could add a whole-table constraint on Users to require there to be at least one Admin user, like follows:

```<code>ALTER TABLE Users
ADD CONSTRAINT Chk_MinOneAdminUser
CHECK (SELECT SUM(Users) WHERE Type = 'Admin') > 0
</code>```

(Assuming you are using SQL Server, don't mix multiple apps in the same database, don't have replication issues to worry about, can stand the performance hit of an additional select on all users for each table update, and can't think of something better.)

Body:
So, you're wondering how to prevent a user of your Application from deleting all of the Application Users, which are stored in your database on a simple Users table?

Implement the exact same strategy you would use for any other data-shape requirement.  Assuming you don't have a framework that can do it better, you could add a whole-table constraint on Users to require there to be at least one Admin user, like follows:

ALTER TABLE Users
ADD CONSTRAINT Chk_MinOneAdminUser
CHECK (SELECT SUM(Users) WHERE Type = 'Admin') > 0

(Assuming you are using SQL Server, don't mix multiple apps in the same database, don't have replication issues to worry about, can stand the performance hit of an additional select on all users for each table update, and can't think of something better.)